1/* 2 * apply.c 3 * 4 * Copyright (C) Linus Torvalds, 2005 5 * 6 * This applies patches on top of some (arbitrary) version of the SCM. 7 * 8 */ 9#include"cache.h" 10#include"cache-tree.h" 11#include"quote.h" 12#include"blob.h" 13#include"delta.h" 14#include"builtin.h" 15#include"string-list.h" 16#include"dir.h" 17#include"diff.h" 18#include"parse-options.h" 19 20/* 21 * --check turns on checking that the working tree matches the 22 * files that are being modified, but doesn't apply the patch 23 * --stat does just a diffstat, and doesn't actually apply 24 * --numstat does numeric diffstat, and doesn't actually apply 25 * --index-info shows the old and new index info for paths if available. 26 * --index updates the cache as well. 27 * --cached updates only the cache without ever touching the working tree. 28 */ 29static const char*prefix; 30static int prefix_length = -1; 31static int newfd = -1; 32 33static int unidiff_zero; 34static int p_value =1; 35static int p_value_known; 36static int check_index; 37static int update_index; 38static int cached; 39static int diffstat; 40static int numstat; 41static int summary; 42static int check; 43static int apply =1; 44static int apply_in_reverse; 45static int apply_with_reject; 46static int apply_verbosely; 47static int allow_overlap; 48static int no_add; 49static const char*fake_ancestor; 50static int line_termination ='\n'; 51static unsigned int p_context = UINT_MAX; 52static const char*const apply_usage[] = { 53N_("git apply [options] [<patch>...]"), 54 NULL 55}; 56 57static enum ws_error_action { 58 nowarn_ws_error, 59 warn_on_ws_error, 60 die_on_ws_error, 61 correct_ws_error 62} ws_error_action = warn_on_ws_error; 63static int whitespace_error; 64static int squelch_whitespace_errors =5; 65static int applied_after_fixing_ws; 66 67static enum ws_ignore { 68 ignore_ws_none, 69 ignore_ws_change 70} ws_ignore_action = ignore_ws_none; 71 72 73static const char*patch_input_file; 74static const char*root; 75static int root_len; 76static int read_stdin =1; 77static int options; 78 79static voidparse_whitespace_option(const char*option) 80{ 81if(!option) { 82 ws_error_action = warn_on_ws_error; 83return; 84} 85if(!strcmp(option,"warn")) { 86 ws_error_action = warn_on_ws_error; 87return; 88} 89if(!strcmp(option,"nowarn")) { 90 ws_error_action = nowarn_ws_error; 91return; 92} 93if(!strcmp(option,"error")) { 94 ws_error_action = die_on_ws_error; 95return; 96} 97if(!strcmp(option,"error-all")) { 98 ws_error_action = die_on_ws_error; 99 squelch_whitespace_errors =0; 100return; 101} 102if(!strcmp(option,"strip") || !strcmp(option,"fix")) { 103 ws_error_action = correct_ws_error; 104return; 105} 106die(_("unrecognized whitespace option '%s'"), option); 107} 108 109static voidparse_ignorewhitespace_option(const char*option) 110{ 111if(!option || !strcmp(option,"no") || 112!strcmp(option,"false") || !strcmp(option,"never") || 113!strcmp(option,"none")) { 114 ws_ignore_action = ignore_ws_none; 115return; 116} 117if(!strcmp(option,"change")) { 118 ws_ignore_action = ignore_ws_change; 119return; 120} 121die(_("unrecognized whitespace ignore option '%s'"), option); 122} 123 124static voidset_default_whitespace_mode(const char*whitespace_option) 125{ 126if(!whitespace_option && !apply_default_whitespace) 127 ws_error_action = (apply ? warn_on_ws_error : nowarn_ws_error); 128} 129 130/* 131 * For "diff-stat" like behaviour, we keep track of the biggest change 132 * we've seen, and the longest filename. That allows us to do simple 133 * scaling. 134 */ 135static int max_change, max_len; 136 137/* 138 * Various "current state", notably line numbers and what 139 * file (and how) we're patching right now.. The "is_xxxx" 140 * things are flags, where -1 means "don't know yet". 141 */ 142static int linenr =1; 143 144/* 145 * This represents one "hunk" from a patch, starting with 146 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The 147 * patch text is pointed at by patch, and its byte length 148 * is stored in size. leading and trailing are the number 149 * of context lines. 150 */ 151struct fragment { 152unsigned long leading, trailing; 153unsigned long oldpos, oldlines; 154unsigned long newpos, newlines; 155/* 156 * 'patch' is usually borrowed from buf in apply_patch(), 157 * but some codepaths store an allocated buffer. 158 */ 159const char*patch; 160unsigned free_patch:1, 161 rejected:1; 162int size; 163int linenr; 164struct fragment *next; 165}; 166 167/* 168 * When dealing with a binary patch, we reuse "leading" field 169 * to store the type of the binary hunk, either deflated "delta" 170 * or deflated "literal". 171 */ 172#define binary_patch_method leading 173#define BINARY_DELTA_DEFLATED 1 174#define BINARY_LITERAL_DEFLATED 2 175 176/* 177 * This represents a "patch" to a file, both metainfo changes 178 * such as creation/deletion, filemode and content changes represented 179 * as a series of fragments. 180 */ 181struct patch { 182char*new_name, *old_name, *def_name; 183unsigned int old_mode, new_mode; 184int is_new, is_delete;/* -1 = unknown, 0 = false, 1 = true */ 185int rejected; 186unsigned ws_rule; 187int lines_added, lines_deleted; 188int score; 189unsigned int is_toplevel_relative:1; 190unsigned int inaccurate_eof:1; 191unsigned int is_binary:1; 192unsigned int is_copy:1; 193unsigned int is_rename:1; 194unsigned int recount:1; 195struct fragment *fragments; 196char*result; 197size_t resultsize; 198char old_sha1_prefix[41]; 199char new_sha1_prefix[41]; 200struct patch *next; 201}; 202 203static voidfree_fragment_list(struct fragment *list) 204{ 205while(list) { 206struct fragment *next = list->next; 207if(list->free_patch) 208free((char*)list->patch); 209free(list); 210 list = next; 211} 212} 213 214static voidfree_patch(struct patch *patch) 215{ 216free_fragment_list(patch->fragments); 217free(patch->def_name); 218free(patch->old_name); 219free(patch->new_name); 220free(patch->result); 221free(patch); 222} 223 224static voidfree_patch_list(struct patch *list) 225{ 226while(list) { 227struct patch *next = list->next; 228free_patch(list); 229 list = next; 230} 231} 232 233/* 234 * A line in a file, len-bytes long (includes the terminating LF, 235 * except for an incomplete line at the end if the file ends with 236 * one), and its contents hashes to 'hash'. 237 */ 238struct line { 239size_t len; 240unsigned hash :24; 241unsigned flag :8; 242#define LINE_COMMON 1 243#define LINE_PATCHED 2 244}; 245 246/* 247 * This represents a "file", which is an array of "lines". 248 */ 249struct image { 250char*buf; 251size_t len; 252size_t nr; 253size_t alloc; 254struct line *line_allocated; 255struct line *line; 256}; 257 258/* 259 * Records filenames that have been touched, in order to handle 260 * the case where more than one patches touch the same file. 261 */ 262 263static struct string_list fn_table; 264 265static uint32_thash_line(const char*cp,size_t len) 266{ 267size_t i; 268uint32_t h; 269for(i =0, h =0; i < len; i++) { 270if(!isspace(cp[i])) { 271 h = h *3+ (cp[i] &0xff); 272} 273} 274return h; 275} 276 277/* 278 * Compare lines s1 of length n1 and s2 of length n2, ignoring 279 * whitespace difference. Returns 1 if they match, 0 otherwise 280 */ 281static intfuzzy_matchlines(const char*s1,size_t n1, 282const char*s2,size_t n2) 283{ 284const char*last1 = s1 + n1 -1; 285const char*last2 = s2 + n2 -1; 286int result =0; 287 288/* ignore line endings */ 289while((*last1 =='\r') || (*last1 =='\n')) 290 last1--; 291while((*last2 =='\r') || (*last2 =='\n')) 292 last2--; 293 294/* skip leading whitespace */ 295while(isspace(*s1) && (s1 <= last1)) 296 s1++; 297while(isspace(*s2) && (s2 <= last2)) 298 s2++; 299/* early return if both lines are empty */ 300if((s1 > last1) && (s2 > last2)) 301return1; 302while(!result) { 303 result = *s1++ - *s2++; 304/* 305 * Skip whitespace inside. We check for whitespace on 306 * both buffers because we don't want "a b" to match 307 * "ab" 308 */ 309if(isspace(*s1) &&isspace(*s2)) { 310while(isspace(*s1) && s1 <= last1) 311 s1++; 312while(isspace(*s2) && s2 <= last2) 313 s2++; 314} 315/* 316 * If we reached the end on one side only, 317 * lines don't match 318 */ 319if( 320((s2 > last2) && (s1 <= last1)) || 321((s1 > last1) && (s2 <= last2))) 322return0; 323if((s1 > last1) && (s2 > last2)) 324break; 325} 326 327return!result; 328} 329 330static voidadd_line_info(struct image *img,const char*bol,size_t len,unsigned flag) 331{ 332ALLOC_GROW(img->line_allocated, img->nr +1, img->alloc); 333 img->line_allocated[img->nr].len = len; 334 img->line_allocated[img->nr].hash =hash_line(bol, len); 335 img->line_allocated[img->nr].flag = flag; 336 img->nr++; 337} 338 339/* 340 * "buf" has the file contents to be patched (read from various sources). 341 * attach it to "image" and add line-based index to it. 342 * "image" now owns the "buf". 343 */ 344static voidprepare_image(struct image *image,char*buf,size_t len, 345int prepare_linetable) 346{ 347const char*cp, *ep; 348 349memset(image,0,sizeof(*image)); 350 image->buf = buf; 351 image->len = len; 352 353if(!prepare_linetable) 354return; 355 356 ep = image->buf + image->len; 357 cp = image->buf; 358while(cp < ep) { 359const char*next; 360for(next = cp; next < ep && *next !='\n'; next++) 361; 362if(next < ep) 363 next++; 364add_line_info(image, cp, next - cp,0); 365 cp = next; 366} 367 image->line = image->line_allocated; 368} 369 370static voidclear_image(struct image *image) 371{ 372free(image->buf); 373 image->buf = NULL; 374 image->len =0; 375} 376 377/* fmt must contain _one_ %s and no other substitution */ 378static voidsay_patch_name(FILE*output,const char*fmt,struct patch *patch) 379{ 380struct strbuf sb = STRBUF_INIT; 381 382if(patch->old_name && patch->new_name && 383strcmp(patch->old_name, patch->new_name)) { 384quote_c_style(patch->old_name, &sb, NULL,0); 385strbuf_addstr(&sb," => "); 386quote_c_style(patch->new_name, &sb, NULL,0); 387}else{ 388const char*n = patch->new_name; 389if(!n) 390 n = patch->old_name; 391quote_c_style(n, &sb, NULL,0); 392} 393fprintf(output, fmt, sb.buf); 394fputc('\n', output); 395strbuf_release(&sb); 396} 397 398#define SLOP (16) 399 400static voidread_patch_file(struct strbuf *sb,int fd) 401{ 402if(strbuf_read(sb, fd,0) <0) 403die_errno("git apply: failed to read"); 404 405/* 406 * Make sure that we have some slop in the buffer 407 * so that we can do speculative "memcmp" etc, and 408 * see to it that it is NUL-filled. 409 */ 410strbuf_grow(sb, SLOP); 411memset(sb->buf + sb->len,0, SLOP); 412} 413 414static unsigned longlinelen(const char*buffer,unsigned long size) 415{ 416unsigned long len =0; 417while(size--) { 418 len++; 419if(*buffer++ =='\n') 420break; 421} 422return len; 423} 424 425static intis_dev_null(const char*str) 426{ 427return!memcmp("/dev/null", str,9) &&isspace(str[9]); 428} 429 430#define TERM_SPACE 1 431#define TERM_TAB 2 432 433static intname_terminate(const char*name,int namelen,int c,int terminate) 434{ 435if(c ==' '&& !(terminate & TERM_SPACE)) 436return0; 437if(c =='\t'&& !(terminate & TERM_TAB)) 438return0; 439 440return1; 441} 442 443/* remove double slashes to make --index work with such filenames */ 444static char*squash_slash(char*name) 445{ 446int i =0, j =0; 447 448if(!name) 449return NULL; 450 451while(name[i]) { 452if((name[j++] = name[i++]) =='/') 453while(name[i] =='/') 454 i++; 455} 456 name[j] ='\0'; 457return name; 458} 459 460static char*find_name_gnu(const char*line,const char*def,int p_value) 461{ 462struct strbuf name = STRBUF_INIT; 463char*cp; 464 465/* 466 * Proposed "new-style" GNU patch/diff format; see 467 * http://marc.theaimsgroup.com/?l=git&m=112927316408690&w=2 468 */ 469if(unquote_c_style(&name, line, NULL)) { 470strbuf_release(&name); 471return NULL; 472} 473 474for(cp = name.buf; p_value; p_value--) { 475 cp =strchr(cp,'/'); 476if(!cp) { 477strbuf_release(&name); 478return NULL; 479} 480 cp++; 481} 482 483strbuf_remove(&name,0, cp - name.buf); 484if(root) 485strbuf_insert(&name,0, root, root_len); 486returnsquash_slash(strbuf_detach(&name, NULL)); 487} 488 489static size_tsane_tz_len(const char*line,size_t len) 490{ 491const char*tz, *p; 492 493if(len <strlen(" +0500") || line[len-strlen(" +0500")] !=' ') 494return0; 495 tz = line + len -strlen(" +0500"); 496 497if(tz[1] !='+'&& tz[1] !='-') 498return0; 499 500for(p = tz +2; p != line + len; p++) 501if(!isdigit(*p)) 502return0; 503 504return line + len - tz; 505} 506 507static size_ttz_with_colon_len(const char*line,size_t len) 508{ 509const char*tz, *p; 510 511if(len <strlen(" +08:00") || line[len -strlen(":00")] !=':') 512return0; 513 tz = line + len -strlen(" +08:00"); 514 515if(tz[0] !=' '|| (tz[1] !='+'&& tz[1] !='-')) 516return0; 517 p = tz +2; 518if(!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 519!isdigit(*p++) || !isdigit(*p++)) 520return0; 521 522return line + len - tz; 523} 524 525static size_tdate_len(const char*line,size_t len) 526{ 527const char*date, *p; 528 529if(len <strlen("72-02-05") || line[len-strlen("-05")] !='-') 530return0; 531 p = date = line + len -strlen("72-02-05"); 532 533if(!isdigit(*p++) || !isdigit(*p++) || *p++ !='-'|| 534!isdigit(*p++) || !isdigit(*p++) || *p++ !='-'|| 535!isdigit(*p++) || !isdigit(*p++))/* Not a date. */ 536return0; 537 538if(date - line >=strlen("19") && 539isdigit(date[-1]) &&isdigit(date[-2]))/* 4-digit year */ 540 date -=strlen("19"); 541 542return line + len - date; 543} 544 545static size_tshort_time_len(const char*line,size_t len) 546{ 547const char*time, *p; 548 549if(len <strlen(" 07:01:32") || line[len-strlen(":32")] !=':') 550return0; 551 p = time = line + len -strlen(" 07:01:32"); 552 553/* Permit 1-digit hours? */ 554if(*p++ !=' '|| 555!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 556!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 557!isdigit(*p++) || !isdigit(*p++))/* Not a time. */ 558return0; 559 560return line + len - time; 561} 562 563static size_tfractional_time_len(const char*line,size_t len) 564{ 565const char*p; 566size_t n; 567 568/* Expected format: 19:41:17.620000023 */ 569if(!len || !isdigit(line[len -1])) 570return0; 571 p = line + len -1; 572 573/* Fractional seconds. */ 574while(p > line &&isdigit(*p)) 575 p--; 576if(*p !='.') 577return0; 578 579/* Hours, minutes, and whole seconds. */ 580 n =short_time_len(line, p - line); 581if(!n) 582return0; 583 584return line + len - p + n; 585} 586 587static size_ttrailing_spaces_len(const char*line,size_t len) 588{ 589const char*p; 590 591/* Expected format: ' ' x (1 or more) */ 592if(!len || line[len -1] !=' ') 593return0; 594 595 p = line + len; 596while(p != line) { 597 p--; 598if(*p !=' ') 599return line + len - (p +1); 600} 601 602/* All spaces! */ 603return len; 604} 605 606static size_tdiff_timestamp_len(const char*line,size_t len) 607{ 608const char*end = line + len; 609size_t n; 610 611/* 612 * Posix: 2010-07-05 19:41:17 613 * GNU: 2010-07-05 19:41:17.620000023 -0500 614 */ 615 616if(!isdigit(end[-1])) 617return0; 618 619 n =sane_tz_len(line, end - line); 620if(!n) 621 n =tz_with_colon_len(line, end - line); 622 end -= n; 623 624 n =short_time_len(line, end - line); 625if(!n) 626 n =fractional_time_len(line, end - line); 627 end -= n; 628 629 n =date_len(line, end - line); 630if(!n)/* No date. Too bad. */ 631return0; 632 end -= n; 633 634if(end == line)/* No space before date. */ 635return0; 636if(end[-1] =='\t') {/* Success! */ 637 end--; 638return line + len - end; 639} 640if(end[-1] !=' ')/* No space before date. */ 641return0; 642 643/* Whitespace damage. */ 644 end -=trailing_spaces_len(line, end - line); 645return line + len - end; 646} 647 648static char*null_strdup(const char*s) 649{ 650return s ?xstrdup(s) : NULL; 651} 652 653static char*find_name_common(const char*line,const char*def, 654int p_value,const char*end,int terminate) 655{ 656int len; 657const char*start = NULL; 658 659if(p_value ==0) 660 start = line; 661while(line != end) { 662char c = *line; 663 664if(!end &&isspace(c)) { 665if(c =='\n') 666break; 667if(name_terminate(start, line-start, c, terminate)) 668break; 669} 670 line++; 671if(c =='/'&& !--p_value) 672 start = line; 673} 674if(!start) 675returnsquash_slash(null_strdup(def)); 676 len = line - start; 677if(!len) 678returnsquash_slash(null_strdup(def)); 679 680/* 681 * Generally we prefer the shorter name, especially 682 * if the other one is just a variation of that with 683 * something else tacked on to the end (ie "file.orig" 684 * or "file~"). 685 */ 686if(def) { 687int deflen =strlen(def); 688if(deflen < len && !strncmp(start, def, deflen)) 689returnsquash_slash(xstrdup(def)); 690} 691 692if(root) { 693char*ret =xmalloc(root_len + len +1); 694strcpy(ret, root); 695memcpy(ret + root_len, start, len); 696 ret[root_len + len] ='\0'; 697returnsquash_slash(ret); 698} 699 700returnsquash_slash(xmemdupz(start, len)); 701} 702 703static char*find_name(const char*line,char*def,int p_value,int terminate) 704{ 705if(*line =='"') { 706char*name =find_name_gnu(line, def, p_value); 707if(name) 708return name; 709} 710 711returnfind_name_common(line, def, p_value, NULL, terminate); 712} 713 714static char*find_name_traditional(const char*line,char*def,int p_value) 715{ 716size_t len =strlen(line); 717size_t date_len; 718 719if(*line =='"') { 720char*name =find_name_gnu(line, def, p_value); 721if(name) 722return name; 723} 724 725 len =strchrnul(line,'\n') - line; 726 date_len =diff_timestamp_len(line, len); 727if(!date_len) 728returnfind_name_common(line, def, p_value, NULL, TERM_TAB); 729 len -= date_len; 730 731returnfind_name_common(line, def, p_value, line + len,0); 732} 733 734static intcount_slashes(const char*cp) 735{ 736int cnt =0; 737char ch; 738 739while((ch = *cp++)) 740if(ch =='/') 741 cnt++; 742return cnt; 743} 744 745/* 746 * Given the string after "--- " or "+++ ", guess the appropriate 747 * p_value for the given patch. 748 */ 749static intguess_p_value(const char*nameline) 750{ 751char*name, *cp; 752int val = -1; 753 754if(is_dev_null(nameline)) 755return-1; 756 name =find_name_traditional(nameline, NULL,0); 757if(!name) 758return-1; 759 cp =strchr(name,'/'); 760if(!cp) 761 val =0; 762else if(prefix) { 763/* 764 * Does it begin with "a/$our-prefix" and such? Then this is 765 * very likely to apply to our directory. 766 */ 767if(!strncmp(name, prefix, prefix_length)) 768 val =count_slashes(prefix); 769else{ 770 cp++; 771if(!strncmp(cp, prefix, prefix_length)) 772 val =count_slashes(prefix) +1; 773} 774} 775free(name); 776return val; 777} 778 779/* 780 * Does the ---/+++ line has the POSIX timestamp after the last HT? 781 * GNU diff puts epoch there to signal a creation/deletion event. Is 782 * this such a timestamp? 783 */ 784static inthas_epoch_timestamp(const char*nameline) 785{ 786/* 787 * We are only interested in epoch timestamp; any non-zero 788 * fraction cannot be one, hence "(\.0+)?" in the regexp below. 789 * For the same reason, the date must be either 1969-12-31 or 790 * 1970-01-01, and the seconds part must be "00". 791 */ 792const char stamp_regexp[] = 793"^(1969-12-31|1970-01-01)" 794" " 795"[0-2][0-9]:[0-5][0-9]:00(\\.0+)?" 796" " 797"([-+][0-2][0-9]:?[0-5][0-9])\n"; 798const char*timestamp = NULL, *cp, *colon; 799static regex_t *stamp; 800 regmatch_t m[10]; 801int zoneoffset; 802int hourminute; 803int status; 804 805for(cp = nameline; *cp !='\n'; cp++) { 806if(*cp =='\t') 807 timestamp = cp +1; 808} 809if(!timestamp) 810return0; 811if(!stamp) { 812 stamp =xmalloc(sizeof(*stamp)); 813if(regcomp(stamp, stamp_regexp, REG_EXTENDED)) { 814warning(_("Cannot prepare timestamp regexp%s"), 815 stamp_regexp); 816return0; 817} 818} 819 820 status =regexec(stamp, timestamp,ARRAY_SIZE(m), m,0); 821if(status) { 822if(status != REG_NOMATCH) 823warning(_("regexec returned%dfor input:%s"), 824 status, timestamp); 825return0; 826} 827 828 zoneoffset =strtol(timestamp + m[3].rm_so +1, (char**) &colon,10); 829if(*colon ==':') 830 zoneoffset = zoneoffset *60+strtol(colon +1, NULL,10); 831else 832 zoneoffset = (zoneoffset /100) *60+ (zoneoffset %100); 833if(timestamp[m[3].rm_so] =='-') 834 zoneoffset = -zoneoffset; 835 836/* 837 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31 838 * (west of GMT) or 1970-01-01 (east of GMT) 839 */ 840if((zoneoffset <0&&memcmp(timestamp,"1969-12-31",10)) || 841(0<= zoneoffset &&memcmp(timestamp,"1970-01-01",10))) 842return0; 843 844 hourminute = (strtol(timestamp +11, NULL,10) *60+ 845strtol(timestamp +14, NULL,10) - 846 zoneoffset); 847 848return((zoneoffset <0&& hourminute ==1440) || 849(0<= zoneoffset && !hourminute)); 850} 851 852/* 853 * Get the name etc info from the ---/+++ lines of a traditional patch header 854 * 855 * FIXME! The end-of-filename heuristics are kind of screwy. For existing 856 * files, we can happily check the index for a match, but for creating a 857 * new file we should try to match whatever "patch" does. I have no idea. 858 */ 859static voidparse_traditional_patch(const char*first,const char*second,struct patch *patch) 860{ 861char*name; 862 863 first +=4;/* skip "--- " */ 864 second +=4;/* skip "+++ " */ 865if(!p_value_known) { 866int p, q; 867 p =guess_p_value(first); 868 q =guess_p_value(second); 869if(p <0) p = q; 870if(0<= p && p == q) { 871 p_value = p; 872 p_value_known =1; 873} 874} 875if(is_dev_null(first)) { 876 patch->is_new =1; 877 patch->is_delete =0; 878 name =find_name_traditional(second, NULL, p_value); 879 patch->new_name = name; 880}else if(is_dev_null(second)) { 881 patch->is_new =0; 882 patch->is_delete =1; 883 name =find_name_traditional(first, NULL, p_value); 884 patch->old_name = name; 885}else{ 886char*first_name; 887 first_name =find_name_traditional(first, NULL, p_value); 888 name =find_name_traditional(second, first_name, p_value); 889free(first_name); 890if(has_epoch_timestamp(first)) { 891 patch->is_new =1; 892 patch->is_delete =0; 893 patch->new_name = name; 894}else if(has_epoch_timestamp(second)) { 895 patch->is_new =0; 896 patch->is_delete =1; 897 patch->old_name = name; 898}else{ 899 patch->old_name = name; 900 patch->new_name =xstrdup(name); 901} 902} 903if(!name) 904die(_("unable to find filename in patch at line%d"), linenr); 905} 906 907static intgitdiff_hdrend(const char*line,struct patch *patch) 908{ 909return-1; 910} 911 912/* 913 * We're anal about diff header consistency, to make 914 * sure that we don't end up having strange ambiguous 915 * patches floating around. 916 * 917 * As a result, gitdiff_{old|new}name() will check 918 * their names against any previous information, just 919 * to make sure.. 920 */ 921#define DIFF_OLD_NAME 0 922#define DIFF_NEW_NAME 1 923 924static char*gitdiff_verify_name(const char*line,int isnull,char*orig_name,int side) 925{ 926if(!orig_name && !isnull) 927returnfind_name(line, NULL, p_value, TERM_TAB); 928 929if(orig_name) { 930int len; 931const char*name; 932char*another; 933 name = orig_name; 934 len =strlen(name); 935if(isnull) 936die(_("git apply: bad git-diff - expected /dev/null, got%son line%d"), name, linenr); 937 another =find_name(line, NULL, p_value, TERM_TAB); 938if(!another ||memcmp(another, name, len +1)) 939die((side == DIFF_NEW_NAME) ? 940_("git apply: bad git-diff - inconsistent new filename on line%d") : 941_("git apply: bad git-diff - inconsistent old filename on line%d"), linenr); 942free(another); 943return orig_name; 944} 945else{ 946/* expect "/dev/null" */ 947if(memcmp("/dev/null", line,9) || line[9] !='\n') 948die(_("git apply: bad git-diff - expected /dev/null on line%d"), linenr); 949return NULL; 950} 951} 952 953static intgitdiff_oldname(const char*line,struct patch *patch) 954{ 955char*orig = patch->old_name; 956 patch->old_name =gitdiff_verify_name(line, patch->is_new, patch->old_name, 957 DIFF_OLD_NAME); 958if(orig != patch->old_name) 959free(orig); 960return0; 961} 962 963static intgitdiff_newname(const char*line,struct patch *patch) 964{ 965char*orig = patch->new_name; 966 patch->new_name =gitdiff_verify_name(line, patch->is_delete, patch->new_name, 967 DIFF_NEW_NAME); 968if(orig != patch->new_name) 969free(orig); 970return0; 971} 972 973static intgitdiff_oldmode(const char*line,struct patch *patch) 974{ 975 patch->old_mode =strtoul(line, NULL,8); 976return0; 977} 978 979static intgitdiff_newmode(const char*line,struct patch *patch) 980{ 981 patch->new_mode =strtoul(line, NULL,8); 982return0; 983} 984 985static intgitdiff_delete(const char*line,struct patch *patch) 986{ 987 patch->is_delete =1; 988free(patch->old_name); 989 patch->old_name =null_strdup(patch->def_name); 990returngitdiff_oldmode(line, patch); 991} 992 993static intgitdiff_newfile(const char*line,struct patch *patch) 994{ 995 patch->is_new =1; 996free(patch->new_name); 997 patch->new_name =null_strdup(patch->def_name); 998returngitdiff_newmode(line, patch); 999}10001001static intgitdiff_copysrc(const char*line,struct patch *patch)1002{1003 patch->is_copy =1;1004free(patch->old_name);1005 patch->old_name =find_name(line, NULL, p_value ? p_value -1:0,0);1006return0;1007}10081009static intgitdiff_copydst(const char*line,struct patch *patch)1010{1011 patch->is_copy =1;1012free(patch->new_name);1013 patch->new_name =find_name(line, NULL, p_value ? p_value -1:0,0);1014return0;1015}10161017static intgitdiff_renamesrc(const char*line,struct patch *patch)1018{1019 patch->is_rename =1;1020free(patch->old_name);1021 patch->old_name =find_name(line, NULL, p_value ? p_value -1:0,0);1022return0;1023}10241025static intgitdiff_renamedst(const char*line,struct patch *patch)1026{1027 patch->is_rename =1;1028free(patch->new_name);1029 patch->new_name =find_name(line, NULL, p_value ? p_value -1:0,0);1030return0;1031}10321033static intgitdiff_similarity(const char*line,struct patch *patch)1034{1035if((patch->score =strtoul(line, NULL,10)) == ULONG_MAX)1036 patch->score =0;1037return0;1038}10391040static intgitdiff_dissimilarity(const char*line,struct patch *patch)1041{1042if((patch->score =strtoul(line, NULL,10)) == ULONG_MAX)1043 patch->score =0;1044return0;1045}10461047static intgitdiff_index(const char*line,struct patch *patch)1048{1049/*1050 * index line is N hexadecimal, "..", N hexadecimal,1051 * and optional space with octal mode.1052 */1053const char*ptr, *eol;1054int len;10551056 ptr =strchr(line,'.');1057if(!ptr || ptr[1] !='.'||40< ptr - line)1058return0;1059 len = ptr - line;1060memcpy(patch->old_sha1_prefix, line, len);1061 patch->old_sha1_prefix[len] =0;10621063 line = ptr +2;1064 ptr =strchr(line,' ');1065 eol =strchr(line,'\n');10661067if(!ptr || eol < ptr)1068 ptr = eol;1069 len = ptr - line;10701071if(40< len)1072return0;1073memcpy(patch->new_sha1_prefix, line, len);1074 patch->new_sha1_prefix[len] =0;1075if(*ptr ==' ')1076 patch->old_mode =strtoul(ptr+1, NULL,8);1077return0;1078}10791080/*1081 * This is normal for a diff that doesn't change anything: we'll fall through1082 * into the next diff. Tell the parser to break out.1083 */1084static intgitdiff_unrecognized(const char*line,struct patch *patch)1085{1086return-1;1087}10881089/*1090 * Skip p_value leading components from "line"; as we do not accept1091 * absolute paths, return NULL in that case.1092 */1093static const char*skip_tree_prefix(const char*line,int llen)1094{1095int nslash;1096int i;10971098if(!p_value)1099return(llen && line[0] =='/') ? NULL : line;11001101 nslash = p_value;1102for(i =0; i < llen; i++) {1103int ch = line[i];1104if(ch =='/'&& --nslash <=0)1105return(i ==0) ? NULL : &line[i +1];1106}1107return NULL;1108}11091110/*1111 * This is to extract the same name that appears on "diff --git"1112 * line. We do not find and return anything if it is a rename1113 * patch, and it is OK because we will find the name elsewhere.1114 * We need to reliably find name only when it is mode-change only,1115 * creation or deletion of an empty file. In any of these cases,1116 * both sides are the same name under a/ and b/ respectively.1117 */1118static char*git_header_name(const char*line,int llen)1119{1120const char*name;1121const char*second = NULL;1122size_t len, line_len;11231124 line +=strlen("diff --git ");1125 llen -=strlen("diff --git ");11261127if(*line =='"') {1128const char*cp;1129struct strbuf first = STRBUF_INIT;1130struct strbuf sp = STRBUF_INIT;11311132if(unquote_c_style(&first, line, &second))1133goto free_and_fail1;11341135/* strip the a/b prefix including trailing slash */1136 cp =skip_tree_prefix(first.buf, first.len);1137if(!cp)1138goto free_and_fail1;1139strbuf_remove(&first,0, cp - first.buf);11401141/*1142 * second points at one past closing dq of name.1143 * find the second name.1144 */1145while((second < line + llen) &&isspace(*second))1146 second++;11471148if(line + llen <= second)1149goto free_and_fail1;1150if(*second =='"') {1151if(unquote_c_style(&sp, second, NULL))1152goto free_and_fail1;1153 cp =skip_tree_prefix(sp.buf, sp.len);1154if(!cp)1155goto free_and_fail1;1156/* They must match, otherwise ignore */1157if(strcmp(cp, first.buf))1158goto free_and_fail1;1159strbuf_release(&sp);1160returnstrbuf_detach(&first, NULL);1161}11621163/* unquoted second */1164 cp =skip_tree_prefix(second, line + llen - second);1165if(!cp)1166goto free_and_fail1;1167if(line + llen - cp != first.len ||1168memcmp(first.buf, cp, first.len))1169goto free_and_fail1;1170returnstrbuf_detach(&first, NULL);11711172 free_and_fail1:1173strbuf_release(&first);1174strbuf_release(&sp);1175return NULL;1176}11771178/* unquoted first name */1179 name =skip_tree_prefix(line, llen);1180if(!name)1181return NULL;11821183/*1184 * since the first name is unquoted, a dq if exists must be1185 * the beginning of the second name.1186 */1187for(second = name; second < line + llen; second++) {1188if(*second =='"') {1189struct strbuf sp = STRBUF_INIT;1190const char*np;11911192if(unquote_c_style(&sp, second, NULL))1193goto free_and_fail2;11941195 np =skip_tree_prefix(sp.buf, sp.len);1196if(!np)1197goto free_and_fail2;11981199 len = sp.buf + sp.len - np;1200if(len < second - name &&1201!strncmp(np, name, len) &&1202isspace(name[len])) {1203/* Good */1204strbuf_remove(&sp,0, np - sp.buf);1205returnstrbuf_detach(&sp, NULL);1206}12071208 free_and_fail2:1209strbuf_release(&sp);1210return NULL;1211}1212}12131214/*1215 * Accept a name only if it shows up twice, exactly the same1216 * form.1217 */1218 second =strchr(name,'\n');1219if(!second)1220return NULL;1221 line_len = second - name;1222for(len =0; ; len++) {1223switch(name[len]) {1224default:1225continue;1226case'\n':1227return NULL;1228case'\t':case' ':1229/*1230 * Is this the separator between the preimage1231 * and the postimage pathname? Again, we are1232 * only interested in the case where there is1233 * no rename, as this is only to set def_name1234 * and a rename patch has the names elsewhere1235 * in an unambiguous form.1236 */1237if(!name[len +1])1238return NULL;/* no postimage name */1239 second =skip_tree_prefix(name + len +1,1240 line_len - (len +1));1241if(!second)1242return NULL;1243/*1244 * Does len bytes starting at "name" and "second"1245 * (that are separated by one HT or SP we just1246 * found) exactly match?1247 */1248if(second[len] =='\n'&& !strncmp(name, second, len))1249returnxmemdupz(name, len);1250}1251}1252}12531254/* Verify that we recognize the lines following a git header */1255static intparse_git_header(const char*line,int len,unsigned int size,struct patch *patch)1256{1257unsigned long offset;12581259/* A git diff has explicit new/delete information, so we don't guess */1260 patch->is_new =0;1261 patch->is_delete =0;12621263/*1264 * Some things may not have the old name in the1265 * rest of the headers anywhere (pure mode changes,1266 * or removing or adding empty files), so we get1267 * the default name from the header.1268 */1269 patch->def_name =git_header_name(line, len);1270if(patch->def_name && root) {1271char*s =xmalloc(root_len +strlen(patch->def_name) +1);1272strcpy(s, root);1273strcpy(s + root_len, patch->def_name);1274free(patch->def_name);1275 patch->def_name = s;1276}12771278 line += len;1279 size -= len;1280 linenr++;1281for(offset = len ; size >0; offset += len, size -= len, line += len, linenr++) {1282static const struct opentry {1283const char*str;1284int(*fn)(const char*,struct patch *);1285} optable[] = {1286{"@@ -", gitdiff_hdrend },1287{"--- ", gitdiff_oldname },1288{"+++ ", gitdiff_newname },1289{"old mode ", gitdiff_oldmode },1290{"new mode ", gitdiff_newmode },1291{"deleted file mode ", gitdiff_delete },1292{"new file mode ", gitdiff_newfile },1293{"copy from ", gitdiff_copysrc },1294{"copy to ", gitdiff_copydst },1295{"rename old ", gitdiff_renamesrc },1296{"rename new ", gitdiff_renamedst },1297{"rename from ", gitdiff_renamesrc },1298{"rename to ", gitdiff_renamedst },1299{"similarity index ", gitdiff_similarity },1300{"dissimilarity index ", gitdiff_dissimilarity },1301{"index ", gitdiff_index },1302{"", gitdiff_unrecognized },1303};1304int i;13051306 len =linelen(line, size);1307if(!len || line[len-1] !='\n')1308break;1309for(i =0; i <ARRAY_SIZE(optable); i++) {1310const struct opentry *p = optable + i;1311int oplen =strlen(p->str);1312if(len < oplen ||memcmp(p->str, line, oplen))1313continue;1314if(p->fn(line + oplen, patch) <0)1315return offset;1316break;1317}1318}13191320return offset;1321}13221323static intparse_num(const char*line,unsigned long*p)1324{1325char*ptr;13261327if(!isdigit(*line))1328return0;1329*p =strtoul(line, &ptr,10);1330return ptr - line;1331}13321333static intparse_range(const char*line,int len,int offset,const char*expect,1334unsigned long*p1,unsigned long*p2)1335{1336int digits, ex;13371338if(offset <0|| offset >= len)1339return-1;1340 line += offset;1341 len -= offset;13421343 digits =parse_num(line, p1);1344if(!digits)1345return-1;13461347 offset += digits;1348 line += digits;1349 len -= digits;13501351*p2 =1;1352if(*line ==',') {1353 digits =parse_num(line+1, p2);1354if(!digits)1355return-1;13561357 offset += digits+1;1358 line += digits+1;1359 len -= digits+1;1360}13611362 ex =strlen(expect);1363if(ex > len)1364return-1;1365if(memcmp(line, expect, ex))1366return-1;13671368return offset + ex;1369}13701371static voidrecount_diff(const char*line,int size,struct fragment *fragment)1372{1373int oldlines =0, newlines =0, ret =0;13741375if(size <1) {1376warning("recount: ignore empty hunk");1377return;1378}13791380for(;;) {1381int len =linelen(line, size);1382 size -= len;1383 line += len;13841385if(size <1)1386break;13871388switch(*line) {1389case' ':case'\n':1390 newlines++;1391/* fall through */1392case'-':1393 oldlines++;1394continue;1395case'+':1396 newlines++;1397continue;1398case'\\':1399continue;1400case'@':1401 ret = size <3||prefixcmp(line,"@@ ");1402break;1403case'd':1404 ret = size <5||prefixcmp(line,"diff ");1405break;1406default:1407 ret = -1;1408break;1409}1410if(ret) {1411warning(_("recount: unexpected line: %.*s"),1412(int)linelen(line, size), line);1413return;1414}1415break;1416}1417 fragment->oldlines = oldlines;1418 fragment->newlines = newlines;1419}14201421/*1422 * Parse a unified diff fragment header of the1423 * form "@@ -a,b +c,d @@"1424 */1425static intparse_fragment_header(const char*line,int len,struct fragment *fragment)1426{1427int offset;14281429if(!len || line[len-1] !='\n')1430return-1;14311432/* Figure out the number of lines in a fragment */1433 offset =parse_range(line, len,4," +", &fragment->oldpos, &fragment->oldlines);1434 offset =parse_range(line, len, offset," @@", &fragment->newpos, &fragment->newlines);14351436return offset;1437}14381439static intfind_header(const char*line,unsigned long size,int*hdrsize,struct patch *patch)1440{1441unsigned long offset, len;14421443 patch->is_toplevel_relative =0;1444 patch->is_rename = patch->is_copy =0;1445 patch->is_new = patch->is_delete = -1;1446 patch->old_mode = patch->new_mode =0;1447 patch->old_name = patch->new_name = NULL;1448for(offset =0; size >0; offset += len, size -= len, line += len, linenr++) {1449unsigned long nextlen;14501451 len =linelen(line, size);1452if(!len)1453break;14541455/* Testing this early allows us to take a few shortcuts.. */1456if(len <6)1457continue;14581459/*1460 * Make sure we don't find any unconnected patch fragments.1461 * That's a sign that we didn't find a header, and that a1462 * patch has become corrupted/broken up.1463 */1464if(!memcmp("@@ -", line,4)) {1465struct fragment dummy;1466if(parse_fragment_header(line, len, &dummy) <0)1467continue;1468die(_("patch fragment without header at line%d: %.*s"),1469 linenr, (int)len-1, line);1470}14711472if(size < len +6)1473break;14741475/*1476 * Git patch? It might not have a real patch, just a rename1477 * or mode change, so we handle that specially1478 */1479if(!memcmp("diff --git ", line,11)) {1480int git_hdr_len =parse_git_header(line, len, size, patch);1481if(git_hdr_len <= len)1482continue;1483if(!patch->old_name && !patch->new_name) {1484if(!patch->def_name)1485die(Q_("git diff header lacks filename information when removing "1486"%dleading pathname component (line%d)",1487"git diff header lacks filename information when removing "1488"%dleading pathname components (line%d)",1489 p_value),1490 p_value, linenr);1491 patch->old_name =xstrdup(patch->def_name);1492 patch->new_name =xstrdup(patch->def_name);1493}1494if(!patch->is_delete && !patch->new_name)1495die("git diff header lacks filename information "1496"(line%d)", linenr);1497 patch->is_toplevel_relative =1;1498*hdrsize = git_hdr_len;1499return offset;1500}15011502/* --- followed by +++ ? */1503if(memcmp("--- ", line,4) ||memcmp("+++ ", line + len,4))1504continue;15051506/*1507 * We only accept unified patches, so we want it to1508 * at least have "@@ -a,b +c,d @@\n", which is 14 chars1509 * minimum ("@@ -0,0 +1 @@\n" is the shortest).1510 */1511 nextlen =linelen(line + len, size - len);1512if(size < nextlen +14||memcmp("@@ -", line + len + nextlen,4))1513continue;15141515/* Ok, we'll consider it a patch */1516parse_traditional_patch(line, line+len, patch);1517*hdrsize = len + nextlen;1518 linenr +=2;1519return offset;1520}1521return-1;1522}15231524static voidrecord_ws_error(unsigned result,const char*line,int len,int linenr)1525{1526char*err;15271528if(!result)1529return;15301531 whitespace_error++;1532if(squelch_whitespace_errors &&1533 squelch_whitespace_errors < whitespace_error)1534return;15351536 err =whitespace_error_string(result);1537fprintf(stderr,"%s:%d:%s.\n%.*s\n",1538 patch_input_file, linenr, err, len, line);1539free(err);1540}15411542static voidcheck_whitespace(const char*line,int len,unsigned ws_rule)1543{1544unsigned result =ws_check(line +1, len -1, ws_rule);15451546record_ws_error(result, line +1, len -2, linenr);1547}15481549/*1550 * Parse a unified diff. Note that this really needs to parse each1551 * fragment separately, since the only way to know the difference1552 * between a "---" that is part of a patch, and a "---" that starts1553 * the next patch is to look at the line counts..1554 */1555static intparse_fragment(const char*line,unsigned long size,1556struct patch *patch,struct fragment *fragment)1557{1558int added, deleted;1559int len =linelen(line, size), offset;1560unsigned long oldlines, newlines;1561unsigned long leading, trailing;15621563 offset =parse_fragment_header(line, len, fragment);1564if(offset <0)1565return-1;1566if(offset >0&& patch->recount)1567recount_diff(line + offset, size - offset, fragment);1568 oldlines = fragment->oldlines;1569 newlines = fragment->newlines;1570 leading =0;1571 trailing =0;15721573/* Parse the thing.. */1574 line += len;1575 size -= len;1576 linenr++;1577 added = deleted =0;1578for(offset = len;15790< size;1580 offset += len, size -= len, line += len, linenr++) {1581if(!oldlines && !newlines)1582break;1583 len =linelen(line, size);1584if(!len || line[len-1] !='\n')1585return-1;1586switch(*line) {1587default:1588return-1;1589case'\n':/* newer GNU diff, an empty context line */1590case' ':1591 oldlines--;1592 newlines--;1593if(!deleted && !added)1594 leading++;1595 trailing++;1596break;1597case'-':1598if(apply_in_reverse &&1599 ws_error_action != nowarn_ws_error)1600check_whitespace(line, len, patch->ws_rule);1601 deleted++;1602 oldlines--;1603 trailing =0;1604break;1605case'+':1606if(!apply_in_reverse &&1607 ws_error_action != nowarn_ws_error)1608check_whitespace(line, len, patch->ws_rule);1609 added++;1610 newlines--;1611 trailing =0;1612break;16131614/*1615 * We allow "\ No newline at end of file". Depending1616 * on locale settings when the patch was produced we1617 * don't know what this line looks like. The only1618 * thing we do know is that it begins with "\ ".1619 * Checking for 12 is just for sanity check -- any1620 * l10n of "\ No newline..." is at least that long.1621 */1622case'\\':1623if(len <12||memcmp(line,"\\",2))1624return-1;1625break;1626}1627}1628if(oldlines || newlines)1629return-1;1630 fragment->leading = leading;1631 fragment->trailing = trailing;16321633/*1634 * If a fragment ends with an incomplete line, we failed to include1635 * it in the above loop because we hit oldlines == newlines == 01636 * before seeing it.1637 */1638if(12< size && !memcmp(line,"\\",2))1639 offset +=linelen(line, size);16401641 patch->lines_added += added;1642 patch->lines_deleted += deleted;16431644if(0< patch->is_new && oldlines)1645returnerror(_("new file depends on old contents"));1646if(0< patch->is_delete && newlines)1647returnerror(_("deleted file still has contents"));1648return offset;1649}16501651/*1652 * We have seen "diff --git a/... b/..." header (or a traditional patch1653 * header). Read hunks that belong to this patch into fragments and hang1654 * them to the given patch structure.1655 *1656 * The (fragment->patch, fragment->size) pair points into the memory given1657 * by the caller, not a copy, when we return.1658 */1659static intparse_single_patch(const char*line,unsigned long size,struct patch *patch)1660{1661unsigned long offset =0;1662unsigned long oldlines =0, newlines =0, context =0;1663struct fragment **fragp = &patch->fragments;16641665while(size >4&& !memcmp(line,"@@ -",4)) {1666struct fragment *fragment;1667int len;16681669 fragment =xcalloc(1,sizeof(*fragment));1670 fragment->linenr = linenr;1671 len =parse_fragment(line, size, patch, fragment);1672if(len <=0)1673die(_("corrupt patch at line%d"), linenr);1674 fragment->patch = line;1675 fragment->size = len;1676 oldlines += fragment->oldlines;1677 newlines += fragment->newlines;1678 context += fragment->leading + fragment->trailing;16791680*fragp = fragment;1681 fragp = &fragment->next;16821683 offset += len;1684 line += len;1685 size -= len;1686}16871688/*1689 * If something was removed (i.e. we have old-lines) it cannot1690 * be creation, and if something was added it cannot be1691 * deletion. However, the reverse is not true; --unified=01692 * patches that only add are not necessarily creation even1693 * though they do not have any old lines, and ones that only1694 * delete are not necessarily deletion.1695 *1696 * Unfortunately, a real creation/deletion patch do _not_ have1697 * any context line by definition, so we cannot safely tell it1698 * apart with --unified=0 insanity. At least if the patch has1699 * more than one hunk it is not creation or deletion.1700 */1701if(patch->is_new <0&&1702(oldlines || (patch->fragments && patch->fragments->next)))1703 patch->is_new =0;1704if(patch->is_delete <0&&1705(newlines || (patch->fragments && patch->fragments->next)))1706 patch->is_delete =0;17071708if(0< patch->is_new && oldlines)1709die(_("new file%sdepends on old contents"), patch->new_name);1710if(0< patch->is_delete && newlines)1711die(_("deleted file%sstill has contents"), patch->old_name);1712if(!patch->is_delete && !newlines && context)1713fprintf_ln(stderr,1714_("** warning: "1715"file%sbecomes empty but is not deleted"),1716 patch->new_name);17171718return offset;1719}17201721staticinlineintmetadata_changes(struct patch *patch)1722{1723return patch->is_rename >0||1724 patch->is_copy >0||1725 patch->is_new >0||1726 patch->is_delete ||1727(patch->old_mode && patch->new_mode &&1728 patch->old_mode != patch->new_mode);1729}17301731static char*inflate_it(const void*data,unsigned long size,1732unsigned long inflated_size)1733{1734 git_zstream stream;1735void*out;1736int st;17371738memset(&stream,0,sizeof(stream));17391740 stream.next_in = (unsigned char*)data;1741 stream.avail_in = size;1742 stream.next_out = out =xmalloc(inflated_size);1743 stream.avail_out = inflated_size;1744git_inflate_init(&stream);1745 st =git_inflate(&stream, Z_FINISH);1746git_inflate_end(&stream);1747if((st != Z_STREAM_END) || stream.total_out != inflated_size) {1748free(out);1749return NULL;1750}1751return out;1752}17531754/*1755 * Read a binary hunk and return a new fragment; fragment->patch1756 * points at an allocated memory that the caller must free, so1757 * it is marked as "->free_patch = 1".1758 */1759static struct fragment *parse_binary_hunk(char**buf_p,1760unsigned long*sz_p,1761int*status_p,1762int*used_p)1763{1764/*1765 * Expect a line that begins with binary patch method ("literal"1766 * or "delta"), followed by the length of data before deflating.1767 * a sequence of 'length-byte' followed by base-85 encoded data1768 * should follow, terminated by a newline.1769 *1770 * Each 5-byte sequence of base-85 encodes up to 4 bytes,1771 * and we would limit the patch line to 66 characters,1772 * so one line can fit up to 13 groups that would decode1773 * to 52 bytes max. The length byte 'A'-'Z' corresponds1774 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.1775 */1776int llen, used;1777unsigned long size = *sz_p;1778char*buffer = *buf_p;1779int patch_method;1780unsigned long origlen;1781char*data = NULL;1782int hunk_size =0;1783struct fragment *frag;17841785 llen =linelen(buffer, size);1786 used = llen;17871788*status_p =0;17891790if(!prefixcmp(buffer,"delta ")) {1791 patch_method = BINARY_DELTA_DEFLATED;1792 origlen =strtoul(buffer +6, NULL,10);1793}1794else if(!prefixcmp(buffer,"literal ")) {1795 patch_method = BINARY_LITERAL_DEFLATED;1796 origlen =strtoul(buffer +8, NULL,10);1797}1798else1799return NULL;18001801 linenr++;1802 buffer += llen;1803while(1) {1804int byte_length, max_byte_length, newsize;1805 llen =linelen(buffer, size);1806 used += llen;1807 linenr++;1808if(llen ==1) {1809/* consume the blank line */1810 buffer++;1811 size--;1812break;1813}1814/*1815 * Minimum line is "A00000\n" which is 7-byte long,1816 * and the line length must be multiple of 5 plus 2.1817 */1818if((llen <7) || (llen-2) %5)1819goto corrupt;1820 max_byte_length = (llen -2) /5*4;1821 byte_length = *buffer;1822if('A'<= byte_length && byte_length <='Z')1823 byte_length = byte_length -'A'+1;1824else if('a'<= byte_length && byte_length <='z')1825 byte_length = byte_length -'a'+27;1826else1827goto corrupt;1828/* if the input length was not multiple of 4, we would1829 * have filler at the end but the filler should never1830 * exceed 3 bytes1831 */1832if(max_byte_length < byte_length ||1833 byte_length <= max_byte_length -4)1834goto corrupt;1835 newsize = hunk_size + byte_length;1836 data =xrealloc(data, newsize);1837if(decode_85(data + hunk_size, buffer +1, byte_length))1838goto corrupt;1839 hunk_size = newsize;1840 buffer += llen;1841 size -= llen;1842}18431844 frag =xcalloc(1,sizeof(*frag));1845 frag->patch =inflate_it(data, hunk_size, origlen);1846 frag->free_patch =1;1847if(!frag->patch)1848goto corrupt;1849free(data);1850 frag->size = origlen;1851*buf_p = buffer;1852*sz_p = size;1853*used_p = used;1854 frag->binary_patch_method = patch_method;1855return frag;18561857 corrupt:1858free(data);1859*status_p = -1;1860error(_("corrupt binary patch at line%d: %.*s"),1861 linenr-1, llen-1, buffer);1862return NULL;1863}18641865static intparse_binary(char*buffer,unsigned long size,struct patch *patch)1866{1867/*1868 * We have read "GIT binary patch\n"; what follows is a line1869 * that says the patch method (currently, either "literal" or1870 * "delta") and the length of data before deflating; a1871 * sequence of 'length-byte' followed by base-85 encoded data1872 * follows.1873 *1874 * When a binary patch is reversible, there is another binary1875 * hunk in the same format, starting with patch method (either1876 * "literal" or "delta") with the length of data, and a sequence1877 * of length-byte + base-85 encoded data, terminated with another1878 * empty line. This data, when applied to the postimage, produces1879 * the preimage.1880 */1881struct fragment *forward;1882struct fragment *reverse;1883int status;1884int used, used_1;18851886 forward =parse_binary_hunk(&buffer, &size, &status, &used);1887if(!forward && !status)1888/* there has to be one hunk (forward hunk) */1889returnerror(_("unrecognized binary patch at line%d"), linenr-1);1890if(status)1891/* otherwise we already gave an error message */1892return status;18931894 reverse =parse_binary_hunk(&buffer, &size, &status, &used_1);1895if(reverse)1896 used += used_1;1897else if(status) {1898/*1899 * Not having reverse hunk is not an error, but having1900 * a corrupt reverse hunk is.1901 */1902free((void*) forward->patch);1903free(forward);1904return status;1905}1906 forward->next = reverse;1907 patch->fragments = forward;1908 patch->is_binary =1;1909return used;1910}19111912/*1913 * Read the patch text in "buffer" taht extends for "size" bytes; stop1914 * reading after seeing a single patch (i.e. changes to a single file).1915 * Create fragments (i.e. patch hunks) and hang them to the given patch.1916 * Return the number of bytes consumed, so that the caller can call us1917 * again for the next patch.1918 */1919static intparse_chunk(char*buffer,unsigned long size,struct patch *patch)1920{1921int hdrsize, patchsize;1922int offset =find_header(buffer, size, &hdrsize, patch);19231924if(offset <0)1925return offset;19261927 patch->ws_rule =whitespace_rule(patch->new_name1928? patch->new_name1929: patch->old_name);19301931 patchsize =parse_single_patch(buffer + offset + hdrsize,1932 size - offset - hdrsize, patch);19331934if(!patchsize) {1935static const char*binhdr[] = {1936"Binary files ",1937"Files ",1938 NULL,1939};1940static const char git_binary[] ="GIT binary patch\n";1941int i;1942int hd = hdrsize + offset;1943unsigned long llen =linelen(buffer + hd, size - hd);19441945if(llen ==sizeof(git_binary) -1&&1946!memcmp(git_binary, buffer + hd, llen)) {1947int used;1948 linenr++;1949 used =parse_binary(buffer + hd + llen,1950 size - hd - llen, patch);1951if(used)1952 patchsize = used + llen;1953else1954 patchsize =0;1955}1956else if(!memcmp(" differ\n", buffer + hd + llen -8,8)) {1957for(i =0; binhdr[i]; i++) {1958int len =strlen(binhdr[i]);1959if(len < size - hd &&1960!memcmp(binhdr[i], buffer + hd, len)) {1961 linenr++;1962 patch->is_binary =1;1963 patchsize = llen;1964break;1965}1966}1967}19681969/* Empty patch cannot be applied if it is a text patch1970 * without metadata change. A binary patch appears1971 * empty to us here.1972 */1973if((apply || check) &&1974(!patch->is_binary && !metadata_changes(patch)))1975die(_("patch with only garbage at line%d"), linenr);1976}19771978return offset + hdrsize + patchsize;1979}19801981#define swap(a,b) myswap((a),(b),sizeof(a))19821983#define myswap(a, b, size) do { \1984 unsigned char mytmp[size]; \1985 memcpy(mytmp, &a, size); \1986 memcpy(&a, &b, size); \1987 memcpy(&b, mytmp, size); \1988} while (0)19891990static voidreverse_patches(struct patch *p)1991{1992for(; p; p = p->next) {1993struct fragment *frag = p->fragments;19941995swap(p->new_name, p->old_name);1996swap(p->new_mode, p->old_mode);1997swap(p->is_new, p->is_delete);1998swap(p->lines_added, p->lines_deleted);1999swap(p->old_sha1_prefix, p->new_sha1_prefix);20002001for(; frag; frag = frag->next) {2002swap(frag->newpos, frag->oldpos);2003swap(frag->newlines, frag->oldlines);2004}2005}2006}20072008static const char pluses[] =2009"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";2010static const char minuses[]=2011"----------------------------------------------------------------------";20122013static voidshow_stats(struct patch *patch)2014{2015struct strbuf qname = STRBUF_INIT;2016char*cp = patch->new_name ? patch->new_name : patch->old_name;2017int max, add, del;20182019quote_c_style(cp, &qname, NULL,0);20202021/*2022 * "scale" the filename2023 */2024 max = max_len;2025if(max >50)2026 max =50;20272028if(qname.len > max) {2029 cp =strchr(qname.buf + qname.len +3- max,'/');2030if(!cp)2031 cp = qname.buf + qname.len +3- max;2032strbuf_splice(&qname,0, cp - qname.buf,"...",3);2033}20342035if(patch->is_binary) {2036printf(" %-*s | Bin\n", max, qname.buf);2037strbuf_release(&qname);2038return;2039}20402041printf(" %-*s |", max, qname.buf);2042strbuf_release(&qname);20432044/*2045 * scale the add/delete2046 */2047 max = max + max_change >70?70- max : max_change;2048 add = patch->lines_added;2049 del = patch->lines_deleted;20502051if(max_change >0) {2052int total = ((add + del) * max + max_change /2) / max_change;2053 add = (add * max + max_change /2) / max_change;2054 del = total - add;2055}2056printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,2057 add, pluses, del, minuses);2058}20592060static intread_old_data(struct stat *st,const char*path,struct strbuf *buf)2061{2062switch(st->st_mode & S_IFMT) {2063case S_IFLNK:2064if(strbuf_readlink(buf, path, st->st_size) <0)2065returnerror(_("unable to read symlink%s"), path);2066return0;2067case S_IFREG:2068if(strbuf_read_file(buf, path, st->st_size) != st->st_size)2069returnerror(_("unable to open or read%s"), path);2070convert_to_git(path, buf->buf, buf->len, buf,0);2071return0;2072default:2073return-1;2074}2075}20762077/*2078 * Update the preimage, and the common lines in postimage,2079 * from buffer buf of length len. If postlen is 0 the postimage2080 * is updated in place, otherwise it's updated on a new buffer2081 * of length postlen2082 */20832084static voidupdate_pre_post_images(struct image *preimage,2085struct image *postimage,2086char*buf,2087size_t len,size_t postlen)2088{2089int i, ctx;2090char*new, *old, *fixed;2091struct image fixed_preimage;20922093/*2094 * Update the preimage with whitespace fixes. Note that we2095 * are not losing preimage->buf -- apply_one_fragment() will2096 * free "oldlines".2097 */2098prepare_image(&fixed_preimage, buf, len,1);2099assert(fixed_preimage.nr == preimage->nr);2100for(i =0; i < preimage->nr; i++)2101 fixed_preimage.line[i].flag = preimage->line[i].flag;2102free(preimage->line_allocated);2103*preimage = fixed_preimage;21042105/*2106 * Adjust the common context lines in postimage. This can be2107 * done in-place when we are just doing whitespace fixing,2108 * which does not make the string grow, but needs a new buffer2109 * when ignoring whitespace causes the update, since in this case2110 * we could have e.g. tabs converted to multiple spaces.2111 * We trust the caller to tell us if the update can be done2112 * in place (postlen==0) or not.2113 */2114 old = postimage->buf;2115if(postlen)2116new= postimage->buf =xmalloc(postlen);2117else2118new= old;2119 fixed = preimage->buf;2120for(i = ctx =0; i < postimage->nr; i++) {2121size_t len = postimage->line[i].len;2122if(!(postimage->line[i].flag & LINE_COMMON)) {2123/* an added line -- no counterparts in preimage */2124memmove(new, old, len);2125 old += len;2126new+= len;2127continue;2128}21292130/* a common context -- skip it in the original postimage */2131 old += len;21322133/* and find the corresponding one in the fixed preimage */2134while(ctx < preimage->nr &&2135!(preimage->line[ctx].flag & LINE_COMMON)) {2136 fixed += preimage->line[ctx].len;2137 ctx++;2138}2139if(preimage->nr <= ctx)2140die(_("oops"));21412142/* and copy it in, while fixing the line length */2143 len = preimage->line[ctx].len;2144memcpy(new, fixed, len);2145new+= len;2146 fixed += len;2147 postimage->line[i].len = len;2148 ctx++;2149}21502151/* Fix the length of the whole thing */2152 postimage->len =new- postimage->buf;2153}21542155static intmatch_fragment(struct image *img,2156struct image *preimage,2157struct image *postimage,2158unsigned longtry,2159int try_lno,2160unsigned ws_rule,2161int match_beginning,int match_end)2162{2163int i;2164char*fixed_buf, *buf, *orig, *target;2165struct strbuf fixed;2166size_t fixed_len;2167int preimage_limit;21682169if(preimage->nr + try_lno <= img->nr) {2170/*2171 * The hunk falls within the boundaries of img.2172 */2173 preimage_limit = preimage->nr;2174if(match_end && (preimage->nr + try_lno != img->nr))2175return0;2176}else if(ws_error_action == correct_ws_error &&2177(ws_rule & WS_BLANK_AT_EOF)) {2178/*2179 * This hunk extends beyond the end of img, and we are2180 * removing blank lines at the end of the file. This2181 * many lines from the beginning of the preimage must2182 * match with img, and the remainder of the preimage2183 * must be blank.2184 */2185 preimage_limit = img->nr - try_lno;2186}else{2187/*2188 * The hunk extends beyond the end of the img and2189 * we are not removing blanks at the end, so we2190 * should reject the hunk at this position.2191 */2192return0;2193}21942195if(match_beginning && try_lno)2196return0;21972198/* Quick hash check */2199for(i =0; i < preimage_limit; i++)2200if((img->line[try_lno + i].flag & LINE_PATCHED) ||2201(preimage->line[i].hash != img->line[try_lno + i].hash))2202return0;22032204if(preimage_limit == preimage->nr) {2205/*2206 * Do we have an exact match? If we were told to match2207 * at the end, size must be exactly at try+fragsize,2208 * otherwise try+fragsize must be still within the preimage,2209 * and either case, the old piece should match the preimage2210 * exactly.2211 */2212if((match_end2213? (try+ preimage->len == img->len)2214: (try+ preimage->len <= img->len)) &&2215!memcmp(img->buf +try, preimage->buf, preimage->len))2216return1;2217}else{2218/*2219 * The preimage extends beyond the end of img, so2220 * there cannot be an exact match.2221 *2222 * There must be one non-blank context line that match2223 * a line before the end of img.2224 */2225char*buf_end;22262227 buf = preimage->buf;2228 buf_end = buf;2229for(i =0; i < preimage_limit; i++)2230 buf_end += preimage->line[i].len;22312232for( ; buf < buf_end; buf++)2233if(!isspace(*buf))2234break;2235if(buf == buf_end)2236return0;2237}22382239/*2240 * No exact match. If we are ignoring whitespace, run a line-by-line2241 * fuzzy matching. We collect all the line length information because2242 * we need it to adjust whitespace if we match.2243 */2244if(ws_ignore_action == ignore_ws_change) {2245size_t imgoff =0;2246size_t preoff =0;2247size_t postlen = postimage->len;2248size_t extra_chars;2249char*preimage_eof;2250char*preimage_end;2251for(i =0; i < preimage_limit; i++) {2252size_t prelen = preimage->line[i].len;2253size_t imglen = img->line[try_lno+i].len;22542255if(!fuzzy_matchlines(img->buf +try+ imgoff, imglen,2256 preimage->buf + preoff, prelen))2257return0;2258if(preimage->line[i].flag & LINE_COMMON)2259 postlen += imglen - prelen;2260 imgoff += imglen;2261 preoff += prelen;2262}22632264/*2265 * Ok, the preimage matches with whitespace fuzz.2266 *2267 * imgoff now holds the true length of the target that2268 * matches the preimage before the end of the file.2269 *2270 * Count the number of characters in the preimage that fall2271 * beyond the end of the file and make sure that all of them2272 * are whitespace characters. (This can only happen if2273 * we are removing blank lines at the end of the file.)2274 */2275 buf = preimage_eof = preimage->buf + preoff;2276for( ; i < preimage->nr; i++)2277 preoff += preimage->line[i].len;2278 preimage_end = preimage->buf + preoff;2279for( ; buf < preimage_end; buf++)2280if(!isspace(*buf))2281return0;22822283/*2284 * Update the preimage and the common postimage context2285 * lines to use the same whitespace as the target.2286 * If whitespace is missing in the target (i.e.2287 * if the preimage extends beyond the end of the file),2288 * use the whitespace from the preimage.2289 */2290 extra_chars = preimage_end - preimage_eof;2291strbuf_init(&fixed, imgoff + extra_chars);2292strbuf_add(&fixed, img->buf +try, imgoff);2293strbuf_add(&fixed, preimage_eof, extra_chars);2294 fixed_buf =strbuf_detach(&fixed, &fixed_len);2295update_pre_post_images(preimage, postimage,2296 fixed_buf, fixed_len, postlen);2297return1;2298}22992300if(ws_error_action != correct_ws_error)2301return0;23022303/*2304 * The hunk does not apply byte-by-byte, but the hash says2305 * it might with whitespace fuzz. We haven't been asked to2306 * ignore whitespace, we were asked to correct whitespace2307 * errors, so let's try matching after whitespace correction.2308 *2309 * The preimage may extend beyond the end of the file,2310 * but in this loop we will only handle the part of the2311 * preimage that falls within the file.2312 */2313strbuf_init(&fixed, preimage->len +1);2314 orig = preimage->buf;2315 target = img->buf +try;2316for(i =0; i < preimage_limit; i++) {2317size_t oldlen = preimage->line[i].len;2318size_t tgtlen = img->line[try_lno + i].len;2319size_t fixstart = fixed.len;2320struct strbuf tgtfix;2321int match;23222323/* Try fixing the line in the preimage */2324ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);23252326/* Try fixing the line in the target */2327strbuf_init(&tgtfix, tgtlen);2328ws_fix_copy(&tgtfix, target, tgtlen, ws_rule, NULL);23292330/*2331 * If they match, either the preimage was based on2332 * a version before our tree fixed whitespace breakage,2333 * or we are lacking a whitespace-fix patch the tree2334 * the preimage was based on already had (i.e. target2335 * has whitespace breakage, the preimage doesn't).2336 * In either case, we are fixing the whitespace breakages2337 * so we might as well take the fix together with their2338 * real change.2339 */2340 match = (tgtfix.len == fixed.len - fixstart &&2341!memcmp(tgtfix.buf, fixed.buf + fixstart,2342 fixed.len - fixstart));23432344strbuf_release(&tgtfix);2345if(!match)2346goto unmatch_exit;23472348 orig += oldlen;2349 target += tgtlen;2350}235123522353/*2354 * Now handle the lines in the preimage that falls beyond the2355 * end of the file (if any). They will only match if they are2356 * empty or only contain whitespace (if WS_BLANK_AT_EOL is2357 * false).2358 */2359for( ; i < preimage->nr; i++) {2360size_t fixstart = fixed.len;/* start of the fixed preimage */2361size_t oldlen = preimage->line[i].len;2362int j;23632364/* Try fixing the line in the preimage */2365ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);23662367for(j = fixstart; j < fixed.len; j++)2368if(!isspace(fixed.buf[j]))2369goto unmatch_exit;23702371 orig += oldlen;2372}23732374/*2375 * Yes, the preimage is based on an older version that still2376 * has whitespace breakages unfixed, and fixing them makes the2377 * hunk match. Update the context lines in the postimage.2378 */2379 fixed_buf =strbuf_detach(&fixed, &fixed_len);2380update_pre_post_images(preimage, postimage,2381 fixed_buf, fixed_len,0);2382return1;23832384 unmatch_exit:2385strbuf_release(&fixed);2386return0;2387}23882389static intfind_pos(struct image *img,2390struct image *preimage,2391struct image *postimage,2392int line,2393unsigned ws_rule,2394int match_beginning,int match_end)2395{2396int i;2397unsigned long backwards, forwards,try;2398int backwards_lno, forwards_lno, try_lno;23992400/*2401 * If match_beginning or match_end is specified, there is no2402 * point starting from a wrong line that will never match and2403 * wander around and wait for a match at the specified end.2404 */2405if(match_beginning)2406 line =0;2407else if(match_end)2408 line = img->nr - preimage->nr;24092410/*2411 * Because the comparison is unsigned, the following test2412 * will also take care of a negative line number that can2413 * result when match_end and preimage is larger than the target.2414 */2415if((size_t) line > img->nr)2416 line = img->nr;24172418try=0;2419for(i =0; i < line; i++)2420try+= img->line[i].len;24212422/*2423 * There's probably some smart way to do this, but I'll leave2424 * that to the smart and beautiful people. I'm simple and stupid.2425 */2426 backwards =try;2427 backwards_lno = line;2428 forwards =try;2429 forwards_lno = line;2430 try_lno = line;24312432for(i =0; ; i++) {2433if(match_fragment(img, preimage, postimage,2434try, try_lno, ws_rule,2435 match_beginning, match_end))2436return try_lno;24372438 again:2439if(backwards_lno ==0&& forwards_lno == img->nr)2440break;24412442if(i &1) {2443if(backwards_lno ==0) {2444 i++;2445goto again;2446}2447 backwards_lno--;2448 backwards -= img->line[backwards_lno].len;2449try= backwards;2450 try_lno = backwards_lno;2451}else{2452if(forwards_lno == img->nr) {2453 i++;2454goto again;2455}2456 forwards += img->line[forwards_lno].len;2457 forwards_lno++;2458try= forwards;2459 try_lno = forwards_lno;2460}24612462}2463return-1;2464}24652466static voidremove_first_line(struct image *img)2467{2468 img->buf += img->line[0].len;2469 img->len -= img->line[0].len;2470 img->line++;2471 img->nr--;2472}24732474static voidremove_last_line(struct image *img)2475{2476 img->len -= img->line[--img->nr].len;2477}24782479/*2480 * The change from "preimage" and "postimage" has been found to2481 * apply at applied_pos (counts in line numbers) in "img".2482 * Update "img" to remove "preimage" and replace it with "postimage".2483 */2484static voidupdate_image(struct image *img,2485int applied_pos,2486struct image *preimage,2487struct image *postimage)2488{2489/*2490 * remove the copy of preimage at offset in img2491 * and replace it with postimage2492 */2493int i, nr;2494size_t remove_count, insert_count, applied_at =0;2495char*result;2496int preimage_limit;24972498/*2499 * If we are removing blank lines at the end of img,2500 * the preimage may extend beyond the end.2501 * If that is the case, we must be careful only to2502 * remove the part of the preimage that falls within2503 * the boundaries of img. Initialize preimage_limit2504 * to the number of lines in the preimage that falls2505 * within the boundaries.2506 */2507 preimage_limit = preimage->nr;2508if(preimage_limit > img->nr - applied_pos)2509 preimage_limit = img->nr - applied_pos;25102511for(i =0; i < applied_pos; i++)2512 applied_at += img->line[i].len;25132514 remove_count =0;2515for(i =0; i < preimage_limit; i++)2516 remove_count += img->line[applied_pos + i].len;2517 insert_count = postimage->len;25182519/* Adjust the contents */2520 result =xmalloc(img->len + insert_count - remove_count +1);2521memcpy(result, img->buf, applied_at);2522memcpy(result + applied_at, postimage->buf, postimage->len);2523memcpy(result + applied_at + postimage->len,2524 img->buf + (applied_at + remove_count),2525 img->len - (applied_at + remove_count));2526free(img->buf);2527 img->buf = result;2528 img->len += insert_count - remove_count;2529 result[img->len] ='\0';25302531/* Adjust the line table */2532 nr = img->nr + postimage->nr - preimage_limit;2533if(preimage_limit < postimage->nr) {2534/*2535 * NOTE: this knows that we never call remove_first_line()2536 * on anything other than pre/post image.2537 */2538 img->line =xrealloc(img->line, nr *sizeof(*img->line));2539 img->line_allocated = img->line;2540}2541if(preimage_limit != postimage->nr)2542memmove(img->line + applied_pos + postimage->nr,2543 img->line + applied_pos + preimage_limit,2544(img->nr - (applied_pos + preimage_limit)) *2545sizeof(*img->line));2546memcpy(img->line + applied_pos,2547 postimage->line,2548 postimage->nr *sizeof(*img->line));2549if(!allow_overlap)2550for(i =0; i < postimage->nr; i++)2551 img->line[applied_pos + i].flag |= LINE_PATCHED;2552 img->nr = nr;2553}25542555/*2556 * Use the patch-hunk text in "frag" to prepare two images (preimage and2557 * postimage) for the hunk. Find lines that match "preimage" in "img" and2558 * replace the part of "img" with "postimage" text.2559 */2560static intapply_one_fragment(struct image *img,struct fragment *frag,2561int inaccurate_eof,unsigned ws_rule,2562int nth_fragment)2563{2564int match_beginning, match_end;2565const char*patch = frag->patch;2566int size = frag->size;2567char*old, *oldlines;2568struct strbuf newlines;2569int new_blank_lines_at_end =0;2570int found_new_blank_lines_at_end =0;2571int hunk_linenr = frag->linenr;2572unsigned long leading, trailing;2573int pos, applied_pos;2574struct image preimage;2575struct image postimage;25762577memset(&preimage,0,sizeof(preimage));2578memset(&postimage,0,sizeof(postimage));2579 oldlines =xmalloc(size);2580strbuf_init(&newlines, size);25812582 old = oldlines;2583while(size >0) {2584char first;2585int len =linelen(patch, size);2586int plen;2587int added_blank_line =0;2588int is_blank_context =0;2589size_t start;25902591if(!len)2592break;25932594/*2595 * "plen" is how much of the line we should use for2596 * the actual patch data. Normally we just remove the2597 * first character on the line, but if the line is2598 * followed by "\ No newline", then we also remove the2599 * last one (which is the newline, of course).2600 */2601 plen = len -1;2602if(len < size && patch[len] =='\\')2603 plen--;2604 first = *patch;2605if(apply_in_reverse) {2606if(first =='-')2607 first ='+';2608else if(first =='+')2609 first ='-';2610}26112612switch(first) {2613case'\n':2614/* Newer GNU diff, empty context line */2615if(plen <0)2616/* ... followed by '\No newline'; nothing */2617break;2618*old++ ='\n';2619strbuf_addch(&newlines,'\n');2620add_line_info(&preimage,"\n",1, LINE_COMMON);2621add_line_info(&postimage,"\n",1, LINE_COMMON);2622 is_blank_context =1;2623break;2624case' ':2625if(plen && (ws_rule & WS_BLANK_AT_EOF) &&2626ws_blank_line(patch +1, plen, ws_rule))2627 is_blank_context =1;2628case'-':2629memcpy(old, patch +1, plen);2630add_line_info(&preimage, old, plen,2631(first ==' '? LINE_COMMON :0));2632 old += plen;2633if(first =='-')2634break;2635/* Fall-through for ' ' */2636case'+':2637/* --no-add does not add new lines */2638if(first =='+'&& no_add)2639break;26402641 start = newlines.len;2642if(first !='+'||2643!whitespace_error ||2644 ws_error_action != correct_ws_error) {2645strbuf_add(&newlines, patch +1, plen);2646}2647else{2648ws_fix_copy(&newlines, patch +1, plen, ws_rule, &applied_after_fixing_ws);2649}2650add_line_info(&postimage, newlines.buf + start, newlines.len - start,2651(first =='+'?0: LINE_COMMON));2652if(first =='+'&&2653(ws_rule & WS_BLANK_AT_EOF) &&2654ws_blank_line(patch +1, plen, ws_rule))2655 added_blank_line =1;2656break;2657case'@':case'\\':2658/* Ignore it, we already handled it */2659break;2660default:2661if(apply_verbosely)2662error(_("invalid start of line: '%c'"), first);2663return-1;2664}2665if(added_blank_line) {2666if(!new_blank_lines_at_end)2667 found_new_blank_lines_at_end = hunk_linenr;2668 new_blank_lines_at_end++;2669}2670else if(is_blank_context)2671;2672else2673 new_blank_lines_at_end =0;2674 patch += len;2675 size -= len;2676 hunk_linenr++;2677}2678if(inaccurate_eof &&2679 old > oldlines && old[-1] =='\n'&&2680 newlines.len >0&& newlines.buf[newlines.len -1] =='\n') {2681 old--;2682strbuf_setlen(&newlines, newlines.len -1);2683}26842685 leading = frag->leading;2686 trailing = frag->trailing;26872688/*2689 * A hunk to change lines at the beginning would begin with2690 * @@ -1,L +N,M @@2691 * but we need to be careful. -U0 that inserts before the second2692 * line also has this pattern.2693 *2694 * And a hunk to add to an empty file would begin with2695 * @@ -0,0 +N,M @@2696 *2697 * In other words, a hunk that is (frag->oldpos <= 1) with or2698 * without leading context must match at the beginning.2699 */2700 match_beginning = (!frag->oldpos ||2701(frag->oldpos ==1&& !unidiff_zero));27022703/*2704 * A hunk without trailing lines must match at the end.2705 * However, we simply cannot tell if a hunk must match end2706 * from the lack of trailing lines if the patch was generated2707 * with unidiff without any context.2708 */2709 match_end = !unidiff_zero && !trailing;27102711 pos = frag->newpos ? (frag->newpos -1) :0;2712 preimage.buf = oldlines;2713 preimage.len = old - oldlines;2714 postimage.buf = newlines.buf;2715 postimage.len = newlines.len;2716 preimage.line = preimage.line_allocated;2717 postimage.line = postimage.line_allocated;27182719for(;;) {27202721 applied_pos =find_pos(img, &preimage, &postimage, pos,2722 ws_rule, match_beginning, match_end);27232724if(applied_pos >=0)2725break;27262727/* Am I at my context limits? */2728if((leading <= p_context) && (trailing <= p_context))2729break;2730if(match_beginning || match_end) {2731 match_beginning = match_end =0;2732continue;2733}27342735/*2736 * Reduce the number of context lines; reduce both2737 * leading and trailing if they are equal otherwise2738 * just reduce the larger context.2739 */2740if(leading >= trailing) {2741remove_first_line(&preimage);2742remove_first_line(&postimage);2743 pos--;2744 leading--;2745}2746if(trailing > leading) {2747remove_last_line(&preimage);2748remove_last_line(&postimage);2749 trailing--;2750}2751}27522753if(applied_pos >=0) {2754if(new_blank_lines_at_end &&2755 preimage.nr + applied_pos >= img->nr &&2756(ws_rule & WS_BLANK_AT_EOF) &&2757 ws_error_action != nowarn_ws_error) {2758record_ws_error(WS_BLANK_AT_EOF,"+",1,2759 found_new_blank_lines_at_end);2760if(ws_error_action == correct_ws_error) {2761while(new_blank_lines_at_end--)2762remove_last_line(&postimage);2763}2764/*2765 * We would want to prevent write_out_results()2766 * from taking place in apply_patch() that follows2767 * the callchain led us here, which is:2768 * apply_patch->check_patch_list->check_patch->2769 * apply_data->apply_fragments->apply_one_fragment2770 */2771if(ws_error_action == die_on_ws_error)2772 apply =0;2773}27742775if(apply_verbosely && applied_pos != pos) {2776int offset = applied_pos - pos;2777if(apply_in_reverse)2778 offset =0- offset;2779fprintf_ln(stderr,2780Q_("Hunk #%dsucceeded at%d(offset%dline).",2781"Hunk #%dsucceeded at%d(offset%dlines).",2782 offset),2783 nth_fragment, applied_pos +1, offset);2784}27852786/*2787 * Warn if it was necessary to reduce the number2788 * of context lines.2789 */2790if((leading != frag->leading) ||2791(trailing != frag->trailing))2792fprintf_ln(stderr,_("Context reduced to (%ld/%ld)"2793" to apply fragment at%d"),2794 leading, trailing, applied_pos+1);2795update_image(img, applied_pos, &preimage, &postimage);2796}else{2797if(apply_verbosely)2798error(_("while searching for:\n%.*s"),2799(int)(old - oldlines), oldlines);2800}28012802free(oldlines);2803strbuf_release(&newlines);2804free(preimage.line_allocated);2805free(postimage.line_allocated);28062807return(applied_pos <0);2808}28092810static intapply_binary_fragment(struct image *img,struct patch *patch)2811{2812struct fragment *fragment = patch->fragments;2813unsigned long len;2814void*dst;28152816if(!fragment)2817returnerror(_("missing binary patch data for '%s'"),2818 patch->new_name ?2819 patch->new_name :2820 patch->old_name);28212822/* Binary patch is irreversible without the optional second hunk */2823if(apply_in_reverse) {2824if(!fragment->next)2825returnerror("cannot reverse-apply a binary patch "2826"without the reverse hunk to '%s'",2827 patch->new_name2828? patch->new_name : patch->old_name);2829 fragment = fragment->next;2830}2831switch(fragment->binary_patch_method) {2832case BINARY_DELTA_DEFLATED:2833 dst =patch_delta(img->buf, img->len, fragment->patch,2834 fragment->size, &len);2835if(!dst)2836return-1;2837clear_image(img);2838 img->buf = dst;2839 img->len = len;2840return0;2841case BINARY_LITERAL_DEFLATED:2842clear_image(img);2843 img->len = fragment->size;2844 img->buf =xmalloc(img->len+1);2845memcpy(img->buf, fragment->patch, img->len);2846 img->buf[img->len] ='\0';2847return0;2848}2849return-1;2850}28512852/*2853 * Replace "img" with the result of applying the binary patch.2854 * The binary patch data itself in patch->fragment is still kept2855 * but the preimage prepared by the caller in "img" is freed here2856 * or in the helper function apply_binary_fragment() this calls.2857 */2858static intapply_binary(struct image *img,struct patch *patch)2859{2860const char*name = patch->old_name ? patch->old_name : patch->new_name;2861unsigned char sha1[20];28622863/*2864 * For safety, we require patch index line to contain2865 * full 40-byte textual SHA1 for old and new, at least for now.2866 */2867if(strlen(patch->old_sha1_prefix) !=40||2868strlen(patch->new_sha1_prefix) !=40||2869get_sha1_hex(patch->old_sha1_prefix, sha1) ||2870get_sha1_hex(patch->new_sha1_prefix, sha1))2871returnerror("cannot apply binary patch to '%s' "2872"without full index line", name);28732874if(patch->old_name) {2875/*2876 * See if the old one matches what the patch2877 * applies to.2878 */2879hash_sha1_file(img->buf, img->len, blob_type, sha1);2880if(strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))2881returnerror("the patch applies to '%s' (%s), "2882"which does not match the "2883"current contents.",2884 name,sha1_to_hex(sha1));2885}2886else{2887/* Otherwise, the old one must be empty. */2888if(img->len)2889returnerror("the patch applies to an empty "2890"'%s' but it is not empty", name);2891}28922893get_sha1_hex(patch->new_sha1_prefix, sha1);2894if(is_null_sha1(sha1)) {2895clear_image(img);2896return0;/* deletion patch */2897}28982899if(has_sha1_file(sha1)) {2900/* We already have the postimage */2901enum object_type type;2902unsigned long size;2903char*result;29042905 result =read_sha1_file(sha1, &type, &size);2906if(!result)2907returnerror("the necessary postimage%sfor "2908"'%s' cannot be read",2909 patch->new_sha1_prefix, name);2910clear_image(img);2911 img->buf = result;2912 img->len = size;2913}else{2914/*2915 * We have verified buf matches the preimage;2916 * apply the patch data to it, which is stored2917 * in the patch->fragments->{patch,size}.2918 */2919if(apply_binary_fragment(img, patch))2920returnerror(_("binary patch does not apply to '%s'"),2921 name);29222923/* verify that the result matches */2924hash_sha1_file(img->buf, img->len, blob_type, sha1);2925if(strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))2926returnerror(_("binary patch to '%s' creates incorrect result (expecting%s, got%s)"),2927 name, patch->new_sha1_prefix,sha1_to_hex(sha1));2928}29292930return0;2931}29322933static intapply_fragments(struct image *img,struct patch *patch)2934{2935struct fragment *frag = patch->fragments;2936const char*name = patch->old_name ? patch->old_name : patch->new_name;2937unsigned ws_rule = patch->ws_rule;2938unsigned inaccurate_eof = patch->inaccurate_eof;2939int nth =0;29402941if(patch->is_binary)2942returnapply_binary(img, patch);29432944while(frag) {2945 nth++;2946if(apply_one_fragment(img, frag, inaccurate_eof, ws_rule, nth)) {2947error(_("patch failed:%s:%ld"), name, frag->oldpos);2948if(!apply_with_reject)2949return-1;2950 frag->rejected =1;2951}2952 frag = frag->next;2953}2954return0;2955}29562957static intread_file_or_gitlink(struct cache_entry *ce,struct strbuf *buf)2958{2959if(!ce)2960return0;29612962if(S_ISGITLINK(ce->ce_mode)) {2963strbuf_grow(buf,100);2964strbuf_addf(buf,"Subproject commit%s\n",sha1_to_hex(ce->sha1));2965}else{2966enum object_type type;2967unsigned long sz;2968char*result;29692970 result =read_sha1_file(ce->sha1, &type, &sz);2971if(!result)2972return-1;2973/* XXX read_sha1_file NUL-terminates */2974strbuf_attach(buf, result, sz, sz +1);2975}2976return0;2977}29782979static struct patch *in_fn_table(const char*name)2980{2981struct string_list_item *item;29822983if(name == NULL)2984return NULL;29852986 item =string_list_lookup(&fn_table, name);2987if(item != NULL)2988return(struct patch *)item->util;29892990return NULL;2991}29922993/*2994 * item->util in the filename table records the status of the path.2995 * Usually it points at a patch (whose result records the contents2996 * of it after applying it), but it could be PATH_WAS_DELETED for a2997 * path that a previously applied patch has already removed.2998 */2999#define PATH_TO_BE_DELETED ((struct patch *) -2)3000#define PATH_WAS_DELETED ((struct patch *) -1)30013002static intto_be_deleted(struct patch *patch)3003{3004return patch == PATH_TO_BE_DELETED;3005}30063007static intwas_deleted(struct patch *patch)3008{3009return patch == PATH_WAS_DELETED;3010}30113012static voidadd_to_fn_table(struct patch *patch)3013{3014struct string_list_item *item;30153016/*3017 * Always add new_name unless patch is a deletion3018 * This should cover the cases for normal diffs,3019 * file creations and copies3020 */3021if(patch->new_name != NULL) {3022 item =string_list_insert(&fn_table, patch->new_name);3023 item->util = patch;3024}30253026/*3027 * store a failure on rename/deletion cases because3028 * later chunks shouldn't patch old names3029 */3030if((patch->new_name == NULL) || (patch->is_rename)) {3031 item =string_list_insert(&fn_table, patch->old_name);3032 item->util = PATH_WAS_DELETED;3033}3034}30353036static voidprepare_fn_table(struct patch *patch)3037{3038/*3039 * store information about incoming file deletion3040 */3041while(patch) {3042if((patch->new_name == NULL) || (patch->is_rename)) {3043struct string_list_item *item;3044 item =string_list_insert(&fn_table, patch->old_name);3045 item->util = PATH_TO_BE_DELETED;3046}3047 patch = patch->next;3048}3049}30503051static intapply_data(struct patch *patch,struct stat *st,struct cache_entry *ce)3052{3053struct strbuf buf = STRBUF_INIT;3054struct image image;3055size_t len;3056char*img;3057struct patch *tpatch;30583059if(!(patch->is_copy || patch->is_rename) &&3060(tpatch =in_fn_table(patch->old_name)) != NULL && !to_be_deleted(tpatch)) {3061if(was_deleted(tpatch)) {3062returnerror(_("patch%shas been renamed/deleted"),3063 patch->old_name);3064}3065/* We have a patched copy in memory; use that. */3066strbuf_add(&buf, tpatch->result, tpatch->resultsize);3067}else if(cached) {3068if(read_file_or_gitlink(ce, &buf))3069returnerror(_("read of%sfailed"), patch->old_name);3070}else if(patch->old_name) {3071if(S_ISGITLINK(patch->old_mode)) {3072if(ce) {3073read_file_or_gitlink(ce, &buf);3074}else{3075/*3076 * There is no way to apply subproject3077 * patch without looking at the index.3078 * NEEDSWORK: shouldn't this be flagged3079 * as an error???3080 */3081free_fragment_list(patch->fragments);3082 patch->fragments = NULL;3083}3084}else{3085if(read_old_data(st, patch->old_name, &buf))3086returnerror(_("read of%sfailed"), patch->old_name);3087}3088}30893090 img =strbuf_detach(&buf, &len);3091prepare_image(&image, img, len, !patch->is_binary);30923093if(apply_fragments(&image, patch) <0)3094return-1;/* note with --reject this succeeds. */3095 patch->result = image.buf;3096 patch->resultsize = image.len;3097add_to_fn_table(patch);3098free(image.line_allocated);30993100if(0< patch->is_delete && patch->resultsize)3101returnerror(_("removal patch leaves file contents"));31023103return0;3104}31053106static intcheck_to_create_blob(const char*new_name,int ok_if_exists)3107{3108struct stat nst;3109if(!lstat(new_name, &nst)) {3110if(S_ISDIR(nst.st_mode) || ok_if_exists)3111return0;3112/*3113 * A leading component of new_name might be a symlink3114 * that is going to be removed with this patch, but3115 * still pointing at somewhere that has the path.3116 * In such a case, path "new_name" does not exist as3117 * far as git is concerned.3118 */3119if(has_symlink_leading_path(new_name,strlen(new_name)))3120return0;31213122returnerror(_("%s: already exists in working directory"), new_name);3123}3124else if((errno != ENOENT) && (errno != ENOTDIR))3125returnerror("%s:%s", new_name,strerror(errno));3126return0;3127}31283129static intverify_index_match(struct cache_entry *ce,struct stat *st)3130{3131if(S_ISGITLINK(ce->ce_mode)) {3132if(!S_ISDIR(st->st_mode))3133return-1;3134return0;3135}3136returnce_match_stat(ce, st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE);3137}31383139static intcheck_preimage(struct patch *patch,struct cache_entry **ce,struct stat *st)3140{3141const char*old_name = patch->old_name;3142struct patch *tpatch = NULL;3143int stat_ret =0;3144unsigned st_mode =0;31453146/*3147 * Make sure that we do not have local modifications from the3148 * index when we are looking at the index. Also make sure3149 * we have the preimage file to be patched in the work tree,3150 * unless --cached, which tells git to apply only in the index.3151 */3152if(!old_name)3153return0;31543155assert(patch->is_new <=0);31563157if(!(patch->is_copy || patch->is_rename) &&3158(tpatch =in_fn_table(old_name)) != NULL && !to_be_deleted(tpatch)) {3159if(was_deleted(tpatch))3160returnerror(_("%s: has been deleted/renamed"), old_name);3161 st_mode = tpatch->new_mode;3162}else if(!cached) {3163 stat_ret =lstat(old_name, st);3164if(stat_ret && errno != ENOENT)3165returnerror(_("%s:%s"), old_name,strerror(errno));3166}31673168if(to_be_deleted(tpatch))3169 tpatch = NULL;31703171if(check_index && !tpatch) {3172int pos =cache_name_pos(old_name,strlen(old_name));3173if(pos <0) {3174if(patch->is_new <0)3175goto is_new;3176returnerror(_("%s: does not exist in index"), old_name);3177}3178*ce = active_cache[pos];3179if(stat_ret <0) {3180struct checkout costate;3181/* checkout */3182memset(&costate,0,sizeof(costate));3183 costate.base_dir ="";3184 costate.refresh_cache =1;3185if(checkout_entry(*ce, &costate, NULL) ||3186lstat(old_name, st))3187return-1;3188}3189if(!cached &&verify_index_match(*ce, st))3190returnerror(_("%s: does not match index"), old_name);3191if(cached)3192 st_mode = (*ce)->ce_mode;3193}else if(stat_ret <0) {3194if(patch->is_new <0)3195goto is_new;3196returnerror(_("%s:%s"), old_name,strerror(errno));3197}31983199if(!cached && !tpatch)3200 st_mode =ce_mode_from_stat(*ce, st->st_mode);32013202if(patch->is_new <0)3203 patch->is_new =0;3204if(!patch->old_mode)3205 patch->old_mode = st_mode;3206if((st_mode ^ patch->old_mode) & S_IFMT)3207returnerror(_("%s: wrong type"), old_name);3208if(st_mode != patch->old_mode)3209warning(_("%shas type%o, expected%o"),3210 old_name, st_mode, patch->old_mode);3211if(!patch->new_mode && !patch->is_delete)3212 patch->new_mode = st_mode;3213return0;32143215 is_new:3216 patch->is_new =1;3217 patch->is_delete =0;3218free(patch->old_name);3219 patch->old_name = NULL;3220return0;3221}32223223/*3224 * Check and apply the patch in-core; leave the result in patch->result3225 * for the caller to write it out to the final destination.3226 */3227static intcheck_patch(struct patch *patch)3228{3229struct stat st;3230const char*old_name = patch->old_name;3231const char*new_name = patch->new_name;3232const char*name = old_name ? old_name : new_name;3233struct cache_entry *ce = NULL;3234struct patch *tpatch;3235int ok_if_exists;3236int status;32373238 patch->rejected =1;/* we will drop this after we succeed */32393240 status =check_preimage(patch, &ce, &st);3241if(status)3242return status;3243 old_name = patch->old_name;32443245if((tpatch =in_fn_table(new_name)) &&3246(was_deleted(tpatch) ||to_be_deleted(tpatch)))3247/*3248 * A type-change diff is always split into a patch to3249 * delete old, immediately followed by a patch to3250 * create new (see diff.c::run_diff()); in such a case3251 * it is Ok that the entry to be deleted by the3252 * previous patch is still in the working tree and in3253 * the index.3254 */3255 ok_if_exists =1;3256else3257 ok_if_exists =0;32583259if(new_name &&3260((0< patch->is_new) | (0< patch->is_rename) | patch->is_copy)) {3261if(check_index &&3262cache_name_pos(new_name,strlen(new_name)) >=0&&3263!ok_if_exists)3264returnerror(_("%s: already exists in index"), new_name);3265if(!cached) {3266int err =check_to_create_blob(new_name, ok_if_exists);3267if(err)3268return err;3269}3270if(!patch->new_mode) {3271if(0< patch->is_new)3272 patch->new_mode = S_IFREG |0644;3273else3274 patch->new_mode = patch->old_mode;3275}3276}32773278if(new_name && old_name) {3279int same = !strcmp(old_name, new_name);3280if(!patch->new_mode)3281 patch->new_mode = patch->old_mode;3282if((patch->old_mode ^ patch->new_mode) & S_IFMT) {3283if(same)3284returnerror(_("new mode (%o) of%sdoes not "3285"match old mode (%o)"),3286 patch->new_mode, new_name,3287 patch->old_mode);3288else3289returnerror(_("new mode (%o) of%sdoes not "3290"match old mode (%o) of%s"),3291 patch->new_mode, new_name,3292 patch->old_mode, old_name);3293}3294}32953296if(apply_data(patch, &st, ce) <0)3297returnerror(_("%s: patch does not apply"), name);3298 patch->rejected =0;3299return0;3300}33013302static intcheck_patch_list(struct patch *patch)3303{3304int err =0;33053306prepare_fn_table(patch);3307while(patch) {3308if(apply_verbosely)3309say_patch_name(stderr,3310_("Checking patch%s..."), patch);3311 err |=check_patch(patch);3312 patch = patch->next;3313}3314return err;3315}33163317/* This function tries to read the sha1 from the current index */3318static intget_current_sha1(const char*path,unsigned char*sha1)3319{3320int pos;33213322if(read_cache() <0)3323return-1;3324 pos =cache_name_pos(path,strlen(path));3325if(pos <0)3326return-1;3327hashcpy(sha1, active_cache[pos]->sha1);3328return0;3329}33303331/* Build an index that contains the just the files needed for a 3way merge */3332static voidbuild_fake_ancestor(struct patch *list,const char*filename)3333{3334struct patch *patch;3335struct index_state result = { NULL };3336int fd;33373338/* Once we start supporting the reverse patch, it may be3339 * worth showing the new sha1 prefix, but until then...3340 */3341for(patch = list; patch; patch = patch->next) {3342const unsigned char*sha1_ptr;3343unsigned char sha1[20];3344struct cache_entry *ce;3345const char*name;33463347 name = patch->old_name ? patch->old_name : patch->new_name;3348if(0< patch->is_new)3349continue;3350else if(get_sha1(patch->old_sha1_prefix, sha1))3351/* git diff has no index line for mode/type changes */3352if(!patch->lines_added && !patch->lines_deleted) {3353if(get_current_sha1(patch->old_name, sha1))3354die("mode change for%s, which is not "3355"in current HEAD", name);3356 sha1_ptr = sha1;3357}else3358die("sha1 information is lacking or useless "3359"(%s).", name);3360else3361 sha1_ptr = sha1;33623363 ce =make_cache_entry(patch->old_mode, sha1_ptr, name,0,0);3364if(!ce)3365die(_("make_cache_entry failed for path '%s'"), name);3366if(add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD))3367die("Could not add%sto temporary index", name);3368}33693370 fd =open(filename, O_WRONLY | O_CREAT,0666);3371if(fd <0||write_index(&result, fd) ||close(fd))3372die("Could not write temporary index to%s", filename);33733374discard_index(&result);3375}33763377static voidstat_patch_list(struct patch *patch)3378{3379int files, adds, dels;33803381for(files = adds = dels =0; patch ; patch = patch->next) {3382 files++;3383 adds += patch->lines_added;3384 dels += patch->lines_deleted;3385show_stats(patch);3386}33873388print_stat_summary(stdout, files, adds, dels);3389}33903391static voidnumstat_patch_list(struct patch *patch)3392{3393for( ; patch; patch = patch->next) {3394const char*name;3395 name = patch->new_name ? patch->new_name : patch->old_name;3396if(patch->is_binary)3397printf("-\t-\t");3398else3399printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);3400write_name_quoted(name, stdout, line_termination);3401}3402}34033404static voidshow_file_mode_name(const char*newdelete,unsigned int mode,const char*name)3405{3406if(mode)3407printf("%smode%06o%s\n", newdelete, mode, name);3408else3409printf("%s %s\n", newdelete, name);3410}34113412static voidshow_mode_change(struct patch *p,int show_name)3413{3414if(p->old_mode && p->new_mode && p->old_mode != p->new_mode) {3415if(show_name)3416printf(" mode change%06o =>%06o%s\n",3417 p->old_mode, p->new_mode, p->new_name);3418else3419printf(" mode change%06o =>%06o\n",3420 p->old_mode, p->new_mode);3421}3422}34233424static voidshow_rename_copy(struct patch *p)3425{3426const char*renamecopy = p->is_rename ?"rename":"copy";3427const char*old, *new;34283429/* Find common prefix */3430 old = p->old_name;3431new= p->new_name;3432while(1) {3433const char*slash_old, *slash_new;3434 slash_old =strchr(old,'/');3435 slash_new =strchr(new,'/');3436if(!slash_old ||3437!slash_new ||3438 slash_old - old != slash_new -new||3439memcmp(old,new, slash_new -new))3440break;3441 old = slash_old +1;3442new= slash_new +1;3443}3444/* p->old_name thru old is the common prefix, and old and new3445 * through the end of names are renames3446 */3447if(old != p->old_name)3448printf("%s%.*s{%s=>%s} (%d%%)\n", renamecopy,3449(int)(old - p->old_name), p->old_name,3450 old,new, p->score);3451else3452printf("%s %s=>%s(%d%%)\n", renamecopy,3453 p->old_name, p->new_name, p->score);3454show_mode_change(p,0);3455}34563457static voidsummary_patch_list(struct patch *patch)3458{3459struct patch *p;34603461for(p = patch; p; p = p->next) {3462if(p->is_new)3463show_file_mode_name("create", p->new_mode, p->new_name);3464else if(p->is_delete)3465show_file_mode_name("delete", p->old_mode, p->old_name);3466else{3467if(p->is_rename || p->is_copy)3468show_rename_copy(p);3469else{3470if(p->score) {3471printf(" rewrite%s(%d%%)\n",3472 p->new_name, p->score);3473show_mode_change(p,0);3474}3475else3476show_mode_change(p,1);3477}3478}3479}3480}34813482static voidpatch_stats(struct patch *patch)3483{3484int lines = patch->lines_added + patch->lines_deleted;34853486if(lines > max_change)3487 max_change = lines;3488if(patch->old_name) {3489int len =quote_c_style(patch->old_name, NULL, NULL,0);3490if(!len)3491 len =strlen(patch->old_name);3492if(len > max_len)3493 max_len = len;3494}3495if(patch->new_name) {3496int len =quote_c_style(patch->new_name, NULL, NULL,0);3497if(!len)3498 len =strlen(patch->new_name);3499if(len > max_len)3500 max_len = len;3501}3502}35033504static voidremove_file(struct patch *patch,int rmdir_empty)3505{3506if(update_index) {3507if(remove_file_from_cache(patch->old_name) <0)3508die(_("unable to remove%sfrom index"), patch->old_name);3509}3510if(!cached) {3511if(!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {3512remove_path(patch->old_name);3513}3514}3515}35163517static voidadd_index_file(const char*path,unsigned mode,void*buf,unsigned long size)3518{3519struct stat st;3520struct cache_entry *ce;3521int namelen =strlen(path);3522unsigned ce_size =cache_entry_size(namelen);35233524if(!update_index)3525return;35263527 ce =xcalloc(1, ce_size);3528memcpy(ce->name, path, namelen);3529 ce->ce_mode =create_ce_mode(mode);3530 ce->ce_flags = namelen;3531if(S_ISGITLINK(mode)) {3532const char*s = buf;35333534if(get_sha1_hex(s +strlen("Subproject commit "), ce->sha1))3535die(_("corrupt patch for subproject%s"), path);3536}else{3537if(!cached) {3538if(lstat(path, &st) <0)3539die_errno(_("unable to stat newly created file '%s'"),3540 path);3541fill_stat_cache_info(ce, &st);3542}3543if(write_sha1_file(buf, size, blob_type, ce->sha1) <0)3544die(_("unable to create backing store for newly created file%s"), path);3545}3546if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0)3547die(_("unable to add cache entry for%s"), path);3548}35493550static inttry_create_file(const char*path,unsigned int mode,const char*buf,unsigned long size)3551{3552int fd;3553struct strbuf nbuf = STRBUF_INIT;35543555if(S_ISGITLINK(mode)) {3556struct stat st;3557if(!lstat(path, &st) &&S_ISDIR(st.st_mode))3558return0;3559returnmkdir(path,0777);3560}35613562if(has_symlinks &&S_ISLNK(mode))3563/* Although buf:size is counted string, it also is NUL3564 * terminated.3565 */3566returnsymlink(buf, path);35673568 fd =open(path, O_CREAT | O_EXCL | O_WRONLY, (mode &0100) ?0777:0666);3569if(fd <0)3570return-1;35713572if(convert_to_working_tree(path, buf, size, &nbuf)) {3573 size = nbuf.len;3574 buf = nbuf.buf;3575}3576write_or_die(fd, buf, size);3577strbuf_release(&nbuf);35783579if(close(fd) <0)3580die_errno(_("closing file '%s'"), path);3581return0;3582}35833584/*3585 * We optimistically assume that the directories exist,3586 * which is true 99% of the time anyway. If they don't,3587 * we create them and try again.3588 */3589static voidcreate_one_file(char*path,unsigned mode,const char*buf,unsigned long size)3590{3591if(cached)3592return;3593if(!try_create_file(path, mode, buf, size))3594return;35953596if(errno == ENOENT) {3597if(safe_create_leading_directories(path))3598return;3599if(!try_create_file(path, mode, buf, size))3600return;3601}36023603if(errno == EEXIST || errno == EACCES) {3604/* We may be trying to create a file where a directory3605 * used to be.3606 */3607struct stat st;3608if(!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))3609 errno = EEXIST;3610}36113612if(errno == EEXIST) {3613unsigned int nr =getpid();36143615for(;;) {3616char newpath[PATH_MAX];3617mksnpath(newpath,sizeof(newpath),"%s~%u", path, nr);3618if(!try_create_file(newpath, mode, buf, size)) {3619if(!rename(newpath, path))3620return;3621unlink_or_warn(newpath);3622break;3623}3624if(errno != EEXIST)3625break;3626++nr;3627}3628}3629die_errno(_("unable to write file '%s' mode%o"), path, mode);3630}36313632static voidcreate_file(struct patch *patch)3633{3634char*path = patch->new_name;3635unsigned mode = patch->new_mode;3636unsigned long size = patch->resultsize;3637char*buf = patch->result;36383639if(!mode)3640 mode = S_IFREG |0644;3641create_one_file(path, mode, buf, size);3642add_index_file(path, mode, buf, size);3643}36443645/* phase zero is to remove, phase one is to create */3646static voidwrite_out_one_result(struct patch *patch,int phase)3647{3648if(patch->is_delete >0) {3649if(phase ==0)3650remove_file(patch,1);3651return;3652}3653if(patch->is_new >0|| patch->is_copy) {3654if(phase ==1)3655create_file(patch);3656return;3657}3658/*3659 * Rename or modification boils down to the same3660 * thing: remove the old, write the new3661 */3662if(phase ==0)3663remove_file(patch, patch->is_rename);3664if(phase ==1)3665create_file(patch);3666}36673668static intwrite_out_one_reject(struct patch *patch)3669{3670FILE*rej;3671char namebuf[PATH_MAX];3672struct fragment *frag;3673int cnt =0;3674struct strbuf sb = STRBUF_INIT;36753676for(cnt =0, frag = patch->fragments; frag; frag = frag->next) {3677if(!frag->rejected)3678continue;3679 cnt++;3680}36813682if(!cnt) {3683if(apply_verbosely)3684say_patch_name(stderr,3685_("Applied patch%scleanly."), patch);3686return0;3687}36883689/* This should not happen, because a removal patch that leaves3690 * contents are marked "rejected" at the patch level.3691 */3692if(!patch->new_name)3693die(_("internal error"));36943695/* Say this even without --verbose */3696strbuf_addf(&sb,Q_("Applying patch %%swith%dreject...",3697"Applying patch %%swith%drejects...",3698 cnt),3699 cnt);3700say_patch_name(stderr, sb.buf, patch);3701strbuf_release(&sb);37023703 cnt =strlen(patch->new_name);3704if(ARRAY_SIZE(namebuf) <= cnt +5) {3705 cnt =ARRAY_SIZE(namebuf) -5;3706warning(_("truncating .rej filename to %.*s.rej"),3707 cnt -1, patch->new_name);3708}3709memcpy(namebuf, patch->new_name, cnt);3710memcpy(namebuf + cnt,".rej",5);37113712 rej =fopen(namebuf,"w");3713if(!rej)3714returnerror(_("cannot open%s:%s"), namebuf,strerror(errno));37153716/* Normal git tools never deal with .rej, so do not pretend3717 * this is a git patch by saying --git nor give extended3718 * headers. While at it, maybe please "kompare" that wants3719 * the trailing TAB and some garbage at the end of line ;-).3720 */3721fprintf(rej,"diff a/%sb/%s\t(rejected hunks)\n",3722 patch->new_name, patch->new_name);3723for(cnt =1, frag = patch->fragments;3724 frag;3725 cnt++, frag = frag->next) {3726if(!frag->rejected) {3727fprintf_ln(stderr,_("Hunk #%dapplied cleanly."), cnt);3728continue;3729}3730fprintf_ln(stderr,_("Rejected hunk #%d."), cnt);3731fprintf(rej,"%.*s", frag->size, frag->patch);3732if(frag->patch[frag->size-1] !='\n')3733fputc('\n', rej);3734}3735fclose(rej);3736return-1;3737}37383739static intwrite_out_results(struct patch *list)3740{3741int phase;3742int errs =0;3743struct patch *l;37443745for(phase =0; phase <2; phase++) {3746 l = list;3747while(l) {3748if(l->rejected)3749 errs =1;3750else{3751write_out_one_result(l, phase);3752if(phase ==1&&write_out_one_reject(l))3753 errs =1;3754}3755 l = l->next;3756}3757}3758return errs;3759}37603761static struct lock_file lock_file;37623763static struct string_list limit_by_name;3764static int has_include;3765static voidadd_name_limit(const char*name,int exclude)3766{3767struct string_list_item *it;37683769 it =string_list_append(&limit_by_name, name);3770 it->util = exclude ? NULL : (void*)1;3771}37723773static intuse_patch(struct patch *p)3774{3775const char*pathname = p->new_name ? p->new_name : p->old_name;3776int i;37773778/* Paths outside are not touched regardless of "--include" */3779if(0< prefix_length) {3780int pathlen =strlen(pathname);3781if(pathlen <= prefix_length ||3782memcmp(prefix, pathname, prefix_length))3783return0;3784}37853786/* See if it matches any of exclude/include rule */3787for(i =0; i < limit_by_name.nr; i++) {3788struct string_list_item *it = &limit_by_name.items[i];3789if(!fnmatch(it->string, pathname,0))3790return(it->util != NULL);3791}37923793/*3794 * If we had any include, a path that does not match any rule is3795 * not used. Otherwise, we saw bunch of exclude rules (or none)3796 * and such a path is used.3797 */3798return!has_include;3799}380038013802static voidprefix_one(char**name)3803{3804char*old_name = *name;3805if(!old_name)3806return;3807*name =xstrdup(prefix_filename(prefix, prefix_length, *name));3808free(old_name);3809}38103811static voidprefix_patches(struct patch *p)3812{3813if(!prefix || p->is_toplevel_relative)3814return;3815for( ; p; p = p->next) {3816prefix_one(&p->new_name);3817prefix_one(&p->old_name);3818}3819}38203821#define INACCURATE_EOF (1<<0)3822#define RECOUNT (1<<1)38233824static intapply_patch(int fd,const char*filename,int options)3825{3826size_t offset;3827struct strbuf buf = STRBUF_INIT;/* owns the patch text */3828struct patch *list = NULL, **listp = &list;3829int skipped_patch =0;38303831 patch_input_file = filename;3832read_patch_file(&buf, fd);3833 offset =0;3834while(offset < buf.len) {3835struct patch *patch;3836int nr;38373838 patch =xcalloc(1,sizeof(*patch));3839 patch->inaccurate_eof = !!(options & INACCURATE_EOF);3840 patch->recount = !!(options & RECOUNT);3841 nr =parse_chunk(buf.buf + offset, buf.len - offset, patch);3842if(nr <0)3843break;3844if(apply_in_reverse)3845reverse_patches(patch);3846if(prefix)3847prefix_patches(patch);3848if(use_patch(patch)) {3849patch_stats(patch);3850*listp = patch;3851 listp = &patch->next;3852}3853else{3854free_patch(patch);3855 skipped_patch++;3856}3857 offset += nr;3858}38593860if(!list && !skipped_patch)3861die(_("unrecognized input"));38623863if(whitespace_error && (ws_error_action == die_on_ws_error))3864 apply =0;38653866 update_index = check_index && apply;3867if(update_index && newfd <0)3868 newfd =hold_locked_index(&lock_file,1);38693870if(check_index) {3871if(read_cache() <0)3872die(_("unable to read index file"));3873}38743875if((check || apply) &&3876check_patch_list(list) <0&&3877!apply_with_reject)3878exit(1);38793880if(apply &&write_out_results(list))3881exit(1);38823883if(fake_ancestor)3884build_fake_ancestor(list, fake_ancestor);38853886if(diffstat)3887stat_patch_list(list);38883889if(numstat)3890numstat_patch_list(list);38913892if(summary)3893summary_patch_list(list);38943895free_patch_list(list);3896strbuf_release(&buf);3897string_list_clear(&fn_table,0);3898return0;3899}39003901static intgit_apply_config(const char*var,const char*value,void*cb)3902{3903if(!strcmp(var,"apply.whitespace"))3904returngit_config_string(&apply_default_whitespace, var, value);3905else if(!strcmp(var,"apply.ignorewhitespace"))3906returngit_config_string(&apply_default_ignorewhitespace, var, value);3907returngit_default_config(var, value, cb);3908}39093910static intoption_parse_exclude(const struct option *opt,3911const char*arg,int unset)3912{3913add_name_limit(arg,1);3914return0;3915}39163917static intoption_parse_include(const struct option *opt,3918const char*arg,int unset)3919{3920add_name_limit(arg,0);3921 has_include =1;3922return0;3923}39243925static intoption_parse_p(const struct option *opt,3926const char*arg,int unset)3927{3928 p_value =atoi(arg);3929 p_value_known =1;3930return0;3931}39323933static intoption_parse_z(const struct option *opt,3934const char*arg,int unset)3935{3936if(unset)3937 line_termination ='\n';3938else3939 line_termination =0;3940return0;3941}39423943static intoption_parse_space_change(const struct option *opt,3944const char*arg,int unset)3945{3946if(unset)3947 ws_ignore_action = ignore_ws_none;3948else3949 ws_ignore_action = ignore_ws_change;3950return0;3951}39523953static intoption_parse_whitespace(const struct option *opt,3954const char*arg,int unset)3955{3956const char**whitespace_option = opt->value;39573958*whitespace_option = arg;3959parse_whitespace_option(arg);3960return0;3961}39623963static intoption_parse_directory(const struct option *opt,3964const char*arg,int unset)3965{3966 root_len =strlen(arg);3967if(root_len && arg[root_len -1] !='/') {3968char*new_root;3969 root = new_root =xmalloc(root_len +2);3970strcpy(new_root, arg);3971strcpy(new_root + root_len++,"/");3972}else3973 root = arg;3974return0;3975}39763977intcmd_apply(int argc,const char**argv,const char*prefix_)3978{3979int i;3980int errs =0;3981int is_not_gitdir = !startup_info->have_repository;3982int force_apply =0;39833984const char*whitespace_option = NULL;39853986struct option builtin_apply_options[] = {3987{ OPTION_CALLBACK,0,"exclude", NULL,N_("path"),3988N_("don't apply changes matching the given path"),39890, option_parse_exclude },3990{ OPTION_CALLBACK,0,"include", NULL,N_("path"),3991N_("apply changes matching the given path"),39920, option_parse_include },3993{ OPTION_CALLBACK,'p', NULL, NULL,N_("num"),3994N_("remove <num> leading slashes from traditional diff paths"),39950, option_parse_p },3996OPT_BOOLEAN(0,"no-add", &no_add,3997N_("ignore additions made by the patch")),3998OPT_BOOLEAN(0,"stat", &diffstat,3999N_("instead of applying the patch, output diffstat for the input")),4000OPT_NOOP_NOARG(0,"allow-binary-replacement"),4001OPT_NOOP_NOARG(0,"binary"),4002OPT_BOOLEAN(0,"numstat", &numstat,4003N_("shows number of added and deleted lines in decimal notation")),4004OPT_BOOLEAN(0,"summary", &summary,4005N_("instead of applying the patch, output a summary for the input")),4006OPT_BOOLEAN(0,"check", &check,4007N_("instead of applying the patch, see if the patch is applicable")),4008OPT_BOOLEAN(0,"index", &check_index,4009N_("make sure the patch is applicable to the current index")),4010OPT_BOOLEAN(0,"cached", &cached,4011N_("apply a patch without touching the working tree")),4012OPT_BOOLEAN(0,"apply", &force_apply,4013N_("also apply the patch (use with --stat/--summary/--check)")),4014OPT_FILENAME(0,"build-fake-ancestor", &fake_ancestor,4015N_("build a temporary index based on embedded index information")),4016{ OPTION_CALLBACK,'z', NULL, NULL, NULL,4017N_("paths are separated with NUL character"),4018 PARSE_OPT_NOARG, option_parse_z },4019OPT_INTEGER('C', NULL, &p_context,4020N_("ensure at least <n> lines of context match")),4021{ OPTION_CALLBACK,0,"whitespace", &whitespace_option,N_("action"),4022N_("detect new or modified lines that have whitespace errors"),40230, option_parse_whitespace },4024{ OPTION_CALLBACK,0,"ignore-space-change", NULL, NULL,4025N_("ignore changes in whitespace when finding context"),4026 PARSE_OPT_NOARG, option_parse_space_change },4027{ OPTION_CALLBACK,0,"ignore-whitespace", NULL, NULL,4028N_("ignore changes in whitespace when finding context"),4029 PARSE_OPT_NOARG, option_parse_space_change },4030OPT_BOOLEAN('R',"reverse", &apply_in_reverse,4031N_("apply the patch in reverse")),4032OPT_BOOLEAN(0,"unidiff-zero", &unidiff_zero,4033N_("don't expect at least one line of context")),4034OPT_BOOLEAN(0,"reject", &apply_with_reject,4035N_("leave the rejected hunks in corresponding *.rej files")),4036OPT_BOOLEAN(0,"allow-overlap", &allow_overlap,4037N_("allow overlapping hunks")),4038OPT__VERBOSE(&apply_verbosely,N_("be verbose")),4039OPT_BIT(0,"inaccurate-eof", &options,4040N_("tolerate incorrectly detected missing new-line at the end of file"),4041 INACCURATE_EOF),4042OPT_BIT(0,"recount", &options,4043N_("do not trust the line counts in the hunk headers"),4044 RECOUNT),4045{ OPTION_CALLBACK,0,"directory", NULL,N_("root"),4046N_("prepend <root> to all filenames"),40470, option_parse_directory },4048OPT_END()4049};40504051 prefix = prefix_;4052 prefix_length = prefix ?strlen(prefix) :0;4053git_config(git_apply_config, NULL);4054if(apply_default_whitespace)4055parse_whitespace_option(apply_default_whitespace);4056if(apply_default_ignorewhitespace)4057parse_ignorewhitespace_option(apply_default_ignorewhitespace);40584059 argc =parse_options(argc, argv, prefix, builtin_apply_options,4060 apply_usage,0);40614062if(apply_with_reject)4063 apply = apply_verbosely =1;4064if(!force_apply && (diffstat || numstat || summary || check || fake_ancestor))4065 apply =0;4066if(check_index && is_not_gitdir)4067die(_("--index outside a repository"));4068if(cached) {4069if(is_not_gitdir)4070die(_("--cached outside a repository"));4071 check_index =1;4072}4073for(i =0; i < argc; i++) {4074const char*arg = argv[i];4075int fd;40764077if(!strcmp(arg,"-")) {4078 errs |=apply_patch(0,"<stdin>", options);4079 read_stdin =0;4080continue;4081}else if(0< prefix_length)4082 arg =prefix_filename(prefix, prefix_length, arg);40834084 fd =open(arg, O_RDONLY);4085if(fd <0)4086die_errno(_("can't open patch '%s'"), arg);4087 read_stdin =0;4088set_default_whitespace_mode(whitespace_option);4089 errs |=apply_patch(fd, arg, options);4090close(fd);4091}4092set_default_whitespace_mode(whitespace_option);4093if(read_stdin)4094 errs |=apply_patch(0,"<stdin>", options);4095if(whitespace_error) {4096if(squelch_whitespace_errors &&4097 squelch_whitespace_errors < whitespace_error) {4098int squelched =4099 whitespace_error - squelch_whitespace_errors;4100warning(Q_("squelched%dwhitespace error",4101"squelched%dwhitespace errors",4102 squelched),4103 squelched);4104}4105if(ws_error_action == die_on_ws_error)4106die(Q_("%dline adds whitespace errors.",4107"%dlines add whitespace errors.",4108 whitespace_error),4109 whitespace_error);4110if(applied_after_fixing_ws && apply)4111warning("%dline%sapplied after"4112" fixing whitespace errors.",4113 applied_after_fixing_ws,4114 applied_after_fixing_ws ==1?"":"s");4115else if(whitespace_error)4116warning(Q_("%dline adds whitespace errors.",4117"%dlines add whitespace errors.",4118 whitespace_error),4119 whitespace_error);4120}41214122if(update_index) {4123if(write_cache(newfd, active_cache, active_nr) ||4124commit_locked_index(&lock_file))4125die(_("Unable to write new index file"));4126}41274128return!!errs;4129}