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}10881089static const char*stop_at_slash(const char*line,int llen)1090{1091int nslash = p_value;1092int i;10931094for(i =0; i < llen; i++) {1095int ch = line[i];1096if(ch =='/'&& --nslash <=0)1097return&line[i];1098}1099return NULL;1100}11011102/*1103 * This is to extract the same name that appears on "diff --git"1104 * line. We do not find and return anything if it is a rename1105 * patch, and it is OK because we will find the name elsewhere.1106 * We need to reliably find name only when it is mode-change only,1107 * creation or deletion of an empty file. In any of these cases,1108 * both sides are the same name under a/ and b/ respectively.1109 */1110static char*git_header_name(const char*line,int llen)1111{1112const char*name;1113const char*second = NULL;1114size_t len, line_len;11151116 line +=strlen("diff --git ");1117 llen -=strlen("diff --git ");11181119if(*line =='"') {1120const char*cp;1121struct strbuf first = STRBUF_INIT;1122struct strbuf sp = STRBUF_INIT;11231124if(unquote_c_style(&first, line, &second))1125goto free_and_fail1;11261127/* advance to the first slash */1128 cp =stop_at_slash(first.buf, first.len);1129/* we do not accept absolute paths */1130if(!cp || cp == first.buf)1131goto free_and_fail1;1132strbuf_remove(&first,0, cp +1- first.buf);11331134/*1135 * second points at one past closing dq of name.1136 * find the second name.1137 */1138while((second < line + llen) &&isspace(*second))1139 second++;11401141if(line + llen <= second)1142goto free_and_fail1;1143if(*second =='"') {1144if(unquote_c_style(&sp, second, NULL))1145goto free_and_fail1;1146 cp =stop_at_slash(sp.buf, sp.len);1147if(!cp || cp == sp.buf)1148goto free_and_fail1;1149/* They must match, otherwise ignore */1150if(strcmp(cp +1, first.buf))1151goto free_and_fail1;1152strbuf_release(&sp);1153returnstrbuf_detach(&first, NULL);1154}11551156/* unquoted second */1157 cp =stop_at_slash(second, line + llen - second);1158if(!cp || cp == second)1159goto free_and_fail1;1160 cp++;1161if(line + llen - cp != first.len +1||1162memcmp(first.buf, cp, first.len))1163goto free_and_fail1;1164returnstrbuf_detach(&first, NULL);11651166 free_and_fail1:1167strbuf_release(&first);1168strbuf_release(&sp);1169return NULL;1170}11711172/* unquoted first name */1173 name =stop_at_slash(line, llen);1174if(!name || name == line)1175return NULL;1176 name++;11771178/*1179 * since the first name is unquoted, a dq if exists must be1180 * the beginning of the second name.1181 */1182for(second = name; second < line + llen; second++) {1183if(*second =='"') {1184struct strbuf sp = STRBUF_INIT;1185const char*np;11861187if(unquote_c_style(&sp, second, NULL))1188goto free_and_fail2;11891190 np =stop_at_slash(sp.buf, sp.len);1191if(!np || np == sp.buf)1192goto free_and_fail2;1193 np++;11941195 len = sp.buf + sp.len - np;1196if(len < second - name &&1197!strncmp(np, name, len) &&1198isspace(name[len])) {1199/* Good */1200strbuf_remove(&sp,0, np - sp.buf);1201returnstrbuf_detach(&sp, NULL);1202}12031204 free_and_fail2:1205strbuf_release(&sp);1206return NULL;1207}1208}12091210/*1211 * Accept a name only if it shows up twice, exactly the same1212 * form.1213 */1214 second =strchr(name,'\n');1215if(!second)1216return NULL;1217 line_len = second - name;1218for(len =0; ; len++) {1219switch(name[len]) {1220default:1221continue;1222case'\n':1223return NULL;1224case'\t':case' ':1225 second =stop_at_slash(name + len, line_len - len);1226if(!second)1227return NULL;1228 second++;1229if(second[len] =='\n'&& !strncmp(name, second, len)) {1230returnxmemdupz(name, len);1231}1232}1233}1234}12351236/* Verify that we recognize the lines following a git header */1237static intparse_git_header(const char*line,int len,unsigned int size,struct patch *patch)1238{1239unsigned long offset;12401241/* A git diff has explicit new/delete information, so we don't guess */1242 patch->is_new =0;1243 patch->is_delete =0;12441245/*1246 * Some things may not have the old name in the1247 * rest of the headers anywhere (pure mode changes,1248 * or removing or adding empty files), so we get1249 * the default name from the header.1250 */1251 patch->def_name =git_header_name(line, len);1252if(patch->def_name && root) {1253char*s =xmalloc(root_len +strlen(patch->def_name) +1);1254strcpy(s, root);1255strcpy(s + root_len, patch->def_name);1256free(patch->def_name);1257 patch->def_name = s;1258}12591260 line += len;1261 size -= len;1262 linenr++;1263for(offset = len ; size >0; offset += len, size -= len, line += len, linenr++) {1264static const struct opentry {1265const char*str;1266int(*fn)(const char*,struct patch *);1267} optable[] = {1268{"@@ -", gitdiff_hdrend },1269{"--- ", gitdiff_oldname },1270{"+++ ", gitdiff_newname },1271{"old mode ", gitdiff_oldmode },1272{"new mode ", gitdiff_newmode },1273{"deleted file mode ", gitdiff_delete },1274{"new file mode ", gitdiff_newfile },1275{"copy from ", gitdiff_copysrc },1276{"copy to ", gitdiff_copydst },1277{"rename old ", gitdiff_renamesrc },1278{"rename new ", gitdiff_renamedst },1279{"rename from ", gitdiff_renamesrc },1280{"rename to ", gitdiff_renamedst },1281{"similarity index ", gitdiff_similarity },1282{"dissimilarity index ", gitdiff_dissimilarity },1283{"index ", gitdiff_index },1284{"", gitdiff_unrecognized },1285};1286int i;12871288 len =linelen(line, size);1289if(!len || line[len-1] !='\n')1290break;1291for(i =0; i <ARRAY_SIZE(optable); i++) {1292const struct opentry *p = optable + i;1293int oplen =strlen(p->str);1294if(len < oplen ||memcmp(p->str, line, oplen))1295continue;1296if(p->fn(line + oplen, patch) <0)1297return offset;1298break;1299}1300}13011302return offset;1303}13041305static intparse_num(const char*line,unsigned long*p)1306{1307char*ptr;13081309if(!isdigit(*line))1310return0;1311*p =strtoul(line, &ptr,10);1312return ptr - line;1313}13141315static intparse_range(const char*line,int len,int offset,const char*expect,1316unsigned long*p1,unsigned long*p2)1317{1318int digits, ex;13191320if(offset <0|| offset >= len)1321return-1;1322 line += offset;1323 len -= offset;13241325 digits =parse_num(line, p1);1326if(!digits)1327return-1;13281329 offset += digits;1330 line += digits;1331 len -= digits;13321333*p2 =1;1334if(*line ==',') {1335 digits =parse_num(line+1, p2);1336if(!digits)1337return-1;13381339 offset += digits+1;1340 line += digits+1;1341 len -= digits+1;1342}13431344 ex =strlen(expect);1345if(ex > len)1346return-1;1347if(memcmp(line, expect, ex))1348return-1;13491350return offset + ex;1351}13521353static voidrecount_diff(const char*line,int size,struct fragment *fragment)1354{1355int oldlines =0, newlines =0, ret =0;13561357if(size <1) {1358warning("recount: ignore empty hunk");1359return;1360}13611362for(;;) {1363int len =linelen(line, size);1364 size -= len;1365 line += len;13661367if(size <1)1368break;13691370switch(*line) {1371case' ':case'\n':1372 newlines++;1373/* fall through */1374case'-':1375 oldlines++;1376continue;1377case'+':1378 newlines++;1379continue;1380case'\\':1381continue;1382case'@':1383 ret = size <3||prefixcmp(line,"@@ ");1384break;1385case'd':1386 ret = size <5||prefixcmp(line,"diff ");1387break;1388default:1389 ret = -1;1390break;1391}1392if(ret) {1393warning(_("recount: unexpected line: %.*s"),1394(int)linelen(line, size), line);1395return;1396}1397break;1398}1399 fragment->oldlines = oldlines;1400 fragment->newlines = newlines;1401}14021403/*1404 * Parse a unified diff fragment header of the1405 * form "@@ -a,b +c,d @@"1406 */1407static intparse_fragment_header(const char*line,int len,struct fragment *fragment)1408{1409int offset;14101411if(!len || line[len-1] !='\n')1412return-1;14131414/* Figure out the number of lines in a fragment */1415 offset =parse_range(line, len,4," +", &fragment->oldpos, &fragment->oldlines);1416 offset =parse_range(line, len, offset," @@", &fragment->newpos, &fragment->newlines);14171418return offset;1419}14201421static intfind_header(const char*line,unsigned long size,int*hdrsize,struct patch *patch)1422{1423unsigned long offset, len;14241425 patch->is_toplevel_relative =0;1426 patch->is_rename = patch->is_copy =0;1427 patch->is_new = patch->is_delete = -1;1428 patch->old_mode = patch->new_mode =0;1429 patch->old_name = patch->new_name = NULL;1430for(offset =0; size >0; offset += len, size -= len, line += len, linenr++) {1431unsigned long nextlen;14321433 len =linelen(line, size);1434if(!len)1435break;14361437/* Testing this early allows us to take a few shortcuts.. */1438if(len <6)1439continue;14401441/*1442 * Make sure we don't find any unconnected patch fragments.1443 * That's a sign that we didn't find a header, and that a1444 * patch has become corrupted/broken up.1445 */1446if(!memcmp("@@ -", line,4)) {1447struct fragment dummy;1448if(parse_fragment_header(line, len, &dummy) <0)1449continue;1450die(_("patch fragment without header at line%d: %.*s"),1451 linenr, (int)len-1, line);1452}14531454if(size < len +6)1455break;14561457/*1458 * Git patch? It might not have a real patch, just a rename1459 * or mode change, so we handle that specially1460 */1461if(!memcmp("diff --git ", line,11)) {1462int git_hdr_len =parse_git_header(line, len, size, patch);1463if(git_hdr_len <= len)1464continue;1465if(!patch->old_name && !patch->new_name) {1466if(!patch->def_name)1467die(Q_("git diff header lacks filename information when removing "1468"%dleading pathname component (line%d)",1469"git diff header lacks filename information when removing "1470"%dleading pathname components (line%d)",1471 p_value),1472 p_value, linenr);1473 patch->old_name =xstrdup(patch->def_name);1474 patch->new_name =xstrdup(patch->def_name);1475}1476if(!patch->is_delete && !patch->new_name)1477die("git diff header lacks filename information "1478"(line%d)", linenr);1479 patch->is_toplevel_relative =1;1480*hdrsize = git_hdr_len;1481return offset;1482}14831484/* --- followed by +++ ? */1485if(memcmp("--- ", line,4) ||memcmp("+++ ", line + len,4))1486continue;14871488/*1489 * We only accept unified patches, so we want it to1490 * at least have "@@ -a,b +c,d @@\n", which is 14 chars1491 * minimum ("@@ -0,0 +1 @@\n" is the shortest).1492 */1493 nextlen =linelen(line + len, size - len);1494if(size < nextlen +14||memcmp("@@ -", line + len + nextlen,4))1495continue;14961497/* Ok, we'll consider it a patch */1498parse_traditional_patch(line, line+len, patch);1499*hdrsize = len + nextlen;1500 linenr +=2;1501return offset;1502}1503return-1;1504}15051506static voidrecord_ws_error(unsigned result,const char*line,int len,int linenr)1507{1508char*err;15091510if(!result)1511return;15121513 whitespace_error++;1514if(squelch_whitespace_errors &&1515 squelch_whitespace_errors < whitespace_error)1516return;15171518 err =whitespace_error_string(result);1519fprintf(stderr,"%s:%d:%s.\n%.*s\n",1520 patch_input_file, linenr, err, len, line);1521free(err);1522}15231524static voidcheck_whitespace(const char*line,int len,unsigned ws_rule)1525{1526unsigned result =ws_check(line +1, len -1, ws_rule);15271528record_ws_error(result, line +1, len -2, linenr);1529}15301531/*1532 * Parse a unified diff. Note that this really needs to parse each1533 * fragment separately, since the only way to know the difference1534 * between a "---" that is part of a patch, and a "---" that starts1535 * the next patch is to look at the line counts..1536 */1537static intparse_fragment(const char*line,unsigned long size,1538struct patch *patch,struct fragment *fragment)1539{1540int added, deleted;1541int len =linelen(line, size), offset;1542unsigned long oldlines, newlines;1543unsigned long leading, trailing;15441545 offset =parse_fragment_header(line, len, fragment);1546if(offset <0)1547return-1;1548if(offset >0&& patch->recount)1549recount_diff(line + offset, size - offset, fragment);1550 oldlines = fragment->oldlines;1551 newlines = fragment->newlines;1552 leading =0;1553 trailing =0;15541555/* Parse the thing.. */1556 line += len;1557 size -= len;1558 linenr++;1559 added = deleted =0;1560for(offset = len;15610< size;1562 offset += len, size -= len, line += len, linenr++) {1563if(!oldlines && !newlines)1564break;1565 len =linelen(line, size);1566if(!len || line[len-1] !='\n')1567return-1;1568switch(*line) {1569default:1570return-1;1571case'\n':/* newer GNU diff, an empty context line */1572case' ':1573 oldlines--;1574 newlines--;1575if(!deleted && !added)1576 leading++;1577 trailing++;1578break;1579case'-':1580if(apply_in_reverse &&1581 ws_error_action != nowarn_ws_error)1582check_whitespace(line, len, patch->ws_rule);1583 deleted++;1584 oldlines--;1585 trailing =0;1586break;1587case'+':1588if(!apply_in_reverse &&1589 ws_error_action != nowarn_ws_error)1590check_whitespace(line, len, patch->ws_rule);1591 added++;1592 newlines--;1593 trailing =0;1594break;15951596/*1597 * We allow "\ No newline at end of file". Depending1598 * on locale settings when the patch was produced we1599 * don't know what this line looks like. The only1600 * thing we do know is that it begins with "\ ".1601 * Checking for 12 is just for sanity check -- any1602 * l10n of "\ No newline..." is at least that long.1603 */1604case'\\':1605if(len <12||memcmp(line,"\\",2))1606return-1;1607break;1608}1609}1610if(oldlines || newlines)1611return-1;1612 fragment->leading = leading;1613 fragment->trailing = trailing;16141615/*1616 * If a fragment ends with an incomplete line, we failed to include1617 * it in the above loop because we hit oldlines == newlines == 01618 * before seeing it.1619 */1620if(12< size && !memcmp(line,"\\",2))1621 offset +=linelen(line, size);16221623 patch->lines_added += added;1624 patch->lines_deleted += deleted;16251626if(0< patch->is_new && oldlines)1627returnerror(_("new file depends on old contents"));1628if(0< patch->is_delete && newlines)1629returnerror(_("deleted file still has contents"));1630return offset;1631}16321633/*1634 * We have seen "diff --git a/... b/..." header (or a traditional patch1635 * header). Read hunks that belong to this patch into fragments and hang1636 * them to the given patch structure.1637 *1638 * The (fragment->patch, fragment->size) pair points into the memory given1639 * by the caller, not a copy, when we return.1640 */1641static intparse_single_patch(const char*line,unsigned long size,struct patch *patch)1642{1643unsigned long offset =0;1644unsigned long oldlines =0, newlines =0, context =0;1645struct fragment **fragp = &patch->fragments;16461647while(size >4&& !memcmp(line,"@@ -",4)) {1648struct fragment *fragment;1649int len;16501651 fragment =xcalloc(1,sizeof(*fragment));1652 fragment->linenr = linenr;1653 len =parse_fragment(line, size, patch, fragment);1654if(len <=0)1655die(_("corrupt patch at line%d"), linenr);1656 fragment->patch = line;1657 fragment->size = len;1658 oldlines += fragment->oldlines;1659 newlines += fragment->newlines;1660 context += fragment->leading + fragment->trailing;16611662*fragp = fragment;1663 fragp = &fragment->next;16641665 offset += len;1666 line += len;1667 size -= len;1668}16691670/*1671 * If something was removed (i.e. we have old-lines) it cannot1672 * be creation, and if something was added it cannot be1673 * deletion. However, the reverse is not true; --unified=01674 * patches that only add are not necessarily creation even1675 * though they do not have any old lines, and ones that only1676 * delete are not necessarily deletion.1677 *1678 * Unfortunately, a real creation/deletion patch do _not_ have1679 * any context line by definition, so we cannot safely tell it1680 * apart with --unified=0 insanity. At least if the patch has1681 * more than one hunk it is not creation or deletion.1682 */1683if(patch->is_new <0&&1684(oldlines || (patch->fragments && patch->fragments->next)))1685 patch->is_new =0;1686if(patch->is_delete <0&&1687(newlines || (patch->fragments && patch->fragments->next)))1688 patch->is_delete =0;16891690if(0< patch->is_new && oldlines)1691die(_("new file%sdepends on old contents"), patch->new_name);1692if(0< patch->is_delete && newlines)1693die(_("deleted file%sstill has contents"), patch->old_name);1694if(!patch->is_delete && !newlines && context)1695fprintf_ln(stderr,1696_("** warning: "1697"file%sbecomes empty but is not deleted"),1698 patch->new_name);16991700return offset;1701}17021703staticinlineintmetadata_changes(struct patch *patch)1704{1705return patch->is_rename >0||1706 patch->is_copy >0||1707 patch->is_new >0||1708 patch->is_delete ||1709(patch->old_mode && patch->new_mode &&1710 patch->old_mode != patch->new_mode);1711}17121713static char*inflate_it(const void*data,unsigned long size,1714unsigned long inflated_size)1715{1716 git_zstream stream;1717void*out;1718int st;17191720memset(&stream,0,sizeof(stream));17211722 stream.next_in = (unsigned char*)data;1723 stream.avail_in = size;1724 stream.next_out = out =xmalloc(inflated_size);1725 stream.avail_out = inflated_size;1726git_inflate_init(&stream);1727 st =git_inflate(&stream, Z_FINISH);1728git_inflate_end(&stream);1729if((st != Z_STREAM_END) || stream.total_out != inflated_size) {1730free(out);1731return NULL;1732}1733return out;1734}17351736/*1737 * Read a binary hunk and return a new fragment; fragment->patch1738 * points at an allocated memory that the caller must free, so1739 * it is marked as "->free_patch = 1".1740 */1741static struct fragment *parse_binary_hunk(char**buf_p,1742unsigned long*sz_p,1743int*status_p,1744int*used_p)1745{1746/*1747 * Expect a line that begins with binary patch method ("literal"1748 * or "delta"), followed by the length of data before deflating.1749 * a sequence of 'length-byte' followed by base-85 encoded data1750 * should follow, terminated by a newline.1751 *1752 * Each 5-byte sequence of base-85 encodes up to 4 bytes,1753 * and we would limit the patch line to 66 characters,1754 * so one line can fit up to 13 groups that would decode1755 * to 52 bytes max. The length byte 'A'-'Z' corresponds1756 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.1757 */1758int llen, used;1759unsigned long size = *sz_p;1760char*buffer = *buf_p;1761int patch_method;1762unsigned long origlen;1763char*data = NULL;1764int hunk_size =0;1765struct fragment *frag;17661767 llen =linelen(buffer, size);1768 used = llen;17691770*status_p =0;17711772if(!prefixcmp(buffer,"delta ")) {1773 patch_method = BINARY_DELTA_DEFLATED;1774 origlen =strtoul(buffer +6, NULL,10);1775}1776else if(!prefixcmp(buffer,"literal ")) {1777 patch_method = BINARY_LITERAL_DEFLATED;1778 origlen =strtoul(buffer +8, NULL,10);1779}1780else1781return NULL;17821783 linenr++;1784 buffer += llen;1785while(1) {1786int byte_length, max_byte_length, newsize;1787 llen =linelen(buffer, size);1788 used += llen;1789 linenr++;1790if(llen ==1) {1791/* consume the blank line */1792 buffer++;1793 size--;1794break;1795}1796/*1797 * Minimum line is "A00000\n" which is 7-byte long,1798 * and the line length must be multiple of 5 plus 2.1799 */1800if((llen <7) || (llen-2) %5)1801goto corrupt;1802 max_byte_length = (llen -2) /5*4;1803 byte_length = *buffer;1804if('A'<= byte_length && byte_length <='Z')1805 byte_length = byte_length -'A'+1;1806else if('a'<= byte_length && byte_length <='z')1807 byte_length = byte_length -'a'+27;1808else1809goto corrupt;1810/* if the input length was not multiple of 4, we would1811 * have filler at the end but the filler should never1812 * exceed 3 bytes1813 */1814if(max_byte_length < byte_length ||1815 byte_length <= max_byte_length -4)1816goto corrupt;1817 newsize = hunk_size + byte_length;1818 data =xrealloc(data, newsize);1819if(decode_85(data + hunk_size, buffer +1, byte_length))1820goto corrupt;1821 hunk_size = newsize;1822 buffer += llen;1823 size -= llen;1824}18251826 frag =xcalloc(1,sizeof(*frag));1827 frag->patch =inflate_it(data, hunk_size, origlen);1828 frag->free_patch =1;1829if(!frag->patch)1830goto corrupt;1831free(data);1832 frag->size = origlen;1833*buf_p = buffer;1834*sz_p = size;1835*used_p = used;1836 frag->binary_patch_method = patch_method;1837return frag;18381839 corrupt:1840free(data);1841*status_p = -1;1842error(_("corrupt binary patch at line%d: %.*s"),1843 linenr-1, llen-1, buffer);1844return NULL;1845}18461847static intparse_binary(char*buffer,unsigned long size,struct patch *patch)1848{1849/*1850 * We have read "GIT binary patch\n"; what follows is a line1851 * that says the patch method (currently, either "literal" or1852 * "delta") and the length of data before deflating; a1853 * sequence of 'length-byte' followed by base-85 encoded data1854 * follows.1855 *1856 * When a binary patch is reversible, there is another binary1857 * hunk in the same format, starting with patch method (either1858 * "literal" or "delta") with the length of data, and a sequence1859 * of length-byte + base-85 encoded data, terminated with another1860 * empty line. This data, when applied to the postimage, produces1861 * the preimage.1862 */1863struct fragment *forward;1864struct fragment *reverse;1865int status;1866int used, used_1;18671868 forward =parse_binary_hunk(&buffer, &size, &status, &used);1869if(!forward && !status)1870/* there has to be one hunk (forward hunk) */1871returnerror(_("unrecognized binary patch at line%d"), linenr-1);1872if(status)1873/* otherwise we already gave an error message */1874return status;18751876 reverse =parse_binary_hunk(&buffer, &size, &status, &used_1);1877if(reverse)1878 used += used_1;1879else if(status) {1880/*1881 * Not having reverse hunk is not an error, but having1882 * a corrupt reverse hunk is.1883 */1884free((void*) forward->patch);1885free(forward);1886return status;1887}1888 forward->next = reverse;1889 patch->fragments = forward;1890 patch->is_binary =1;1891return used;1892}18931894/*1895 * Read the patch text in "buffer" taht extends for "size" bytes; stop1896 * reading after seeing a single patch (i.e. changes to a single file).1897 * Create fragments (i.e. patch hunks) and hang them to the given patch.1898 * Return the number of bytes consumed, so that the caller can call us1899 * again for the next patch.1900 */1901static intparse_chunk(char*buffer,unsigned long size,struct patch *patch)1902{1903int hdrsize, patchsize;1904int offset =find_header(buffer, size, &hdrsize, patch);19051906if(offset <0)1907return offset;19081909 patch->ws_rule =whitespace_rule(patch->new_name1910? patch->new_name1911: patch->old_name);19121913 patchsize =parse_single_patch(buffer + offset + hdrsize,1914 size - offset - hdrsize, patch);19151916if(!patchsize) {1917static const char*binhdr[] = {1918"Binary files ",1919"Files ",1920 NULL,1921};1922static const char git_binary[] ="GIT binary patch\n";1923int i;1924int hd = hdrsize + offset;1925unsigned long llen =linelen(buffer + hd, size - hd);19261927if(llen ==sizeof(git_binary) -1&&1928!memcmp(git_binary, buffer + hd, llen)) {1929int used;1930 linenr++;1931 used =parse_binary(buffer + hd + llen,1932 size - hd - llen, patch);1933if(used)1934 patchsize = used + llen;1935else1936 patchsize =0;1937}1938else if(!memcmp(" differ\n", buffer + hd + llen -8,8)) {1939for(i =0; binhdr[i]; i++) {1940int len =strlen(binhdr[i]);1941if(len < size - hd &&1942!memcmp(binhdr[i], buffer + hd, len)) {1943 linenr++;1944 patch->is_binary =1;1945 patchsize = llen;1946break;1947}1948}1949}19501951/* Empty patch cannot be applied if it is a text patch1952 * without metadata change. A binary patch appears1953 * empty to us here.1954 */1955if((apply || check) &&1956(!patch->is_binary && !metadata_changes(patch)))1957die(_("patch with only garbage at line%d"), linenr);1958}19591960return offset + hdrsize + patchsize;1961}19621963#define swap(a,b) myswap((a),(b),sizeof(a))19641965#define myswap(a, b, size) do { \1966 unsigned char mytmp[size]; \1967 memcpy(mytmp, &a, size); \1968 memcpy(&a, &b, size); \1969 memcpy(&b, mytmp, size); \1970} while (0)19711972static voidreverse_patches(struct patch *p)1973{1974for(; p; p = p->next) {1975struct fragment *frag = p->fragments;19761977swap(p->new_name, p->old_name);1978swap(p->new_mode, p->old_mode);1979swap(p->is_new, p->is_delete);1980swap(p->lines_added, p->lines_deleted);1981swap(p->old_sha1_prefix, p->new_sha1_prefix);19821983for(; frag; frag = frag->next) {1984swap(frag->newpos, frag->oldpos);1985swap(frag->newlines, frag->oldlines);1986}1987}1988}19891990static const char pluses[] =1991"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";1992static const char minuses[]=1993"----------------------------------------------------------------------";19941995static voidshow_stats(struct patch *patch)1996{1997struct strbuf qname = STRBUF_INIT;1998char*cp = patch->new_name ? patch->new_name : patch->old_name;1999int max, add, del;20002001quote_c_style(cp, &qname, NULL,0);20022003/*2004 * "scale" the filename2005 */2006 max = max_len;2007if(max >50)2008 max =50;20092010if(qname.len > max) {2011 cp =strchr(qname.buf + qname.len +3- max,'/');2012if(!cp)2013 cp = qname.buf + qname.len +3- max;2014strbuf_splice(&qname,0, cp - qname.buf,"...",3);2015}20162017if(patch->is_binary) {2018printf(" %-*s | Bin\n", max, qname.buf);2019strbuf_release(&qname);2020return;2021}20222023printf(" %-*s |", max, qname.buf);2024strbuf_release(&qname);20252026/*2027 * scale the add/delete2028 */2029 max = max + max_change >70?70- max : max_change;2030 add = patch->lines_added;2031 del = patch->lines_deleted;20322033if(max_change >0) {2034int total = ((add + del) * max + max_change /2) / max_change;2035 add = (add * max + max_change /2) / max_change;2036 del = total - add;2037}2038printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,2039 add, pluses, del, minuses);2040}20412042static intread_old_data(struct stat *st,const char*path,struct strbuf *buf)2043{2044switch(st->st_mode & S_IFMT) {2045case S_IFLNK:2046if(strbuf_readlink(buf, path, st->st_size) <0)2047returnerror(_("unable to read symlink%s"), path);2048return0;2049case S_IFREG:2050if(strbuf_read_file(buf, path, st->st_size) != st->st_size)2051returnerror(_("unable to open or read%s"), path);2052convert_to_git(path, buf->buf, buf->len, buf,0);2053return0;2054default:2055return-1;2056}2057}20582059/*2060 * Update the preimage, and the common lines in postimage,2061 * from buffer buf of length len. If postlen is 0 the postimage2062 * is updated in place, otherwise it's updated on a new buffer2063 * of length postlen2064 */20652066static voidupdate_pre_post_images(struct image *preimage,2067struct image *postimage,2068char*buf,2069size_t len,size_t postlen)2070{2071int i, ctx;2072char*new, *old, *fixed;2073struct image fixed_preimage;20742075/*2076 * Update the preimage with whitespace fixes. Note that we2077 * are not losing preimage->buf -- apply_one_fragment() will2078 * free "oldlines".2079 */2080prepare_image(&fixed_preimage, buf, len,1);2081assert(fixed_preimage.nr == preimage->nr);2082for(i =0; i < preimage->nr; i++)2083 fixed_preimage.line[i].flag = preimage->line[i].flag;2084free(preimage->line_allocated);2085*preimage = fixed_preimage;20862087/*2088 * Adjust the common context lines in postimage. This can be2089 * done in-place when we are just doing whitespace fixing,2090 * which does not make the string grow, but needs a new buffer2091 * when ignoring whitespace causes the update, since in this case2092 * we could have e.g. tabs converted to multiple spaces.2093 * We trust the caller to tell us if the update can be done2094 * in place (postlen==0) or not.2095 */2096 old = postimage->buf;2097if(postlen)2098new= postimage->buf =xmalloc(postlen);2099else2100new= old;2101 fixed = preimage->buf;2102for(i = ctx =0; i < postimage->nr; i++) {2103size_t len = postimage->line[i].len;2104if(!(postimage->line[i].flag & LINE_COMMON)) {2105/* an added line -- no counterparts in preimage */2106memmove(new, old, len);2107 old += len;2108new+= len;2109continue;2110}21112112/* a common context -- skip it in the original postimage */2113 old += len;21142115/* and find the corresponding one in the fixed preimage */2116while(ctx < preimage->nr &&2117!(preimage->line[ctx].flag & LINE_COMMON)) {2118 fixed += preimage->line[ctx].len;2119 ctx++;2120}2121if(preimage->nr <= ctx)2122die(_("oops"));21232124/* and copy it in, while fixing the line length */2125 len = preimage->line[ctx].len;2126memcpy(new, fixed, len);2127new+= len;2128 fixed += len;2129 postimage->line[i].len = len;2130 ctx++;2131}21322133/* Fix the length of the whole thing */2134 postimage->len =new- postimage->buf;2135}21362137static intmatch_fragment(struct image *img,2138struct image *preimage,2139struct image *postimage,2140unsigned longtry,2141int try_lno,2142unsigned ws_rule,2143int match_beginning,int match_end)2144{2145int i;2146char*fixed_buf, *buf, *orig, *target;2147struct strbuf fixed;2148size_t fixed_len;2149int preimage_limit;21502151if(preimage->nr + try_lno <= img->nr) {2152/*2153 * The hunk falls within the boundaries of img.2154 */2155 preimage_limit = preimage->nr;2156if(match_end && (preimage->nr + try_lno != img->nr))2157return0;2158}else if(ws_error_action == correct_ws_error &&2159(ws_rule & WS_BLANK_AT_EOF)) {2160/*2161 * This hunk extends beyond the end of img, and we are2162 * removing blank lines at the end of the file. This2163 * many lines from the beginning of the preimage must2164 * match with img, and the remainder of the preimage2165 * must be blank.2166 */2167 preimage_limit = img->nr - try_lno;2168}else{2169/*2170 * The hunk extends beyond the end of the img and2171 * we are not removing blanks at the end, so we2172 * should reject the hunk at this position.2173 */2174return0;2175}21762177if(match_beginning && try_lno)2178return0;21792180/* Quick hash check */2181for(i =0; i < preimage_limit; i++)2182if((img->line[try_lno + i].flag & LINE_PATCHED) ||2183(preimage->line[i].hash != img->line[try_lno + i].hash))2184return0;21852186if(preimage_limit == preimage->nr) {2187/*2188 * Do we have an exact match? If we were told to match2189 * at the end, size must be exactly at try+fragsize,2190 * otherwise try+fragsize must be still within the preimage,2191 * and either case, the old piece should match the preimage2192 * exactly.2193 */2194if((match_end2195? (try+ preimage->len == img->len)2196: (try+ preimage->len <= img->len)) &&2197!memcmp(img->buf +try, preimage->buf, preimage->len))2198return1;2199}else{2200/*2201 * The preimage extends beyond the end of img, so2202 * there cannot be an exact match.2203 *2204 * There must be one non-blank context line that match2205 * a line before the end of img.2206 */2207char*buf_end;22082209 buf = preimage->buf;2210 buf_end = buf;2211for(i =0; i < preimage_limit; i++)2212 buf_end += preimage->line[i].len;22132214for( ; buf < buf_end; buf++)2215if(!isspace(*buf))2216break;2217if(buf == buf_end)2218return0;2219}22202221/*2222 * No exact match. If we are ignoring whitespace, run a line-by-line2223 * fuzzy matching. We collect all the line length information because2224 * we need it to adjust whitespace if we match.2225 */2226if(ws_ignore_action == ignore_ws_change) {2227size_t imgoff =0;2228size_t preoff =0;2229size_t postlen = postimage->len;2230size_t extra_chars;2231char*preimage_eof;2232char*preimage_end;2233for(i =0; i < preimage_limit; i++) {2234size_t prelen = preimage->line[i].len;2235size_t imglen = img->line[try_lno+i].len;22362237if(!fuzzy_matchlines(img->buf +try+ imgoff, imglen,2238 preimage->buf + preoff, prelen))2239return0;2240if(preimage->line[i].flag & LINE_COMMON)2241 postlen += imglen - prelen;2242 imgoff += imglen;2243 preoff += prelen;2244}22452246/*2247 * Ok, the preimage matches with whitespace fuzz.2248 *2249 * imgoff now holds the true length of the target that2250 * matches the preimage before the end of the file.2251 *2252 * Count the number of characters in the preimage that fall2253 * beyond the end of the file and make sure that all of them2254 * are whitespace characters. (This can only happen if2255 * we are removing blank lines at the end of the file.)2256 */2257 buf = preimage_eof = preimage->buf + preoff;2258for( ; i < preimage->nr; i++)2259 preoff += preimage->line[i].len;2260 preimage_end = preimage->buf + preoff;2261for( ; buf < preimage_end; buf++)2262if(!isspace(*buf))2263return0;22642265/*2266 * Update the preimage and the common postimage context2267 * lines to use the same whitespace as the target.2268 * If whitespace is missing in the target (i.e.2269 * if the preimage extends beyond the end of the file),2270 * use the whitespace from the preimage.2271 */2272 extra_chars = preimage_end - preimage_eof;2273strbuf_init(&fixed, imgoff + extra_chars);2274strbuf_add(&fixed, img->buf +try, imgoff);2275strbuf_add(&fixed, preimage_eof, extra_chars);2276 fixed_buf =strbuf_detach(&fixed, &fixed_len);2277update_pre_post_images(preimage, postimage,2278 fixed_buf, fixed_len, postlen);2279return1;2280}22812282if(ws_error_action != correct_ws_error)2283return0;22842285/*2286 * The hunk does not apply byte-by-byte, but the hash says2287 * it might with whitespace fuzz. We haven't been asked to2288 * ignore whitespace, we were asked to correct whitespace2289 * errors, so let's try matching after whitespace correction.2290 *2291 * The preimage may extend beyond the end of the file,2292 * but in this loop we will only handle the part of the2293 * preimage that falls within the file.2294 */2295strbuf_init(&fixed, preimage->len +1);2296 orig = preimage->buf;2297 target = img->buf +try;2298for(i =0; i < preimage_limit; i++) {2299size_t oldlen = preimage->line[i].len;2300size_t tgtlen = img->line[try_lno + i].len;2301size_t fixstart = fixed.len;2302struct strbuf tgtfix;2303int match;23042305/* Try fixing the line in the preimage */2306ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);23072308/* Try fixing the line in the target */2309strbuf_init(&tgtfix, tgtlen);2310ws_fix_copy(&tgtfix, target, tgtlen, ws_rule, NULL);23112312/*2313 * If they match, either the preimage was based on2314 * a version before our tree fixed whitespace breakage,2315 * or we are lacking a whitespace-fix patch the tree2316 * the preimage was based on already had (i.e. target2317 * has whitespace breakage, the preimage doesn't).2318 * In either case, we are fixing the whitespace breakages2319 * so we might as well take the fix together with their2320 * real change.2321 */2322 match = (tgtfix.len == fixed.len - fixstart &&2323!memcmp(tgtfix.buf, fixed.buf + fixstart,2324 fixed.len - fixstart));23252326strbuf_release(&tgtfix);2327if(!match)2328goto unmatch_exit;23292330 orig += oldlen;2331 target += tgtlen;2332}233323342335/*2336 * Now handle the lines in the preimage that falls beyond the2337 * end of the file (if any). They will only match if they are2338 * empty or only contain whitespace (if WS_BLANK_AT_EOL is2339 * false).2340 */2341for( ; i < preimage->nr; i++) {2342size_t fixstart = fixed.len;/* start of the fixed preimage */2343size_t oldlen = preimage->line[i].len;2344int j;23452346/* Try fixing the line in the preimage */2347ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);23482349for(j = fixstart; j < fixed.len; j++)2350if(!isspace(fixed.buf[j]))2351goto unmatch_exit;23522353 orig += oldlen;2354}23552356/*2357 * Yes, the preimage is based on an older version that still2358 * has whitespace breakages unfixed, and fixing them makes the2359 * hunk match. Update the context lines in the postimage.2360 */2361 fixed_buf =strbuf_detach(&fixed, &fixed_len);2362update_pre_post_images(preimage, postimage,2363 fixed_buf, fixed_len,0);2364return1;23652366 unmatch_exit:2367strbuf_release(&fixed);2368return0;2369}23702371static intfind_pos(struct image *img,2372struct image *preimage,2373struct image *postimage,2374int line,2375unsigned ws_rule,2376int match_beginning,int match_end)2377{2378int i;2379unsigned long backwards, forwards,try;2380int backwards_lno, forwards_lno, try_lno;23812382/*2383 * If match_beginning or match_end is specified, there is no2384 * point starting from a wrong line that will never match and2385 * wander around and wait for a match at the specified end.2386 */2387if(match_beginning)2388 line =0;2389else if(match_end)2390 line = img->nr - preimage->nr;23912392/*2393 * Because the comparison is unsigned, the following test2394 * will also take care of a negative line number that can2395 * result when match_end and preimage is larger than the target.2396 */2397if((size_t) line > img->nr)2398 line = img->nr;23992400try=0;2401for(i =0; i < line; i++)2402try+= img->line[i].len;24032404/*2405 * There's probably some smart way to do this, but I'll leave2406 * that to the smart and beautiful people. I'm simple and stupid.2407 */2408 backwards =try;2409 backwards_lno = line;2410 forwards =try;2411 forwards_lno = line;2412 try_lno = line;24132414for(i =0; ; i++) {2415if(match_fragment(img, preimage, postimage,2416try, try_lno, ws_rule,2417 match_beginning, match_end))2418return try_lno;24192420 again:2421if(backwards_lno ==0&& forwards_lno == img->nr)2422break;24232424if(i &1) {2425if(backwards_lno ==0) {2426 i++;2427goto again;2428}2429 backwards_lno--;2430 backwards -= img->line[backwards_lno].len;2431try= backwards;2432 try_lno = backwards_lno;2433}else{2434if(forwards_lno == img->nr) {2435 i++;2436goto again;2437}2438 forwards += img->line[forwards_lno].len;2439 forwards_lno++;2440try= forwards;2441 try_lno = forwards_lno;2442}24432444}2445return-1;2446}24472448static voidremove_first_line(struct image *img)2449{2450 img->buf += img->line[0].len;2451 img->len -= img->line[0].len;2452 img->line++;2453 img->nr--;2454}24552456static voidremove_last_line(struct image *img)2457{2458 img->len -= img->line[--img->nr].len;2459}24602461/*2462 * The change from "preimage" and "postimage" has been found to2463 * apply at applied_pos (counts in line numbers) in "img".2464 * Update "img" to remove "preimage" and replace it with "postimage".2465 */2466static voidupdate_image(struct image *img,2467int applied_pos,2468struct image *preimage,2469struct image *postimage)2470{2471/*2472 * remove the copy of preimage at offset in img2473 * and replace it with postimage2474 */2475int i, nr;2476size_t remove_count, insert_count, applied_at =0;2477char*result;2478int preimage_limit;24792480/*2481 * If we are removing blank lines at the end of img,2482 * the preimage may extend beyond the end.2483 * If that is the case, we must be careful only to2484 * remove the part of the preimage that falls within2485 * the boundaries of img. Initialize preimage_limit2486 * to the number of lines in the preimage that falls2487 * within the boundaries.2488 */2489 preimage_limit = preimage->nr;2490if(preimage_limit > img->nr - applied_pos)2491 preimage_limit = img->nr - applied_pos;24922493for(i =0; i < applied_pos; i++)2494 applied_at += img->line[i].len;24952496 remove_count =0;2497for(i =0; i < preimage_limit; i++)2498 remove_count += img->line[applied_pos + i].len;2499 insert_count = postimage->len;25002501/* Adjust the contents */2502 result =xmalloc(img->len + insert_count - remove_count +1);2503memcpy(result, img->buf, applied_at);2504memcpy(result + applied_at, postimage->buf, postimage->len);2505memcpy(result + applied_at + postimage->len,2506 img->buf + (applied_at + remove_count),2507 img->len - (applied_at + remove_count));2508free(img->buf);2509 img->buf = result;2510 img->len += insert_count - remove_count;2511 result[img->len] ='\0';25122513/* Adjust the line table */2514 nr = img->nr + postimage->nr - preimage_limit;2515if(preimage_limit < postimage->nr) {2516/*2517 * NOTE: this knows that we never call remove_first_line()2518 * on anything other than pre/post image.2519 */2520 img->line =xrealloc(img->line, nr *sizeof(*img->line));2521 img->line_allocated = img->line;2522}2523if(preimage_limit != postimage->nr)2524memmove(img->line + applied_pos + postimage->nr,2525 img->line + applied_pos + preimage_limit,2526(img->nr - (applied_pos + preimage_limit)) *2527sizeof(*img->line));2528memcpy(img->line + applied_pos,2529 postimage->line,2530 postimage->nr *sizeof(*img->line));2531if(!allow_overlap)2532for(i =0; i < postimage->nr; i++)2533 img->line[applied_pos + i].flag |= LINE_PATCHED;2534 img->nr = nr;2535}25362537/*2538 * Use the patch-hunk text in "frag" to prepare two images (preimage and2539 * postimage) for the hunk. Find lines that match "preimage" in "img" and2540 * replace the part of "img" with "postimage" text.2541 */2542static intapply_one_fragment(struct image *img,struct fragment *frag,2543int inaccurate_eof,unsigned ws_rule,2544int nth_fragment)2545{2546int match_beginning, match_end;2547const char*patch = frag->patch;2548int size = frag->size;2549char*old, *oldlines;2550struct strbuf newlines;2551int new_blank_lines_at_end =0;2552int found_new_blank_lines_at_end =0;2553int hunk_linenr = frag->linenr;2554unsigned long leading, trailing;2555int pos, applied_pos;2556struct image preimage;2557struct image postimage;25582559memset(&preimage,0,sizeof(preimage));2560memset(&postimage,0,sizeof(postimage));2561 oldlines =xmalloc(size);2562strbuf_init(&newlines, size);25632564 old = oldlines;2565while(size >0) {2566char first;2567int len =linelen(patch, size);2568int plen;2569int added_blank_line =0;2570int is_blank_context =0;2571size_t start;25722573if(!len)2574break;25752576/*2577 * "plen" is how much of the line we should use for2578 * the actual patch data. Normally we just remove the2579 * first character on the line, but if the line is2580 * followed by "\ No newline", then we also remove the2581 * last one (which is the newline, of course).2582 */2583 plen = len -1;2584if(len < size && patch[len] =='\\')2585 plen--;2586 first = *patch;2587if(apply_in_reverse) {2588if(first =='-')2589 first ='+';2590else if(first =='+')2591 first ='-';2592}25932594switch(first) {2595case'\n':2596/* Newer GNU diff, empty context line */2597if(plen <0)2598/* ... followed by '\No newline'; nothing */2599break;2600*old++ ='\n';2601strbuf_addch(&newlines,'\n');2602add_line_info(&preimage,"\n",1, LINE_COMMON);2603add_line_info(&postimage,"\n",1, LINE_COMMON);2604 is_blank_context =1;2605break;2606case' ':2607if(plen && (ws_rule & WS_BLANK_AT_EOF) &&2608ws_blank_line(patch +1, plen, ws_rule))2609 is_blank_context =1;2610case'-':2611memcpy(old, patch +1, plen);2612add_line_info(&preimage, old, plen,2613(first ==' '? LINE_COMMON :0));2614 old += plen;2615if(first =='-')2616break;2617/* Fall-through for ' ' */2618case'+':2619/* --no-add does not add new lines */2620if(first =='+'&& no_add)2621break;26222623 start = newlines.len;2624if(first !='+'||2625!whitespace_error ||2626 ws_error_action != correct_ws_error) {2627strbuf_add(&newlines, patch +1, plen);2628}2629else{2630ws_fix_copy(&newlines, patch +1, plen, ws_rule, &applied_after_fixing_ws);2631}2632add_line_info(&postimage, newlines.buf + start, newlines.len - start,2633(first =='+'?0: LINE_COMMON));2634if(first =='+'&&2635(ws_rule & WS_BLANK_AT_EOF) &&2636ws_blank_line(patch +1, plen, ws_rule))2637 added_blank_line =1;2638break;2639case'@':case'\\':2640/* Ignore it, we already handled it */2641break;2642default:2643if(apply_verbosely)2644error(_("invalid start of line: '%c'"), first);2645return-1;2646}2647if(added_blank_line) {2648if(!new_blank_lines_at_end)2649 found_new_blank_lines_at_end = hunk_linenr;2650 new_blank_lines_at_end++;2651}2652else if(is_blank_context)2653;2654else2655 new_blank_lines_at_end =0;2656 patch += len;2657 size -= len;2658 hunk_linenr++;2659}2660if(inaccurate_eof &&2661 old > oldlines && old[-1] =='\n'&&2662 newlines.len >0&& newlines.buf[newlines.len -1] =='\n') {2663 old--;2664strbuf_setlen(&newlines, newlines.len -1);2665}26662667 leading = frag->leading;2668 trailing = frag->trailing;26692670/*2671 * A hunk to change lines at the beginning would begin with2672 * @@ -1,L +N,M @@2673 * but we need to be careful. -U0 that inserts before the second2674 * line also has this pattern.2675 *2676 * And a hunk to add to an empty file would begin with2677 * @@ -0,0 +N,M @@2678 *2679 * In other words, a hunk that is (frag->oldpos <= 1) with or2680 * without leading context must match at the beginning.2681 */2682 match_beginning = (!frag->oldpos ||2683(frag->oldpos ==1&& !unidiff_zero));26842685/*2686 * A hunk without trailing lines must match at the end.2687 * However, we simply cannot tell if a hunk must match end2688 * from the lack of trailing lines if the patch was generated2689 * with unidiff without any context.2690 */2691 match_end = !unidiff_zero && !trailing;26922693 pos = frag->newpos ? (frag->newpos -1) :0;2694 preimage.buf = oldlines;2695 preimage.len = old - oldlines;2696 postimage.buf = newlines.buf;2697 postimage.len = newlines.len;2698 preimage.line = preimage.line_allocated;2699 postimage.line = postimage.line_allocated;27002701for(;;) {27022703 applied_pos =find_pos(img, &preimage, &postimage, pos,2704 ws_rule, match_beginning, match_end);27052706if(applied_pos >=0)2707break;27082709/* Am I at my context limits? */2710if((leading <= p_context) && (trailing <= p_context))2711break;2712if(match_beginning || match_end) {2713 match_beginning = match_end =0;2714continue;2715}27162717/*2718 * Reduce the number of context lines; reduce both2719 * leading and trailing if they are equal otherwise2720 * just reduce the larger context.2721 */2722if(leading >= trailing) {2723remove_first_line(&preimage);2724remove_first_line(&postimage);2725 pos--;2726 leading--;2727}2728if(trailing > leading) {2729remove_last_line(&preimage);2730remove_last_line(&postimage);2731 trailing--;2732}2733}27342735if(applied_pos >=0) {2736if(new_blank_lines_at_end &&2737 preimage.nr + applied_pos >= img->nr &&2738(ws_rule & WS_BLANK_AT_EOF) &&2739 ws_error_action != nowarn_ws_error) {2740record_ws_error(WS_BLANK_AT_EOF,"+",1,2741 found_new_blank_lines_at_end);2742if(ws_error_action == correct_ws_error) {2743while(new_blank_lines_at_end--)2744remove_last_line(&postimage);2745}2746/*2747 * We would want to prevent write_out_results()2748 * from taking place in apply_patch() that follows2749 * the callchain led us here, which is:2750 * apply_patch->check_patch_list->check_patch->2751 * apply_data->apply_fragments->apply_one_fragment2752 */2753if(ws_error_action == die_on_ws_error)2754 apply =0;2755}27562757if(apply_verbosely && applied_pos != pos) {2758int offset = applied_pos - pos;2759if(apply_in_reverse)2760 offset =0- offset;2761fprintf_ln(stderr,2762Q_("Hunk #%dsucceeded at%d(offset%dline).",2763"Hunk #%dsucceeded at%d(offset%dlines).",2764 offset),2765 nth_fragment, applied_pos +1, offset);2766}27672768/*2769 * Warn if it was necessary to reduce the number2770 * of context lines.2771 */2772if((leading != frag->leading) ||2773(trailing != frag->trailing))2774fprintf_ln(stderr,_("Context reduced to (%ld/%ld)"2775" to apply fragment at%d"),2776 leading, trailing, applied_pos+1);2777update_image(img, applied_pos, &preimage, &postimage);2778}else{2779if(apply_verbosely)2780error(_("while searching for:\n%.*s"),2781(int)(old - oldlines), oldlines);2782}27832784free(oldlines);2785strbuf_release(&newlines);2786free(preimage.line_allocated);2787free(postimage.line_allocated);27882789return(applied_pos <0);2790}27912792static intapply_binary_fragment(struct image *img,struct patch *patch)2793{2794struct fragment *fragment = patch->fragments;2795unsigned long len;2796void*dst;27972798if(!fragment)2799returnerror(_("missing binary patch data for '%s'"),2800 patch->new_name ?2801 patch->new_name :2802 patch->old_name);28032804/* Binary patch is irreversible without the optional second hunk */2805if(apply_in_reverse) {2806if(!fragment->next)2807returnerror("cannot reverse-apply a binary patch "2808"without the reverse hunk to '%s'",2809 patch->new_name2810? patch->new_name : patch->old_name);2811 fragment = fragment->next;2812}2813switch(fragment->binary_patch_method) {2814case BINARY_DELTA_DEFLATED:2815 dst =patch_delta(img->buf, img->len, fragment->patch,2816 fragment->size, &len);2817if(!dst)2818return-1;2819clear_image(img);2820 img->buf = dst;2821 img->len = len;2822return0;2823case BINARY_LITERAL_DEFLATED:2824clear_image(img);2825 img->len = fragment->size;2826 img->buf =xmalloc(img->len+1);2827memcpy(img->buf, fragment->patch, img->len);2828 img->buf[img->len] ='\0';2829return0;2830}2831return-1;2832}28332834/*2835 * Replace "img" with the result of applying the binary patch.2836 * The binary patch data itself in patch->fragment is still kept2837 * but the preimage prepared by the caller in "img" is freed here2838 * or in the helper function apply_binary_fragment() this calls.2839 */2840static intapply_binary(struct image *img,struct patch *patch)2841{2842const char*name = patch->old_name ? patch->old_name : patch->new_name;2843unsigned char sha1[20];28442845/*2846 * For safety, we require patch index line to contain2847 * full 40-byte textual SHA1 for old and new, at least for now.2848 */2849if(strlen(patch->old_sha1_prefix) !=40||2850strlen(patch->new_sha1_prefix) !=40||2851get_sha1_hex(patch->old_sha1_prefix, sha1) ||2852get_sha1_hex(patch->new_sha1_prefix, sha1))2853returnerror("cannot apply binary patch to '%s' "2854"without full index line", name);28552856if(patch->old_name) {2857/*2858 * See if the old one matches what the patch2859 * applies to.2860 */2861hash_sha1_file(img->buf, img->len, blob_type, sha1);2862if(strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))2863returnerror("the patch applies to '%s' (%s), "2864"which does not match the "2865"current contents.",2866 name,sha1_to_hex(sha1));2867}2868else{2869/* Otherwise, the old one must be empty. */2870if(img->len)2871returnerror("the patch applies to an empty "2872"'%s' but it is not empty", name);2873}28742875get_sha1_hex(patch->new_sha1_prefix, sha1);2876if(is_null_sha1(sha1)) {2877clear_image(img);2878return0;/* deletion patch */2879}28802881if(has_sha1_file(sha1)) {2882/* We already have the postimage */2883enum object_type type;2884unsigned long size;2885char*result;28862887 result =read_sha1_file(sha1, &type, &size);2888if(!result)2889returnerror("the necessary postimage%sfor "2890"'%s' cannot be read",2891 patch->new_sha1_prefix, name);2892clear_image(img);2893 img->buf = result;2894 img->len = size;2895}else{2896/*2897 * We have verified buf matches the preimage;2898 * apply the patch data to it, which is stored2899 * in the patch->fragments->{patch,size}.2900 */2901if(apply_binary_fragment(img, patch))2902returnerror(_("binary patch does not apply to '%s'"),2903 name);29042905/* verify that the result matches */2906hash_sha1_file(img->buf, img->len, blob_type, sha1);2907if(strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))2908returnerror(_("binary patch to '%s' creates incorrect result (expecting%s, got%s)"),2909 name, patch->new_sha1_prefix,sha1_to_hex(sha1));2910}29112912return0;2913}29142915static intapply_fragments(struct image *img,struct patch *patch)2916{2917struct fragment *frag = patch->fragments;2918const char*name = patch->old_name ? patch->old_name : patch->new_name;2919unsigned ws_rule = patch->ws_rule;2920unsigned inaccurate_eof = patch->inaccurate_eof;2921int nth =0;29222923if(patch->is_binary)2924returnapply_binary(img, patch);29252926while(frag) {2927 nth++;2928if(apply_one_fragment(img, frag, inaccurate_eof, ws_rule, nth)) {2929error(_("patch failed:%s:%ld"), name, frag->oldpos);2930if(!apply_with_reject)2931return-1;2932 frag->rejected =1;2933}2934 frag = frag->next;2935}2936return0;2937}29382939static intread_file_or_gitlink(struct cache_entry *ce,struct strbuf *buf)2940{2941if(!ce)2942return0;29432944if(S_ISGITLINK(ce->ce_mode)) {2945strbuf_grow(buf,100);2946strbuf_addf(buf,"Subproject commit%s\n",sha1_to_hex(ce->sha1));2947}else{2948enum object_type type;2949unsigned long sz;2950char*result;29512952 result =read_sha1_file(ce->sha1, &type, &sz);2953if(!result)2954return-1;2955/* XXX read_sha1_file NUL-terminates */2956strbuf_attach(buf, result, sz, sz +1);2957}2958return0;2959}29602961static struct patch *in_fn_table(const char*name)2962{2963struct string_list_item *item;29642965if(name == NULL)2966return NULL;29672968 item =string_list_lookup(&fn_table, name);2969if(item != NULL)2970return(struct patch *)item->util;29712972return NULL;2973}29742975/*2976 * item->util in the filename table records the status of the path.2977 * Usually it points at a patch (whose result records the contents2978 * of it after applying it), but it could be PATH_WAS_DELETED for a2979 * path that a previously applied patch has already removed.2980 */2981#define PATH_TO_BE_DELETED ((struct patch *) -2)2982#define PATH_WAS_DELETED ((struct patch *) -1)29832984static intto_be_deleted(struct patch *patch)2985{2986return patch == PATH_TO_BE_DELETED;2987}29882989static intwas_deleted(struct patch *patch)2990{2991return patch == PATH_WAS_DELETED;2992}29932994static voidadd_to_fn_table(struct patch *patch)2995{2996struct string_list_item *item;29972998/*2999 * Always add new_name unless patch is a deletion3000 * This should cover the cases for normal diffs,3001 * file creations and copies3002 */3003if(patch->new_name != NULL) {3004 item =string_list_insert(&fn_table, patch->new_name);3005 item->util = patch;3006}30073008/*3009 * store a failure on rename/deletion cases because3010 * later chunks shouldn't patch old names3011 */3012if((patch->new_name == NULL) || (patch->is_rename)) {3013 item =string_list_insert(&fn_table, patch->old_name);3014 item->util = PATH_WAS_DELETED;3015}3016}30173018static voidprepare_fn_table(struct patch *patch)3019{3020/*3021 * store information about incoming file deletion3022 */3023while(patch) {3024if((patch->new_name == NULL) || (patch->is_rename)) {3025struct string_list_item *item;3026 item =string_list_insert(&fn_table, patch->old_name);3027 item->util = PATH_TO_BE_DELETED;3028}3029 patch = patch->next;3030}3031}30323033static intapply_data(struct patch *patch,struct stat *st,struct cache_entry *ce)3034{3035struct strbuf buf = STRBUF_INIT;3036struct image image;3037size_t len;3038char*img;3039struct patch *tpatch;30403041if(!(patch->is_copy || patch->is_rename) &&3042(tpatch =in_fn_table(patch->old_name)) != NULL && !to_be_deleted(tpatch)) {3043if(was_deleted(tpatch)) {3044returnerror(_("patch%shas been renamed/deleted"),3045 patch->old_name);3046}3047/* We have a patched copy in memory; use that. */3048strbuf_add(&buf, tpatch->result, tpatch->resultsize);3049}else if(cached) {3050if(read_file_or_gitlink(ce, &buf))3051returnerror(_("read of%sfailed"), patch->old_name);3052}else if(patch->old_name) {3053if(S_ISGITLINK(patch->old_mode)) {3054if(ce) {3055read_file_or_gitlink(ce, &buf);3056}else{3057/*3058 * There is no way to apply subproject3059 * patch without looking at the index.3060 * NEEDSWORK: shouldn't this be flagged3061 * as an error???3062 */3063free_fragment_list(patch->fragments);3064 patch->fragments = NULL;3065}3066}else{3067if(read_old_data(st, patch->old_name, &buf))3068returnerror(_("read of%sfailed"), patch->old_name);3069}3070}30713072 img =strbuf_detach(&buf, &len);3073prepare_image(&image, img, len, !patch->is_binary);30743075if(apply_fragments(&image, patch) <0)3076return-1;/* note with --reject this succeeds. */3077 patch->result = image.buf;3078 patch->resultsize = image.len;3079add_to_fn_table(patch);3080free(image.line_allocated);30813082if(0< patch->is_delete && patch->resultsize)3083returnerror(_("removal patch leaves file contents"));30843085return0;3086}30873088static intcheck_to_create_blob(const char*new_name,int ok_if_exists)3089{3090struct stat nst;3091if(!lstat(new_name, &nst)) {3092if(S_ISDIR(nst.st_mode) || ok_if_exists)3093return0;3094/*3095 * A leading component of new_name might be a symlink3096 * that is going to be removed with this patch, but3097 * still pointing at somewhere that has the path.3098 * In such a case, path "new_name" does not exist as3099 * far as git is concerned.3100 */3101if(has_symlink_leading_path(new_name,strlen(new_name)))3102return0;31033104returnerror(_("%s: already exists in working directory"), new_name);3105}3106else if((errno != ENOENT) && (errno != ENOTDIR))3107returnerror("%s:%s", new_name,strerror(errno));3108return0;3109}31103111static intverify_index_match(struct cache_entry *ce,struct stat *st)3112{3113if(S_ISGITLINK(ce->ce_mode)) {3114if(!S_ISDIR(st->st_mode))3115return-1;3116return0;3117}3118returnce_match_stat(ce, st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE);3119}31203121static intcheck_preimage(struct patch *patch,struct cache_entry **ce,struct stat *st)3122{3123const char*old_name = patch->old_name;3124struct patch *tpatch = NULL;3125int stat_ret =0;3126unsigned st_mode =0;31273128/*3129 * Make sure that we do not have local modifications from the3130 * index when we are looking at the index. Also make sure3131 * we have the preimage file to be patched in the work tree,3132 * unless --cached, which tells git to apply only in the index.3133 */3134if(!old_name)3135return0;31363137assert(patch->is_new <=0);31383139if(!(patch->is_copy || patch->is_rename) &&3140(tpatch =in_fn_table(old_name)) != NULL && !to_be_deleted(tpatch)) {3141if(was_deleted(tpatch))3142returnerror(_("%s: has been deleted/renamed"), old_name);3143 st_mode = tpatch->new_mode;3144}else if(!cached) {3145 stat_ret =lstat(old_name, st);3146if(stat_ret && errno != ENOENT)3147returnerror(_("%s:%s"), old_name,strerror(errno));3148}31493150if(to_be_deleted(tpatch))3151 tpatch = NULL;31523153if(check_index && !tpatch) {3154int pos =cache_name_pos(old_name,strlen(old_name));3155if(pos <0) {3156if(patch->is_new <0)3157goto is_new;3158returnerror(_("%s: does not exist in index"), old_name);3159}3160*ce = active_cache[pos];3161if(stat_ret <0) {3162struct checkout costate;3163/* checkout */3164memset(&costate,0,sizeof(costate));3165 costate.base_dir ="";3166 costate.refresh_cache =1;3167if(checkout_entry(*ce, &costate, NULL) ||3168lstat(old_name, st))3169return-1;3170}3171if(!cached &&verify_index_match(*ce, st))3172returnerror(_("%s: does not match index"), old_name);3173if(cached)3174 st_mode = (*ce)->ce_mode;3175}else if(stat_ret <0) {3176if(patch->is_new <0)3177goto is_new;3178returnerror(_("%s:%s"), old_name,strerror(errno));3179}31803181if(!cached && !tpatch)3182 st_mode =ce_mode_from_stat(*ce, st->st_mode);31833184if(patch->is_new <0)3185 patch->is_new =0;3186if(!patch->old_mode)3187 patch->old_mode = st_mode;3188if((st_mode ^ patch->old_mode) & S_IFMT)3189returnerror(_("%s: wrong type"), old_name);3190if(st_mode != patch->old_mode)3191warning(_("%shas type%o, expected%o"),3192 old_name, st_mode, patch->old_mode);3193if(!patch->new_mode && !patch->is_delete)3194 patch->new_mode = st_mode;3195return0;31963197 is_new:3198 patch->is_new =1;3199 patch->is_delete =0;3200free(patch->old_name);3201 patch->old_name = NULL;3202return0;3203}32043205/*3206 * Check and apply the patch in-core; leave the result in patch->result3207 * for the caller to write it out to the final destination.3208 */3209static intcheck_patch(struct patch *patch)3210{3211struct stat st;3212const char*old_name = patch->old_name;3213const char*new_name = patch->new_name;3214const char*name = old_name ? old_name : new_name;3215struct cache_entry *ce = NULL;3216struct patch *tpatch;3217int ok_if_exists;3218int status;32193220 patch->rejected =1;/* we will drop this after we succeed */32213222 status =check_preimage(patch, &ce, &st);3223if(status)3224return status;3225 old_name = patch->old_name;32263227if((tpatch =in_fn_table(new_name)) &&3228(was_deleted(tpatch) ||to_be_deleted(tpatch)))3229/*3230 * A type-change diff is always split into a patch to3231 * delete old, immediately followed by a patch to3232 * create new (see diff.c::run_diff()); in such a case3233 * it is Ok that the entry to be deleted by the3234 * previous patch is still in the working tree and in3235 * the index.3236 */3237 ok_if_exists =1;3238else3239 ok_if_exists =0;32403241if(new_name &&3242((0< patch->is_new) | (0< patch->is_rename) | patch->is_copy)) {3243if(check_index &&3244cache_name_pos(new_name,strlen(new_name)) >=0&&3245!ok_if_exists)3246returnerror(_("%s: already exists in index"), new_name);3247if(!cached) {3248int err =check_to_create_blob(new_name, ok_if_exists);3249if(err)3250return err;3251}3252if(!patch->new_mode) {3253if(0< patch->is_new)3254 patch->new_mode = S_IFREG |0644;3255else3256 patch->new_mode = patch->old_mode;3257}3258}32593260if(new_name && old_name) {3261int same = !strcmp(old_name, new_name);3262if(!patch->new_mode)3263 patch->new_mode = patch->old_mode;3264if((patch->old_mode ^ patch->new_mode) & S_IFMT) {3265if(same)3266returnerror(_("new mode (%o) of%sdoes not "3267"match old mode (%o)"),3268 patch->new_mode, new_name,3269 patch->old_mode);3270else3271returnerror(_("new mode (%o) of%sdoes not "3272"match old mode (%o) of%s"),3273 patch->new_mode, new_name,3274 patch->old_mode, old_name);3275}3276}32773278if(apply_data(patch, &st, ce) <0)3279returnerror(_("%s: patch does not apply"), name);3280 patch->rejected =0;3281return0;3282}32833284static intcheck_patch_list(struct patch *patch)3285{3286int err =0;32873288prepare_fn_table(patch);3289while(patch) {3290if(apply_verbosely)3291say_patch_name(stderr,3292_("Checking patch%s..."), patch);3293 err |=check_patch(patch);3294 patch = patch->next;3295}3296return err;3297}32983299/* This function tries to read the sha1 from the current index */3300static intget_current_sha1(const char*path,unsigned char*sha1)3301{3302int pos;33033304if(read_cache() <0)3305return-1;3306 pos =cache_name_pos(path,strlen(path));3307if(pos <0)3308return-1;3309hashcpy(sha1, active_cache[pos]->sha1);3310return0;3311}33123313/* Build an index that contains the just the files needed for a 3way merge */3314static voidbuild_fake_ancestor(struct patch *list,const char*filename)3315{3316struct patch *patch;3317struct index_state result = { NULL };3318int fd;33193320/* Once we start supporting the reverse patch, it may be3321 * worth showing the new sha1 prefix, but until then...3322 */3323for(patch = list; patch; patch = patch->next) {3324const unsigned char*sha1_ptr;3325unsigned char sha1[20];3326struct cache_entry *ce;3327const char*name;33283329 name = patch->old_name ? patch->old_name : patch->new_name;3330if(0< patch->is_new)3331continue;3332else if(get_sha1(patch->old_sha1_prefix, sha1))3333/* git diff has no index line for mode/type changes */3334if(!patch->lines_added && !patch->lines_deleted) {3335if(get_current_sha1(patch->old_name, sha1))3336die("mode change for%s, which is not "3337"in current HEAD", name);3338 sha1_ptr = sha1;3339}else3340die("sha1 information is lacking or useless "3341"(%s).", name);3342else3343 sha1_ptr = sha1;33443345 ce =make_cache_entry(patch->old_mode, sha1_ptr, name,0,0);3346if(!ce)3347die(_("make_cache_entry failed for path '%s'"), name);3348if(add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD))3349die("Could not add%sto temporary index", name);3350}33513352 fd =open(filename, O_WRONLY | O_CREAT,0666);3353if(fd <0||write_index(&result, fd) ||close(fd))3354die("Could not write temporary index to%s", filename);33553356discard_index(&result);3357}33583359static voidstat_patch_list(struct patch *patch)3360{3361int files, adds, dels;33623363for(files = adds = dels =0; patch ; patch = patch->next) {3364 files++;3365 adds += patch->lines_added;3366 dels += patch->lines_deleted;3367show_stats(patch);3368}33693370print_stat_summary(stdout, files, adds, dels);3371}33723373static voidnumstat_patch_list(struct patch *patch)3374{3375for( ; patch; patch = patch->next) {3376const char*name;3377 name = patch->new_name ? patch->new_name : patch->old_name;3378if(patch->is_binary)3379printf("-\t-\t");3380else3381printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);3382write_name_quoted(name, stdout, line_termination);3383}3384}33853386static voidshow_file_mode_name(const char*newdelete,unsigned int mode,const char*name)3387{3388if(mode)3389printf("%smode%06o%s\n", newdelete, mode, name);3390else3391printf("%s %s\n", newdelete, name);3392}33933394static voidshow_mode_change(struct patch *p,int show_name)3395{3396if(p->old_mode && p->new_mode && p->old_mode != p->new_mode) {3397if(show_name)3398printf(" mode change%06o =>%06o%s\n",3399 p->old_mode, p->new_mode, p->new_name);3400else3401printf(" mode change%06o =>%06o\n",3402 p->old_mode, p->new_mode);3403}3404}34053406static voidshow_rename_copy(struct patch *p)3407{3408const char*renamecopy = p->is_rename ?"rename":"copy";3409const char*old, *new;34103411/* Find common prefix */3412 old = p->old_name;3413new= p->new_name;3414while(1) {3415const char*slash_old, *slash_new;3416 slash_old =strchr(old,'/');3417 slash_new =strchr(new,'/');3418if(!slash_old ||3419!slash_new ||3420 slash_old - old != slash_new -new||3421memcmp(old,new, slash_new -new))3422break;3423 old = slash_old +1;3424new= slash_new +1;3425}3426/* p->old_name thru old is the common prefix, and old and new3427 * through the end of names are renames3428 */3429if(old != p->old_name)3430printf("%s%.*s{%s=>%s} (%d%%)\n", renamecopy,3431(int)(old - p->old_name), p->old_name,3432 old,new, p->score);3433else3434printf("%s %s=>%s(%d%%)\n", renamecopy,3435 p->old_name, p->new_name, p->score);3436show_mode_change(p,0);3437}34383439static voidsummary_patch_list(struct patch *patch)3440{3441struct patch *p;34423443for(p = patch; p; p = p->next) {3444if(p->is_new)3445show_file_mode_name("create", p->new_mode, p->new_name);3446else if(p->is_delete)3447show_file_mode_name("delete", p->old_mode, p->old_name);3448else{3449if(p->is_rename || p->is_copy)3450show_rename_copy(p);3451else{3452if(p->score) {3453printf(" rewrite%s(%d%%)\n",3454 p->new_name, p->score);3455show_mode_change(p,0);3456}3457else3458show_mode_change(p,1);3459}3460}3461}3462}34633464static voidpatch_stats(struct patch *patch)3465{3466int lines = patch->lines_added + patch->lines_deleted;34673468if(lines > max_change)3469 max_change = lines;3470if(patch->old_name) {3471int len =quote_c_style(patch->old_name, NULL, NULL,0);3472if(!len)3473 len =strlen(patch->old_name);3474if(len > max_len)3475 max_len = len;3476}3477if(patch->new_name) {3478int len =quote_c_style(patch->new_name, NULL, NULL,0);3479if(!len)3480 len =strlen(patch->new_name);3481if(len > max_len)3482 max_len = len;3483}3484}34853486static voidremove_file(struct patch *patch,int rmdir_empty)3487{3488if(update_index) {3489if(remove_file_from_cache(patch->old_name) <0)3490die(_("unable to remove%sfrom index"), patch->old_name);3491}3492if(!cached) {3493if(!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {3494remove_path(patch->old_name);3495}3496}3497}34983499static voidadd_index_file(const char*path,unsigned mode,void*buf,unsigned long size)3500{3501struct stat st;3502struct cache_entry *ce;3503int namelen =strlen(path);3504unsigned ce_size =cache_entry_size(namelen);35053506if(!update_index)3507return;35083509 ce =xcalloc(1, ce_size);3510memcpy(ce->name, path, namelen);3511 ce->ce_mode =create_ce_mode(mode);3512 ce->ce_flags = namelen;3513if(S_ISGITLINK(mode)) {3514const char*s = buf;35153516if(get_sha1_hex(s +strlen("Subproject commit "), ce->sha1))3517die(_("corrupt patch for subproject%s"), path);3518}else{3519if(!cached) {3520if(lstat(path, &st) <0)3521die_errno(_("unable to stat newly created file '%s'"),3522 path);3523fill_stat_cache_info(ce, &st);3524}3525if(write_sha1_file(buf, size, blob_type, ce->sha1) <0)3526die(_("unable to create backing store for newly created file%s"), path);3527}3528if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0)3529die(_("unable to add cache entry for%s"), path);3530}35313532static inttry_create_file(const char*path,unsigned int mode,const char*buf,unsigned long size)3533{3534int fd;3535struct strbuf nbuf = STRBUF_INIT;35363537if(S_ISGITLINK(mode)) {3538struct stat st;3539if(!lstat(path, &st) &&S_ISDIR(st.st_mode))3540return0;3541returnmkdir(path,0777);3542}35433544if(has_symlinks &&S_ISLNK(mode))3545/* Although buf:size is counted string, it also is NUL3546 * terminated.3547 */3548returnsymlink(buf, path);35493550 fd =open(path, O_CREAT | O_EXCL | O_WRONLY, (mode &0100) ?0777:0666);3551if(fd <0)3552return-1;35533554if(convert_to_working_tree(path, buf, size, &nbuf)) {3555 size = nbuf.len;3556 buf = nbuf.buf;3557}3558write_or_die(fd, buf, size);3559strbuf_release(&nbuf);35603561if(close(fd) <0)3562die_errno(_("closing file '%s'"), path);3563return0;3564}35653566/*3567 * We optimistically assume that the directories exist,3568 * which is true 99% of the time anyway. If they don't,3569 * we create them and try again.3570 */3571static voidcreate_one_file(char*path,unsigned mode,const char*buf,unsigned long size)3572{3573if(cached)3574return;3575if(!try_create_file(path, mode, buf, size))3576return;35773578if(errno == ENOENT) {3579if(safe_create_leading_directories(path))3580return;3581if(!try_create_file(path, mode, buf, size))3582return;3583}35843585if(errno == EEXIST || errno == EACCES) {3586/* We may be trying to create a file where a directory3587 * used to be.3588 */3589struct stat st;3590if(!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))3591 errno = EEXIST;3592}35933594if(errno == EEXIST) {3595unsigned int nr =getpid();35963597for(;;) {3598char newpath[PATH_MAX];3599mksnpath(newpath,sizeof(newpath),"%s~%u", path, nr);3600if(!try_create_file(newpath, mode, buf, size)) {3601if(!rename(newpath, path))3602return;3603unlink_or_warn(newpath);3604break;3605}3606if(errno != EEXIST)3607break;3608++nr;3609}3610}3611die_errno(_("unable to write file '%s' mode%o"), path, mode);3612}36133614static voidcreate_file(struct patch *patch)3615{3616char*path = patch->new_name;3617unsigned mode = patch->new_mode;3618unsigned long size = patch->resultsize;3619char*buf = patch->result;36203621if(!mode)3622 mode = S_IFREG |0644;3623create_one_file(path, mode, buf, size);3624add_index_file(path, mode, buf, size);3625}36263627/* phase zero is to remove, phase one is to create */3628static voidwrite_out_one_result(struct patch *patch,int phase)3629{3630if(patch->is_delete >0) {3631if(phase ==0)3632remove_file(patch,1);3633return;3634}3635if(patch->is_new >0|| patch->is_copy) {3636if(phase ==1)3637create_file(patch);3638return;3639}3640/*3641 * Rename or modification boils down to the same3642 * thing: remove the old, write the new3643 */3644if(phase ==0)3645remove_file(patch, patch->is_rename);3646if(phase ==1)3647create_file(patch);3648}36493650static intwrite_out_one_reject(struct patch *patch)3651{3652FILE*rej;3653char namebuf[PATH_MAX];3654struct fragment *frag;3655int cnt =0;3656struct strbuf sb = STRBUF_INIT;36573658for(cnt =0, frag = patch->fragments; frag; frag = frag->next) {3659if(!frag->rejected)3660continue;3661 cnt++;3662}36633664if(!cnt) {3665if(apply_verbosely)3666say_patch_name(stderr,3667_("Applied patch%scleanly."), patch);3668return0;3669}36703671/* This should not happen, because a removal patch that leaves3672 * contents are marked "rejected" at the patch level.3673 */3674if(!patch->new_name)3675die(_("internal error"));36763677/* Say this even without --verbose */3678strbuf_addf(&sb,Q_("Applying patch %%swith%dreject...",3679"Applying patch %%swith%drejects...",3680 cnt),3681 cnt);3682say_patch_name(stderr, sb.buf, patch);3683strbuf_release(&sb);36843685 cnt =strlen(patch->new_name);3686if(ARRAY_SIZE(namebuf) <= cnt +5) {3687 cnt =ARRAY_SIZE(namebuf) -5;3688warning(_("truncating .rej filename to %.*s.rej"),3689 cnt -1, patch->new_name);3690}3691memcpy(namebuf, patch->new_name, cnt);3692memcpy(namebuf + cnt,".rej",5);36933694 rej =fopen(namebuf,"w");3695if(!rej)3696returnerror(_("cannot open%s:%s"), namebuf,strerror(errno));36973698/* Normal git tools never deal with .rej, so do not pretend3699 * this is a git patch by saying --git nor give extended3700 * headers. While at it, maybe please "kompare" that wants3701 * the trailing TAB and some garbage at the end of line ;-).3702 */3703fprintf(rej,"diff a/%sb/%s\t(rejected hunks)\n",3704 patch->new_name, patch->new_name);3705for(cnt =1, frag = patch->fragments;3706 frag;3707 cnt++, frag = frag->next) {3708if(!frag->rejected) {3709fprintf_ln(stderr,_("Hunk #%dapplied cleanly."), cnt);3710continue;3711}3712fprintf_ln(stderr,_("Rejected hunk #%d."), cnt);3713fprintf(rej,"%.*s", frag->size, frag->patch);3714if(frag->patch[frag->size-1] !='\n')3715fputc('\n', rej);3716}3717fclose(rej);3718return-1;3719}37203721static intwrite_out_results(struct patch *list)3722{3723int phase;3724int errs =0;3725struct patch *l;37263727for(phase =0; phase <2; phase++) {3728 l = list;3729while(l) {3730if(l->rejected)3731 errs =1;3732else{3733write_out_one_result(l, phase);3734if(phase ==1&&write_out_one_reject(l))3735 errs =1;3736}3737 l = l->next;3738}3739}3740return errs;3741}37423743static struct lock_file lock_file;37443745static struct string_list limit_by_name;3746static int has_include;3747static voidadd_name_limit(const char*name,int exclude)3748{3749struct string_list_item *it;37503751 it =string_list_append(&limit_by_name, name);3752 it->util = exclude ? NULL : (void*)1;3753}37543755static intuse_patch(struct patch *p)3756{3757const char*pathname = p->new_name ? p->new_name : p->old_name;3758int i;37593760/* Paths outside are not touched regardless of "--include" */3761if(0< prefix_length) {3762int pathlen =strlen(pathname);3763if(pathlen <= prefix_length ||3764memcmp(prefix, pathname, prefix_length))3765return0;3766}37673768/* See if it matches any of exclude/include rule */3769for(i =0; i < limit_by_name.nr; i++) {3770struct string_list_item *it = &limit_by_name.items[i];3771if(!fnmatch(it->string, pathname,0))3772return(it->util != NULL);3773}37743775/*3776 * If we had any include, a path that does not match any rule is3777 * not used. Otherwise, we saw bunch of exclude rules (or none)3778 * and such a path is used.3779 */3780return!has_include;3781}378237833784static voidprefix_one(char**name)3785{3786char*old_name = *name;3787if(!old_name)3788return;3789*name =xstrdup(prefix_filename(prefix, prefix_length, *name));3790free(old_name);3791}37923793static voidprefix_patches(struct patch *p)3794{3795if(!prefix || p->is_toplevel_relative)3796return;3797for( ; p; p = p->next) {3798prefix_one(&p->new_name);3799prefix_one(&p->old_name);3800}3801}38023803#define INACCURATE_EOF (1<<0)3804#define RECOUNT (1<<1)38053806static intapply_patch(int fd,const char*filename,int options)3807{3808size_t offset;3809struct strbuf buf = STRBUF_INIT;/* owns the patch text */3810struct patch *list = NULL, **listp = &list;3811int skipped_patch =0;38123813 patch_input_file = filename;3814read_patch_file(&buf, fd);3815 offset =0;3816while(offset < buf.len) {3817struct patch *patch;3818int nr;38193820 patch =xcalloc(1,sizeof(*patch));3821 patch->inaccurate_eof = !!(options & INACCURATE_EOF);3822 patch->recount = !!(options & RECOUNT);3823 nr =parse_chunk(buf.buf + offset, buf.len - offset, patch);3824if(nr <0)3825break;3826if(apply_in_reverse)3827reverse_patches(patch);3828if(prefix)3829prefix_patches(patch);3830if(use_patch(patch)) {3831patch_stats(patch);3832*listp = patch;3833 listp = &patch->next;3834}3835else{3836free_patch(patch);3837 skipped_patch++;3838}3839 offset += nr;3840}38413842if(!list && !skipped_patch)3843die(_("unrecognized input"));38443845if(whitespace_error && (ws_error_action == die_on_ws_error))3846 apply =0;38473848 update_index = check_index && apply;3849if(update_index && newfd <0)3850 newfd =hold_locked_index(&lock_file,1);38513852if(check_index) {3853if(read_cache() <0)3854die(_("unable to read index file"));3855}38563857if((check || apply) &&3858check_patch_list(list) <0&&3859!apply_with_reject)3860exit(1);38613862if(apply &&write_out_results(list))3863exit(1);38643865if(fake_ancestor)3866build_fake_ancestor(list, fake_ancestor);38673868if(diffstat)3869stat_patch_list(list);38703871if(numstat)3872numstat_patch_list(list);38733874if(summary)3875summary_patch_list(list);38763877free_patch_list(list);3878strbuf_release(&buf);3879string_list_clear(&fn_table,0);3880return0;3881}38823883static intgit_apply_config(const char*var,const char*value,void*cb)3884{3885if(!strcmp(var,"apply.whitespace"))3886returngit_config_string(&apply_default_whitespace, var, value);3887else if(!strcmp(var,"apply.ignorewhitespace"))3888returngit_config_string(&apply_default_ignorewhitespace, var, value);3889returngit_default_config(var, value, cb);3890}38913892static intoption_parse_exclude(const struct option *opt,3893const char*arg,int unset)3894{3895add_name_limit(arg,1);3896return0;3897}38983899static intoption_parse_include(const struct option *opt,3900const char*arg,int unset)3901{3902add_name_limit(arg,0);3903 has_include =1;3904return0;3905}39063907static intoption_parse_p(const struct option *opt,3908const char*arg,int unset)3909{3910 p_value =atoi(arg);3911 p_value_known =1;3912return0;3913}39143915static intoption_parse_z(const struct option *opt,3916const char*arg,int unset)3917{3918if(unset)3919 line_termination ='\n';3920else3921 line_termination =0;3922return0;3923}39243925static intoption_parse_space_change(const struct option *opt,3926const char*arg,int unset)3927{3928if(unset)3929 ws_ignore_action = ignore_ws_none;3930else3931 ws_ignore_action = ignore_ws_change;3932return0;3933}39343935static intoption_parse_whitespace(const struct option *opt,3936const char*arg,int unset)3937{3938const char**whitespace_option = opt->value;39393940*whitespace_option = arg;3941parse_whitespace_option(arg);3942return0;3943}39443945static intoption_parse_directory(const struct option *opt,3946const char*arg,int unset)3947{3948 root_len =strlen(arg);3949if(root_len && arg[root_len -1] !='/') {3950char*new_root;3951 root = new_root =xmalloc(root_len +2);3952strcpy(new_root, arg);3953strcpy(new_root + root_len++,"/");3954}else3955 root = arg;3956return0;3957}39583959intcmd_apply(int argc,const char**argv,const char*prefix_)3960{3961int i;3962int errs =0;3963int is_not_gitdir = !startup_info->have_repository;3964int force_apply =0;39653966const char*whitespace_option = NULL;39673968struct option builtin_apply_options[] = {3969{ OPTION_CALLBACK,0,"exclude", NULL,N_("path"),3970N_("don't apply changes matching the given path"),39710, option_parse_exclude },3972{ OPTION_CALLBACK,0,"include", NULL,N_("path"),3973N_("apply changes matching the given path"),39740, option_parse_include },3975{ OPTION_CALLBACK,'p', NULL, NULL,N_("num"),3976N_("remove <num> leading slashes from traditional diff paths"),39770, option_parse_p },3978OPT_BOOLEAN(0,"no-add", &no_add,3979N_("ignore additions made by the patch")),3980OPT_BOOLEAN(0,"stat", &diffstat,3981N_("instead of applying the patch, output diffstat for the input")),3982OPT_NOOP_NOARG(0,"allow-binary-replacement"),3983OPT_NOOP_NOARG(0,"binary"),3984OPT_BOOLEAN(0,"numstat", &numstat,3985N_("shows number of added and deleted lines in decimal notation")),3986OPT_BOOLEAN(0,"summary", &summary,3987N_("instead of applying the patch, output a summary for the input")),3988OPT_BOOLEAN(0,"check", &check,3989N_("instead of applying the patch, see if the patch is applicable")),3990OPT_BOOLEAN(0,"index", &check_index,3991N_("make sure the patch is applicable to the current index")),3992OPT_BOOLEAN(0,"cached", &cached,3993N_("apply a patch without touching the working tree")),3994OPT_BOOLEAN(0,"apply", &force_apply,3995N_("also apply the patch (use with --stat/--summary/--check)")),3996OPT_FILENAME(0,"build-fake-ancestor", &fake_ancestor,3997N_("build a temporary index based on embedded index information")),3998{ OPTION_CALLBACK,'z', NULL, NULL, NULL,3999N_("paths are separated with NUL character"),4000 PARSE_OPT_NOARG, option_parse_z },4001OPT_INTEGER('C', NULL, &p_context,4002N_("ensure at least <n> lines of context match")),4003{ OPTION_CALLBACK,0,"whitespace", &whitespace_option,N_("action"),4004N_("detect new or modified lines that have whitespace errors"),40050, option_parse_whitespace },4006{ OPTION_CALLBACK,0,"ignore-space-change", NULL, NULL,4007N_("ignore changes in whitespace when finding context"),4008 PARSE_OPT_NOARG, option_parse_space_change },4009{ OPTION_CALLBACK,0,"ignore-whitespace", NULL, NULL,4010N_("ignore changes in whitespace when finding context"),4011 PARSE_OPT_NOARG, option_parse_space_change },4012OPT_BOOLEAN('R',"reverse", &apply_in_reverse,4013N_("apply the patch in reverse")),4014OPT_BOOLEAN(0,"unidiff-zero", &unidiff_zero,4015N_("don't expect at least one line of context")),4016OPT_BOOLEAN(0,"reject", &apply_with_reject,4017N_("leave the rejected hunks in corresponding *.rej files")),4018OPT_BOOLEAN(0,"allow-overlap", &allow_overlap,4019N_("allow overlapping hunks")),4020OPT__VERBOSE(&apply_verbosely,N_("be verbose")),4021OPT_BIT(0,"inaccurate-eof", &options,4022N_("tolerate incorrectly detected missing new-line at the end of file"),4023 INACCURATE_EOF),4024OPT_BIT(0,"recount", &options,4025N_("do not trust the line counts in the hunk headers"),4026 RECOUNT),4027{ OPTION_CALLBACK,0,"directory", NULL,N_("root"),4028N_("prepend <root> to all filenames"),40290, option_parse_directory },4030OPT_END()4031};40324033 prefix = prefix_;4034 prefix_length = prefix ?strlen(prefix) :0;4035git_config(git_apply_config, NULL);4036if(apply_default_whitespace)4037parse_whitespace_option(apply_default_whitespace);4038if(apply_default_ignorewhitespace)4039parse_ignorewhitespace_option(apply_default_ignorewhitespace);40404041 argc =parse_options(argc, argv, prefix, builtin_apply_options,4042 apply_usage,0);40434044if(apply_with_reject)4045 apply = apply_verbosely =1;4046if(!force_apply && (diffstat || numstat || summary || check || fake_ancestor))4047 apply =0;4048if(check_index && is_not_gitdir)4049die(_("--index outside a repository"));4050if(cached) {4051if(is_not_gitdir)4052die(_("--cached outside a repository"));4053 check_index =1;4054}4055for(i =0; i < argc; i++) {4056const char*arg = argv[i];4057int fd;40584059if(!strcmp(arg,"-")) {4060 errs |=apply_patch(0,"<stdin>", options);4061 read_stdin =0;4062continue;4063}else if(0< prefix_length)4064 arg =prefix_filename(prefix, prefix_length, arg);40654066 fd =open(arg, O_RDONLY);4067if(fd <0)4068die_errno(_("can't open patch '%s'"), arg);4069 read_stdin =0;4070set_default_whitespace_mode(whitespace_option);4071 errs |=apply_patch(fd, arg, options);4072close(fd);4073}4074set_default_whitespace_mode(whitespace_option);4075if(read_stdin)4076 errs |=apply_patch(0,"<stdin>", options);4077if(whitespace_error) {4078if(squelch_whitespace_errors &&4079 squelch_whitespace_errors < whitespace_error) {4080int squelched =4081 whitespace_error - squelch_whitespace_errors;4082warning(Q_("squelched%dwhitespace error",4083"squelched%dwhitespace errors",4084 squelched),4085 squelched);4086}4087if(ws_error_action == die_on_ws_error)4088die(Q_("%dline adds whitespace errors.",4089"%dlines add whitespace errors.",4090 whitespace_error),4091 whitespace_error);4092if(applied_after_fixing_ws && apply)4093warning("%dline%sapplied after"4094" fixing whitespace errors.",4095 applied_after_fixing_ws,4096 applied_after_fixing_ws ==1?"":"s");4097else if(whitespace_error)4098warning(Q_("%dline adds whitespace errors.",4099"%dlines add whitespace errors.",4100 whitespace_error),4101 whitespace_error);4102}41034104if(update_index) {4105if(write_cache(newfd, active_cache, active_nr) ||4106commit_locked_index(&lock_file))4107die(_("Unable to write new index file"));4108}41094110return!!errs;4111}