1/* 2 * apply.c 3 * 4 * Copyright (C) Linus Torvalds, 2005 5 * 6 * This applies patches on top of some (arbitrary) version of the SCM. 7 * 8 */ 9#include"cache.h" 10#include"cache-tree.h" 11#include"quote.h" 12#include"blob.h" 13#include"delta.h" 14#include"builtin.h" 15#include"string-list.h" 16#include"dir.h" 17#include"diff.h" 18#include"parse-options.h" 19 20/* 21 * --check turns on checking that the working tree matches the 22 * files that are being modified, but doesn't apply the patch 23 * --stat does just a diffstat, and doesn't actually apply 24 * --numstat does numeric diffstat, and doesn't actually apply 25 * --index-info shows the old and new index info for paths if available. 26 * --index updates the cache as well. 27 * --cached updates only the cache without ever touching the working tree. 28 */ 29static const char*prefix; 30static int prefix_length = -1; 31static int newfd = -1; 32 33static int unidiff_zero; 34static int p_value =1; 35static int p_value_known; 36static int check_index; 37static int update_index; 38static int cached; 39static int diffstat; 40static int numstat; 41static int summary; 42static int check; 43static int apply =1; 44static int apply_in_reverse; 45static int apply_with_reject; 46static int apply_verbosely; 47static int allow_overlap; 48static int no_add; 49static const char*fake_ancestor; 50static int line_termination ='\n'; 51static unsigned int p_context = UINT_MAX; 52static const char*const apply_usage[] = { 53"git apply [options] [<patch>...]", 54 NULL 55}; 56 57static enum ws_error_action { 58 nowarn_ws_error, 59 warn_on_ws_error, 60 die_on_ws_error, 61 correct_ws_error 62} ws_error_action = warn_on_ws_error; 63static int whitespace_error; 64static int squelch_whitespace_errors =5; 65static int applied_after_fixing_ws; 66 67static enum ws_ignore { 68 ignore_ws_none, 69 ignore_ws_change 70} ws_ignore_action = ignore_ws_none; 71 72 73static const char*patch_input_file; 74static const char*root; 75static int root_len; 76static int read_stdin =1; 77static int options; 78 79static voidparse_whitespace_option(const char*option) 80{ 81if(!option) { 82 ws_error_action = warn_on_ws_error; 83return; 84} 85if(!strcmp(option,"warn")) { 86 ws_error_action = warn_on_ws_error; 87return; 88} 89if(!strcmp(option,"nowarn")) { 90 ws_error_action = nowarn_ws_error; 91return; 92} 93if(!strcmp(option,"error")) { 94 ws_error_action = die_on_ws_error; 95return; 96} 97if(!strcmp(option,"error-all")) { 98 ws_error_action = die_on_ws_error; 99 squelch_whitespace_errors =0; 100return; 101} 102if(!strcmp(option,"strip") || !strcmp(option,"fix")) { 103 ws_error_action = correct_ws_error; 104return; 105} 106die(_("unrecognized whitespace option '%s'"), option); 107} 108 109static voidparse_ignorewhitespace_option(const char*option) 110{ 111if(!option || !strcmp(option,"no") || 112!strcmp(option,"false") || !strcmp(option,"never") || 113!strcmp(option,"none")) { 114 ws_ignore_action = ignore_ws_none; 115return; 116} 117if(!strcmp(option,"change")) { 118 ws_ignore_action = ignore_ws_change; 119return; 120} 121die(_("unrecognized whitespace ignore option '%s'"), option); 122} 123 124static voidset_default_whitespace_mode(const char*whitespace_option) 125{ 126if(!whitespace_option && !apply_default_whitespace) 127 ws_error_action = (apply ? warn_on_ws_error : nowarn_ws_error); 128} 129 130/* 131 * For "diff-stat" like behaviour, we keep track of the biggest change 132 * we've seen, and the longest filename. That allows us to do simple 133 * scaling. 134 */ 135static int max_change, max_len; 136 137/* 138 * Various "current state", notably line numbers and what 139 * file (and how) we're patching right now.. The "is_xxxx" 140 * things are flags, where -1 means "don't know yet". 141 */ 142static int linenr =1; 143 144/* 145 * This represents one "hunk" from a patch, starting with 146 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The 147 * patch text is pointed at by patch, and its byte length 148 * is stored in size. leading and trailing are the number 149 * of context lines. 150 */ 151struct fragment { 152unsigned long leading, trailing; 153unsigned long oldpos, oldlines; 154unsigned long newpos, newlines; 155const char*patch; 156int size; 157int rejected; 158int linenr; 159struct fragment *next; 160}; 161 162/* 163 * When dealing with a binary patch, we reuse "leading" field 164 * to store the type of the binary hunk, either deflated "delta" 165 * or deflated "literal". 166 */ 167#define binary_patch_method leading 168#define BINARY_DELTA_DEFLATED 1 169#define BINARY_LITERAL_DEFLATED 2 170 171/* 172 * This represents a "patch" to a file, both metainfo changes 173 * such as creation/deletion, filemode and content changes represented 174 * as a series of fragments. 175 */ 176struct patch { 177char*new_name, *old_name, *def_name; 178unsigned int old_mode, new_mode; 179int is_new, is_delete;/* -1 = unknown, 0 = false, 1 = true */ 180int rejected; 181unsigned ws_rule; 182unsigned long deflate_origlen; 183int lines_added, lines_deleted; 184int score; 185unsigned int is_toplevel_relative:1; 186unsigned int inaccurate_eof:1; 187unsigned int is_binary:1; 188unsigned int is_copy:1; 189unsigned int is_rename:1; 190unsigned int recount:1; 191struct fragment *fragments; 192char*result; 193size_t resultsize; 194char old_sha1_prefix[41]; 195char new_sha1_prefix[41]; 196struct patch *next; 197}; 198 199/* 200 * A line in a file, len-bytes long (includes the terminating LF, 201 * except for an incomplete line at the end if the file ends with 202 * one), and its contents hashes to 'hash'. 203 */ 204struct line { 205size_t len; 206unsigned hash :24; 207unsigned flag :8; 208#define LINE_COMMON 1 209#define LINE_PATCHED 2 210}; 211 212/* 213 * This represents a "file", which is an array of "lines". 214 */ 215struct image { 216char*buf; 217size_t len; 218size_t nr; 219size_t alloc; 220struct line *line_allocated; 221struct line *line; 222}; 223 224/* 225 * Records filenames that have been touched, in order to handle 226 * the case where more than one patches touch the same file. 227 */ 228 229static struct string_list fn_table; 230 231static uint32_thash_line(const char*cp,size_t len) 232{ 233size_t i; 234uint32_t h; 235for(i =0, h =0; i < len; i++) { 236if(!isspace(cp[i])) { 237 h = h *3+ (cp[i] &0xff); 238} 239} 240return h; 241} 242 243/* 244 * Compare lines s1 of length n1 and s2 of length n2, ignoring 245 * whitespace difference. Returns 1 if they match, 0 otherwise 246 */ 247static intfuzzy_matchlines(const char*s1,size_t n1, 248const char*s2,size_t n2) 249{ 250const char*last1 = s1 + n1 -1; 251const char*last2 = s2 + n2 -1; 252int result =0; 253 254/* ignore line endings */ 255while((*last1 =='\r') || (*last1 =='\n')) 256 last1--; 257while((*last2 =='\r') || (*last2 =='\n')) 258 last2--; 259 260/* skip leading whitespace */ 261while(isspace(*s1) && (s1 <= last1)) 262 s1++; 263while(isspace(*s2) && (s2 <= last2)) 264 s2++; 265/* early return if both lines are empty */ 266if((s1 > last1) && (s2 > last2)) 267return1; 268while(!result) { 269 result = *s1++ - *s2++; 270/* 271 * Skip whitespace inside. We check for whitespace on 272 * both buffers because we don't want "a b" to match 273 * "ab" 274 */ 275if(isspace(*s1) &&isspace(*s2)) { 276while(isspace(*s1) && s1 <= last1) 277 s1++; 278while(isspace(*s2) && s2 <= last2) 279 s2++; 280} 281/* 282 * If we reached the end on one side only, 283 * lines don't match 284 */ 285if( 286((s2 > last2) && (s1 <= last1)) || 287((s1 > last1) && (s2 <= last2))) 288return0; 289if((s1 > last1) && (s2 > last2)) 290break; 291} 292 293return!result; 294} 295 296static voidadd_line_info(struct image *img,const char*bol,size_t len,unsigned flag) 297{ 298ALLOC_GROW(img->line_allocated, img->nr +1, img->alloc); 299 img->line_allocated[img->nr].len = len; 300 img->line_allocated[img->nr].hash =hash_line(bol, len); 301 img->line_allocated[img->nr].flag = flag; 302 img->nr++; 303} 304 305static voidprepare_image(struct image *image,char*buf,size_t len, 306int prepare_linetable) 307{ 308const char*cp, *ep; 309 310memset(image,0,sizeof(*image)); 311 image->buf = buf; 312 image->len = len; 313 314if(!prepare_linetable) 315return; 316 317 ep = image->buf + image->len; 318 cp = image->buf; 319while(cp < ep) { 320const char*next; 321for(next = cp; next < ep && *next !='\n'; next++) 322; 323if(next < ep) 324 next++; 325add_line_info(image, cp, next - cp,0); 326 cp = next; 327} 328 image->line = image->line_allocated; 329} 330 331static voidclear_image(struct image *image) 332{ 333free(image->buf); 334 image->buf = NULL; 335 image->len =0; 336} 337 338/* fmt must contain _one_ %s and no other substitution */ 339static voidsay_patch_name(FILE*output,const char*fmt,struct patch *patch) 340{ 341struct strbuf sb = STRBUF_INIT; 342 343if(patch->old_name && patch->new_name && 344strcmp(patch->old_name, patch->new_name)) { 345quote_c_style(patch->old_name, &sb, NULL,0); 346strbuf_addstr(&sb," => "); 347quote_c_style(patch->new_name, &sb, NULL,0); 348}else{ 349const char*n = patch->new_name; 350if(!n) 351 n = patch->old_name; 352quote_c_style(n, &sb, NULL,0); 353} 354fprintf(output, fmt, sb.buf); 355fputc('\n', output); 356strbuf_release(&sb); 357} 358 359#define CHUNKSIZE (8192) 360#define SLOP (16) 361 362static voidread_patch_file(struct strbuf *sb,int fd) 363{ 364if(strbuf_read(sb, fd,0) <0) 365die_errno("git apply: failed to read"); 366 367/* 368 * Make sure that we have some slop in the buffer 369 * so that we can do speculative "memcmp" etc, and 370 * see to it that it is NUL-filled. 371 */ 372strbuf_grow(sb, SLOP); 373memset(sb->buf + sb->len,0, SLOP); 374} 375 376static unsigned longlinelen(const char*buffer,unsigned long size) 377{ 378unsigned long len =0; 379while(size--) { 380 len++; 381if(*buffer++ =='\n') 382break; 383} 384return len; 385} 386 387static intis_dev_null(const char*str) 388{ 389return!memcmp("/dev/null", str,9) &&isspace(str[9]); 390} 391 392#define TERM_SPACE 1 393#define TERM_TAB 2 394 395static intname_terminate(const char*name,int namelen,int c,int terminate) 396{ 397if(c ==' '&& !(terminate & TERM_SPACE)) 398return0; 399if(c =='\t'&& !(terminate & TERM_TAB)) 400return0; 401 402return1; 403} 404 405/* remove double slashes to make --index work with such filenames */ 406static char*squash_slash(char*name) 407{ 408int i =0, j =0; 409 410if(!name) 411return NULL; 412 413while(name[i]) { 414if((name[j++] = name[i++]) =='/') 415while(name[i] =='/') 416 i++; 417} 418 name[j] ='\0'; 419return name; 420} 421 422static char*find_name_gnu(const char*line,char*def,int p_value) 423{ 424struct strbuf name = STRBUF_INIT; 425char*cp; 426 427/* 428 * Proposed "new-style" GNU patch/diff format; see 429 * http://marc.theaimsgroup.com/?l=git&m=112927316408690&w=2 430 */ 431if(unquote_c_style(&name, line, NULL)) { 432strbuf_release(&name); 433return NULL; 434} 435 436for(cp = name.buf; p_value; p_value--) { 437 cp =strchr(cp,'/'); 438if(!cp) { 439strbuf_release(&name); 440return NULL; 441} 442 cp++; 443} 444 445/* name can later be freed, so we need 446 * to memmove, not just return cp 447 */ 448strbuf_remove(&name,0, cp - name.buf); 449free(def); 450if(root) 451strbuf_insert(&name,0, root, root_len); 452returnsquash_slash(strbuf_detach(&name, NULL)); 453} 454 455static size_tsane_tz_len(const char*line,size_t len) 456{ 457const char*tz, *p; 458 459if(len <strlen(" +0500") || line[len-strlen(" +0500")] !=' ') 460return0; 461 tz = line + len -strlen(" +0500"); 462 463if(tz[1] !='+'&& tz[1] !='-') 464return0; 465 466for(p = tz +2; p != line + len; p++) 467if(!isdigit(*p)) 468return0; 469 470return line + len - tz; 471} 472 473static size_ttz_with_colon_len(const char*line,size_t len) 474{ 475const char*tz, *p; 476 477if(len <strlen(" +08:00") || line[len -strlen(":00")] !=':') 478return0; 479 tz = line + len -strlen(" +08:00"); 480 481if(tz[0] !=' '|| (tz[1] !='+'&& tz[1] !='-')) 482return0; 483 p = tz +2; 484if(!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 485!isdigit(*p++) || !isdigit(*p++)) 486return0; 487 488return line + len - tz; 489} 490 491static size_tdate_len(const char*line,size_t len) 492{ 493const char*date, *p; 494 495if(len <strlen("72-02-05") || line[len-strlen("-05")] !='-') 496return0; 497 p = date = line + len -strlen("72-02-05"); 498 499if(!isdigit(*p++) || !isdigit(*p++) || *p++ !='-'|| 500!isdigit(*p++) || !isdigit(*p++) || *p++ !='-'|| 501!isdigit(*p++) || !isdigit(*p++))/* Not a date. */ 502return0; 503 504if(date - line >=strlen("19") && 505isdigit(date[-1]) &&isdigit(date[-2]))/* 4-digit year */ 506 date -=strlen("19"); 507 508return line + len - date; 509} 510 511static size_tshort_time_len(const char*line,size_t len) 512{ 513const char*time, *p; 514 515if(len <strlen(" 07:01:32") || line[len-strlen(":32")] !=':') 516return0; 517 p = time = line + len -strlen(" 07:01:32"); 518 519/* Permit 1-digit hours? */ 520if(*p++ !=' '|| 521!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 522!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 523!isdigit(*p++) || !isdigit(*p++))/* Not a time. */ 524return0; 525 526return line + len - time; 527} 528 529static size_tfractional_time_len(const char*line,size_t len) 530{ 531const char*p; 532size_t n; 533 534/* Expected format: 19:41:17.620000023 */ 535if(!len || !isdigit(line[len -1])) 536return0; 537 p = line + len -1; 538 539/* Fractional seconds. */ 540while(p > line &&isdigit(*p)) 541 p--; 542if(*p !='.') 543return0; 544 545/* Hours, minutes, and whole seconds. */ 546 n =short_time_len(line, p - line); 547if(!n) 548return0; 549 550return line + len - p + n; 551} 552 553static size_ttrailing_spaces_len(const char*line,size_t len) 554{ 555const char*p; 556 557/* Expected format: ' ' x (1 or more) */ 558if(!len || line[len -1] !=' ') 559return0; 560 561 p = line + len; 562while(p != line) { 563 p--; 564if(*p !=' ') 565return line + len - (p +1); 566} 567 568/* All spaces! */ 569return len; 570} 571 572static size_tdiff_timestamp_len(const char*line,size_t len) 573{ 574const char*end = line + len; 575size_t n; 576 577/* 578 * Posix: 2010-07-05 19:41:17 579 * GNU: 2010-07-05 19:41:17.620000023 -0500 580 */ 581 582if(!isdigit(end[-1])) 583return0; 584 585 n =sane_tz_len(line, end - line); 586if(!n) 587 n =tz_with_colon_len(line, end - line); 588 end -= n; 589 590 n =short_time_len(line, end - line); 591if(!n) 592 n =fractional_time_len(line, end - line); 593 end -= n; 594 595 n =date_len(line, end - line); 596if(!n)/* No date. Too bad. */ 597return0; 598 end -= n; 599 600if(end == line)/* No space before date. */ 601return0; 602if(end[-1] =='\t') {/* Success! */ 603 end--; 604return line + len - end; 605} 606if(end[-1] !=' ')/* No space before date. */ 607return0; 608 609/* Whitespace damage. */ 610 end -=trailing_spaces_len(line, end - line); 611return line + len - end; 612} 613 614static char*find_name_common(const char*line,char*def,int p_value, 615const char*end,int terminate) 616{ 617int len; 618const char*start = NULL; 619 620if(p_value ==0) 621 start = line; 622while(line != end) { 623char c = *line; 624 625if(!end &&isspace(c)) { 626if(c =='\n') 627break; 628if(name_terminate(start, line-start, c, terminate)) 629break; 630} 631 line++; 632if(c =='/'&& !--p_value) 633 start = line; 634} 635if(!start) 636returnsquash_slash(def); 637 len = line - start; 638if(!len) 639returnsquash_slash(def); 640 641/* 642 * Generally we prefer the shorter name, especially 643 * if the other one is just a variation of that with 644 * something else tacked on to the end (ie "file.orig" 645 * or "file~"). 646 */ 647if(def) { 648int deflen =strlen(def); 649if(deflen < len && !strncmp(start, def, deflen)) 650returnsquash_slash(def); 651free(def); 652} 653 654if(root) { 655char*ret =xmalloc(root_len + len +1); 656strcpy(ret, root); 657memcpy(ret + root_len, start, len); 658 ret[root_len + len] ='\0'; 659returnsquash_slash(ret); 660} 661 662returnsquash_slash(xmemdupz(start, len)); 663} 664 665static char*find_name(const char*line,char*def,int p_value,int terminate) 666{ 667if(*line =='"') { 668char*name =find_name_gnu(line, def, p_value); 669if(name) 670return name; 671} 672 673returnfind_name_common(line, def, p_value, NULL, terminate); 674} 675 676static char*find_name_traditional(const char*line,char*def,int p_value) 677{ 678size_t len =strlen(line); 679size_t date_len; 680 681if(*line =='"') { 682char*name =find_name_gnu(line, def, p_value); 683if(name) 684return name; 685} 686 687 len =strchrnul(line,'\n') - line; 688 date_len =diff_timestamp_len(line, len); 689if(!date_len) 690returnfind_name_common(line, def, p_value, NULL, TERM_TAB); 691 len -= date_len; 692 693returnfind_name_common(line, def, p_value, line + len,0); 694} 695 696static intcount_slashes(const char*cp) 697{ 698int cnt =0; 699char ch; 700 701while((ch = *cp++)) 702if(ch =='/') 703 cnt++; 704return cnt; 705} 706 707/* 708 * Given the string after "--- " or "+++ ", guess the appropriate 709 * p_value for the given patch. 710 */ 711static intguess_p_value(const char*nameline) 712{ 713char*name, *cp; 714int val = -1; 715 716if(is_dev_null(nameline)) 717return-1; 718 name =find_name_traditional(nameline, NULL,0); 719if(!name) 720return-1; 721 cp =strchr(name,'/'); 722if(!cp) 723 val =0; 724else if(prefix) { 725/* 726 * Does it begin with "a/$our-prefix" and such? Then this is 727 * very likely to apply to our directory. 728 */ 729if(!strncmp(name, prefix, prefix_length)) 730 val =count_slashes(prefix); 731else{ 732 cp++; 733if(!strncmp(cp, prefix, prefix_length)) 734 val =count_slashes(prefix) +1; 735} 736} 737free(name); 738return val; 739} 740 741/* 742 * Does the ---/+++ line has the POSIX timestamp after the last HT? 743 * GNU diff puts epoch there to signal a creation/deletion event. Is 744 * this such a timestamp? 745 */ 746static inthas_epoch_timestamp(const char*nameline) 747{ 748/* 749 * We are only interested in epoch timestamp; any non-zero 750 * fraction cannot be one, hence "(\.0+)?" in the regexp below. 751 * For the same reason, the date must be either 1969-12-31 or 752 * 1970-01-01, and the seconds part must be "00". 753 */ 754const char stamp_regexp[] = 755"^(1969-12-31|1970-01-01)" 756" " 757"[0-2][0-9]:[0-5][0-9]:00(\\.0+)?" 758" " 759"([-+][0-2][0-9]:?[0-5][0-9])\n"; 760const char*timestamp = NULL, *cp, *colon; 761static regex_t *stamp; 762 regmatch_t m[10]; 763int zoneoffset; 764int hourminute; 765int status; 766 767for(cp = nameline; *cp !='\n'; cp++) { 768if(*cp =='\t') 769 timestamp = cp +1; 770} 771if(!timestamp) 772return0; 773if(!stamp) { 774 stamp =xmalloc(sizeof(*stamp)); 775if(regcomp(stamp, stamp_regexp, REG_EXTENDED)) { 776warning(_("Cannot prepare timestamp regexp%s"), 777 stamp_regexp); 778return0; 779} 780} 781 782 status =regexec(stamp, timestamp,ARRAY_SIZE(m), m,0); 783if(status) { 784if(status != REG_NOMATCH) 785warning(_("regexec returned%dfor input:%s"), 786 status, timestamp); 787return0; 788} 789 790 zoneoffset =strtol(timestamp + m[3].rm_so +1, (char**) &colon,10); 791if(*colon ==':') 792 zoneoffset = zoneoffset *60+strtol(colon +1, NULL,10); 793else 794 zoneoffset = (zoneoffset /100) *60+ (zoneoffset %100); 795if(timestamp[m[3].rm_so] =='-') 796 zoneoffset = -zoneoffset; 797 798/* 799 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31 800 * (west of GMT) or 1970-01-01 (east of GMT) 801 */ 802if((zoneoffset <0&&memcmp(timestamp,"1969-12-31",10)) || 803(0<= zoneoffset &&memcmp(timestamp,"1970-01-01",10))) 804return0; 805 806 hourminute = (strtol(timestamp +11, NULL,10) *60+ 807strtol(timestamp +14, NULL,10) - 808 zoneoffset); 809 810return((zoneoffset <0&& hourminute ==1440) || 811(0<= zoneoffset && !hourminute)); 812} 813 814/* 815 * Get the name etc info from the ---/+++ lines of a traditional patch header 816 * 817 * FIXME! The end-of-filename heuristics are kind of screwy. For existing 818 * files, we can happily check the index for a match, but for creating a 819 * new file we should try to match whatever "patch" does. I have no idea. 820 */ 821static voidparse_traditional_patch(const char*first,const char*second,struct patch *patch) 822{ 823char*name; 824 825 first +=4;/* skip "--- " */ 826 second +=4;/* skip "+++ " */ 827if(!p_value_known) { 828int p, q; 829 p =guess_p_value(first); 830 q =guess_p_value(second); 831if(p <0) p = q; 832if(0<= p && p == q) { 833 p_value = p; 834 p_value_known =1; 835} 836} 837if(is_dev_null(first)) { 838 patch->is_new =1; 839 patch->is_delete =0; 840 name =find_name_traditional(second, NULL, p_value); 841 patch->new_name = name; 842}else if(is_dev_null(second)) { 843 patch->is_new =0; 844 patch->is_delete =1; 845 name =find_name_traditional(first, NULL, p_value); 846 patch->old_name = name; 847}else{ 848 name =find_name_traditional(first, NULL, p_value); 849 name =find_name_traditional(second, name, p_value); 850if(has_epoch_timestamp(first)) { 851 patch->is_new =1; 852 patch->is_delete =0; 853 patch->new_name = name; 854}else if(has_epoch_timestamp(second)) { 855 patch->is_new =0; 856 patch->is_delete =1; 857 patch->old_name = name; 858}else{ 859 patch->old_name = patch->new_name = name; 860} 861} 862if(!name) 863die(_("unable to find filename in patch at line%d"), linenr); 864} 865 866static intgitdiff_hdrend(const char*line,struct patch *patch) 867{ 868return-1; 869} 870 871/* 872 * We're anal about diff header consistency, to make 873 * sure that we don't end up having strange ambiguous 874 * patches floating around. 875 * 876 * As a result, gitdiff_{old|new}name() will check 877 * their names against any previous information, just 878 * to make sure.. 879 */ 880static char*gitdiff_verify_name(const char*line,int isnull,char*orig_name,const char*oldnew) 881{ 882if(!orig_name && !isnull) 883returnfind_name(line, NULL, p_value, TERM_TAB); 884 885if(orig_name) { 886int len; 887const char*name; 888char*another; 889 name = orig_name; 890 len =strlen(name); 891if(isnull) 892die(_("git apply: bad git-diff - expected /dev/null, got%son line%d"), name, linenr); 893 another =find_name(line, NULL, p_value, TERM_TAB); 894if(!another ||memcmp(another, name, len +1)) 895die(_("git apply: bad git-diff - inconsistent%sfilename on line%d"), oldnew, linenr); 896free(another); 897return orig_name; 898} 899else{ 900/* expect "/dev/null" */ 901if(memcmp("/dev/null", line,9) || line[9] !='\n') 902die(_("git apply: bad git-diff - expected /dev/null on line%d"), linenr); 903return NULL; 904} 905} 906 907static intgitdiff_oldname(const char*line,struct patch *patch) 908{ 909 patch->old_name =gitdiff_verify_name(line, patch->is_new, patch->old_name,"old"); 910return0; 911} 912 913static intgitdiff_newname(const char*line,struct patch *patch) 914{ 915 patch->new_name =gitdiff_verify_name(line, patch->is_delete, patch->new_name,"new"); 916return0; 917} 918 919static intgitdiff_oldmode(const char*line,struct patch *patch) 920{ 921 patch->old_mode =strtoul(line, NULL,8); 922return0; 923} 924 925static intgitdiff_newmode(const char*line,struct patch *patch) 926{ 927 patch->new_mode =strtoul(line, NULL,8); 928return0; 929} 930 931static intgitdiff_delete(const char*line,struct patch *patch) 932{ 933 patch->is_delete =1; 934 patch->old_name = patch->def_name; 935returngitdiff_oldmode(line, patch); 936} 937 938static intgitdiff_newfile(const char*line,struct patch *patch) 939{ 940 patch->is_new =1; 941 patch->new_name = patch->def_name; 942returngitdiff_newmode(line, patch); 943} 944 945static intgitdiff_copysrc(const char*line,struct patch *patch) 946{ 947 patch->is_copy =1; 948 patch->old_name =find_name(line, NULL, p_value ? p_value -1:0,0); 949return0; 950} 951 952static intgitdiff_copydst(const char*line,struct patch *patch) 953{ 954 patch->is_copy =1; 955 patch->new_name =find_name(line, NULL, p_value ? p_value -1:0,0); 956return0; 957} 958 959static intgitdiff_renamesrc(const char*line,struct patch *patch) 960{ 961 patch->is_rename =1; 962 patch->old_name =find_name(line, NULL, p_value ? p_value -1:0,0); 963return0; 964} 965 966static intgitdiff_renamedst(const char*line,struct patch *patch) 967{ 968 patch->is_rename =1; 969 patch->new_name =find_name(line, NULL, p_value ? p_value -1:0,0); 970return0; 971} 972 973static intgitdiff_similarity(const char*line,struct patch *patch) 974{ 975if((patch->score =strtoul(line, NULL,10)) == ULONG_MAX) 976 patch->score =0; 977return0; 978} 979 980static intgitdiff_dissimilarity(const char*line,struct patch *patch) 981{ 982if((patch->score =strtoul(line, NULL,10)) == ULONG_MAX) 983 patch->score =0; 984return0; 985} 986 987static intgitdiff_index(const char*line,struct patch *patch) 988{ 989/* 990 * index line is N hexadecimal, "..", N hexadecimal, 991 * and optional space with octal mode. 992 */ 993const char*ptr, *eol; 994int len; 995 996 ptr =strchr(line,'.'); 997if(!ptr || ptr[1] !='.'||40< ptr - line) 998return0; 999 len = ptr - line;1000memcpy(patch->old_sha1_prefix, line, len);1001 patch->old_sha1_prefix[len] =0;10021003 line = ptr +2;1004 ptr =strchr(line,' ');1005 eol =strchr(line,'\n');10061007if(!ptr || eol < ptr)1008 ptr = eol;1009 len = ptr - line;10101011if(40< len)1012return0;1013memcpy(patch->new_sha1_prefix, line, len);1014 patch->new_sha1_prefix[len] =0;1015if(*ptr ==' ')1016 patch->old_mode =strtoul(ptr+1, NULL,8);1017return0;1018}10191020/*1021 * This is normal for a diff that doesn't change anything: we'll fall through1022 * into the next diff. Tell the parser to break out.1023 */1024static intgitdiff_unrecognized(const char*line,struct patch *patch)1025{1026return-1;1027}10281029static const char*stop_at_slash(const char*line,int llen)1030{1031int nslash = p_value;1032int i;10331034for(i =0; i < llen; i++) {1035int ch = line[i];1036if(ch =='/'&& --nslash <=0)1037return&line[i];1038}1039return NULL;1040}10411042/*1043 * This is to extract the same name that appears on "diff --git"1044 * line. We do not find and return anything if it is a rename1045 * patch, and it is OK because we will find the name elsewhere.1046 * We need to reliably find name only when it is mode-change only,1047 * creation or deletion of an empty file. In any of these cases,1048 * both sides are the same name under a/ and b/ respectively.1049 */1050static char*git_header_name(char*line,int llen)1051{1052const char*name;1053const char*second = NULL;1054size_t len, line_len;10551056 line +=strlen("diff --git ");1057 llen -=strlen("diff --git ");10581059if(*line =='"') {1060const char*cp;1061struct strbuf first = STRBUF_INIT;1062struct strbuf sp = STRBUF_INIT;10631064if(unquote_c_style(&first, line, &second))1065goto free_and_fail1;10661067/* advance to the first slash */1068 cp =stop_at_slash(first.buf, first.len);1069/* we do not accept absolute paths */1070if(!cp || cp == first.buf)1071goto free_and_fail1;1072strbuf_remove(&first,0, cp +1- first.buf);10731074/*1075 * second points at one past closing dq of name.1076 * find the second name.1077 */1078while((second < line + llen) &&isspace(*second))1079 second++;10801081if(line + llen <= second)1082goto free_and_fail1;1083if(*second =='"') {1084if(unquote_c_style(&sp, second, NULL))1085goto free_and_fail1;1086 cp =stop_at_slash(sp.buf, sp.len);1087if(!cp || cp == sp.buf)1088goto free_and_fail1;1089/* They must match, otherwise ignore */1090if(strcmp(cp +1, first.buf))1091goto free_and_fail1;1092strbuf_release(&sp);1093returnstrbuf_detach(&first, NULL);1094}10951096/* unquoted second */1097 cp =stop_at_slash(second, line + llen - second);1098if(!cp || cp == second)1099goto free_and_fail1;1100 cp++;1101if(line + llen - cp != first.len +1||1102memcmp(first.buf, cp, first.len))1103goto free_and_fail1;1104returnstrbuf_detach(&first, NULL);11051106 free_and_fail1:1107strbuf_release(&first);1108strbuf_release(&sp);1109return NULL;1110}11111112/* unquoted first name */1113 name =stop_at_slash(line, llen);1114if(!name || name == line)1115return NULL;1116 name++;11171118/*1119 * since the first name is unquoted, a dq if exists must be1120 * the beginning of the second name.1121 */1122for(second = name; second < line + llen; second++) {1123if(*second =='"') {1124struct strbuf sp = STRBUF_INIT;1125const char*np;11261127if(unquote_c_style(&sp, second, NULL))1128goto free_and_fail2;11291130 np =stop_at_slash(sp.buf, sp.len);1131if(!np || np == sp.buf)1132goto free_and_fail2;1133 np++;11341135 len = sp.buf + sp.len - np;1136if(len < second - name &&1137!strncmp(np, name, len) &&1138isspace(name[len])) {1139/* Good */1140strbuf_remove(&sp,0, np - sp.buf);1141returnstrbuf_detach(&sp, NULL);1142}11431144 free_and_fail2:1145strbuf_release(&sp);1146return NULL;1147}1148}11491150/*1151 * Accept a name only if it shows up twice, exactly the same1152 * form.1153 */1154 second =strchr(name,'\n');1155if(!second)1156return NULL;1157 line_len = second - name;1158for(len =0; ; len++) {1159switch(name[len]) {1160default:1161continue;1162case'\n':1163return NULL;1164case'\t':case' ':1165 second =stop_at_slash(name + len, line_len - len);1166if(!second)1167return NULL;1168 second++;1169if(second[len] =='\n'&& !strncmp(name, second, len)) {1170returnxmemdupz(name, len);1171}1172}1173}1174}11751176/* Verify that we recognize the lines following a git header */1177static intparse_git_header(char*line,int len,unsigned int size,struct patch *patch)1178{1179unsigned long offset;11801181/* A git diff has explicit new/delete information, so we don't guess */1182 patch->is_new =0;1183 patch->is_delete =0;11841185/*1186 * Some things may not have the old name in the1187 * rest of the headers anywhere (pure mode changes,1188 * or removing or adding empty files), so we get1189 * the default name from the header.1190 */1191 patch->def_name =git_header_name(line, len);1192if(patch->def_name && root) {1193char*s =xmalloc(root_len +strlen(patch->def_name) +1);1194strcpy(s, root);1195strcpy(s + root_len, patch->def_name);1196free(patch->def_name);1197 patch->def_name = s;1198}11991200 line += len;1201 size -= len;1202 linenr++;1203for(offset = len ; size >0; offset += len, size -= len, line += len, linenr++) {1204static const struct opentry {1205const char*str;1206int(*fn)(const char*,struct patch *);1207} optable[] = {1208{"@@ -", gitdiff_hdrend },1209{"--- ", gitdiff_oldname },1210{"+++ ", gitdiff_newname },1211{"old mode ", gitdiff_oldmode },1212{"new mode ", gitdiff_newmode },1213{"deleted file mode ", gitdiff_delete },1214{"new file mode ", gitdiff_newfile },1215{"copy from ", gitdiff_copysrc },1216{"copy to ", gitdiff_copydst },1217{"rename old ", gitdiff_renamesrc },1218{"rename new ", gitdiff_renamedst },1219{"rename from ", gitdiff_renamesrc },1220{"rename to ", gitdiff_renamedst },1221{"similarity index ", gitdiff_similarity },1222{"dissimilarity index ", gitdiff_dissimilarity },1223{"index ", gitdiff_index },1224{"", gitdiff_unrecognized },1225};1226int i;12271228 len =linelen(line, size);1229if(!len || line[len-1] !='\n')1230break;1231for(i =0; i <ARRAY_SIZE(optable); i++) {1232const struct opentry *p = optable + i;1233int oplen =strlen(p->str);1234if(len < oplen ||memcmp(p->str, line, oplen))1235continue;1236if(p->fn(line + oplen, patch) <0)1237return offset;1238break;1239}1240}12411242return offset;1243}12441245static intparse_num(const char*line,unsigned long*p)1246{1247char*ptr;12481249if(!isdigit(*line))1250return0;1251*p =strtoul(line, &ptr,10);1252return ptr - line;1253}12541255static intparse_range(const char*line,int len,int offset,const char*expect,1256unsigned long*p1,unsigned long*p2)1257{1258int digits, ex;12591260if(offset <0|| offset >= len)1261return-1;1262 line += offset;1263 len -= offset;12641265 digits =parse_num(line, p1);1266if(!digits)1267return-1;12681269 offset += digits;1270 line += digits;1271 len -= digits;12721273*p2 =1;1274if(*line ==',') {1275 digits =parse_num(line+1, p2);1276if(!digits)1277return-1;12781279 offset += digits+1;1280 line += digits+1;1281 len -= digits+1;1282}12831284 ex =strlen(expect);1285if(ex > len)1286return-1;1287if(memcmp(line, expect, ex))1288return-1;12891290return offset + ex;1291}12921293static voidrecount_diff(char*line,int size,struct fragment *fragment)1294{1295int oldlines =0, newlines =0, ret =0;12961297if(size <1) {1298warning("recount: ignore empty hunk");1299return;1300}13011302for(;;) {1303int len =linelen(line, size);1304 size -= len;1305 line += len;13061307if(size <1)1308break;13091310switch(*line) {1311case' ':case'\n':1312 newlines++;1313/* fall through */1314case'-':1315 oldlines++;1316continue;1317case'+':1318 newlines++;1319continue;1320case'\\':1321continue;1322case'@':1323 ret = size <3||prefixcmp(line,"@@ ");1324break;1325case'd':1326 ret = size <5||prefixcmp(line,"diff ");1327break;1328default:1329 ret = -1;1330break;1331}1332if(ret) {1333warning(_("recount: unexpected line: %.*s"),1334(int)linelen(line, size), line);1335return;1336}1337break;1338}1339 fragment->oldlines = oldlines;1340 fragment->newlines = newlines;1341}13421343/*1344 * Parse a unified diff fragment header of the1345 * form "@@ -a,b +c,d @@"1346 */1347static intparse_fragment_header(char*line,int len,struct fragment *fragment)1348{1349int offset;13501351if(!len || line[len-1] !='\n')1352return-1;13531354/* Figure out the number of lines in a fragment */1355 offset =parse_range(line, len,4," +", &fragment->oldpos, &fragment->oldlines);1356 offset =parse_range(line, len, offset," @@", &fragment->newpos, &fragment->newlines);13571358return offset;1359}13601361static intfind_header(char*line,unsigned long size,int*hdrsize,struct patch *patch)1362{1363unsigned long offset, len;13641365 patch->is_toplevel_relative =0;1366 patch->is_rename = patch->is_copy =0;1367 patch->is_new = patch->is_delete = -1;1368 patch->old_mode = patch->new_mode =0;1369 patch->old_name = patch->new_name = NULL;1370for(offset =0; size >0; offset += len, size -= len, line += len, linenr++) {1371unsigned long nextlen;13721373 len =linelen(line, size);1374if(!len)1375break;13761377/* Testing this early allows us to take a few shortcuts.. */1378if(len <6)1379continue;13801381/*1382 * Make sure we don't find any unconnected patch fragments.1383 * That's a sign that we didn't find a header, and that a1384 * patch has become corrupted/broken up.1385 */1386if(!memcmp("@@ -", line,4)) {1387struct fragment dummy;1388if(parse_fragment_header(line, len, &dummy) <0)1389continue;1390die(_("patch fragment without header at line%d: %.*s"),1391 linenr, (int)len-1, line);1392}13931394if(size < len +6)1395break;13961397/*1398 * Git patch? It might not have a real patch, just a rename1399 * or mode change, so we handle that specially1400 */1401if(!memcmp("diff --git ", line,11)) {1402int git_hdr_len =parse_git_header(line, len, size, patch);1403if(git_hdr_len <= len)1404continue;1405if(!patch->old_name && !patch->new_name) {1406if(!patch->def_name)1407die(Q_("git diff header lacks filename information when removing "1408"%dleading pathname component (line%d)",1409"git diff header lacks filename information when removing "1410"%dleading pathname components (line%d)",1411 p_value),1412 p_value, linenr);1413 patch->old_name = patch->new_name = patch->def_name;1414}1415if(!patch->is_delete && !patch->new_name)1416die("git diff header lacks filename information "1417"(line%d)", linenr);1418 patch->is_toplevel_relative =1;1419*hdrsize = git_hdr_len;1420return offset;1421}14221423/* --- followed by +++ ? */1424if(memcmp("--- ", line,4) ||memcmp("+++ ", line + len,4))1425continue;14261427/*1428 * We only accept unified patches, so we want it to1429 * at least have "@@ -a,b +c,d @@\n", which is 14 chars1430 * minimum ("@@ -0,0 +1 @@\n" is the shortest).1431 */1432 nextlen =linelen(line + len, size - len);1433if(size < nextlen +14||memcmp("@@ -", line + len + nextlen,4))1434continue;14351436/* Ok, we'll consider it a patch */1437parse_traditional_patch(line, line+len, patch);1438*hdrsize = len + nextlen;1439 linenr +=2;1440return offset;1441}1442return-1;1443}14441445static voidrecord_ws_error(unsigned result,const char*line,int len,int linenr)1446{1447char*err;14481449if(!result)1450return;14511452 whitespace_error++;1453if(squelch_whitespace_errors &&1454 squelch_whitespace_errors < whitespace_error)1455return;14561457 err =whitespace_error_string(result);1458fprintf(stderr,"%s:%d:%s.\n%.*s\n",1459 patch_input_file, linenr, err, len, line);1460free(err);1461}14621463static voidcheck_whitespace(const char*line,int len,unsigned ws_rule)1464{1465unsigned result =ws_check(line +1, len -1, ws_rule);14661467record_ws_error(result, line +1, len -2, linenr);1468}14691470/*1471 * Parse a unified diff. Note that this really needs to parse each1472 * fragment separately, since the only way to know the difference1473 * between a "---" that is part of a patch, and a "---" that starts1474 * the next patch is to look at the line counts..1475 */1476static intparse_fragment(char*line,unsigned long size,1477struct patch *patch,struct fragment *fragment)1478{1479int added, deleted;1480int len =linelen(line, size), offset;1481unsigned long oldlines, newlines;1482unsigned long leading, trailing;14831484 offset =parse_fragment_header(line, len, fragment);1485if(offset <0)1486return-1;1487if(offset >0&& patch->recount)1488recount_diff(line + offset, size - offset, fragment);1489 oldlines = fragment->oldlines;1490 newlines = fragment->newlines;1491 leading =0;1492 trailing =0;14931494/* Parse the thing.. */1495 line += len;1496 size -= len;1497 linenr++;1498 added = deleted =0;1499for(offset = len;15000< size;1501 offset += len, size -= len, line += len, linenr++) {1502if(!oldlines && !newlines)1503break;1504 len =linelen(line, size);1505if(!len || line[len-1] !='\n')1506return-1;1507switch(*line) {1508default:1509return-1;1510case'\n':/* newer GNU diff, an empty context line */1511case' ':1512 oldlines--;1513 newlines--;1514if(!deleted && !added)1515 leading++;1516 trailing++;1517break;1518case'-':1519if(apply_in_reverse &&1520 ws_error_action != nowarn_ws_error)1521check_whitespace(line, len, patch->ws_rule);1522 deleted++;1523 oldlines--;1524 trailing =0;1525break;1526case'+':1527if(!apply_in_reverse &&1528 ws_error_action != nowarn_ws_error)1529check_whitespace(line, len, patch->ws_rule);1530 added++;1531 newlines--;1532 trailing =0;1533break;15341535/*1536 * We allow "\ No newline at end of file". Depending1537 * on locale settings when the patch was produced we1538 * don't know what this line looks like. The only1539 * thing we do know is that it begins with "\ ".1540 * Checking for 12 is just for sanity check -- any1541 * l10n of "\ No newline..." is at least that long.1542 */1543case'\\':1544if(len <12||memcmp(line,"\\",2))1545return-1;1546break;1547}1548}1549if(oldlines || newlines)1550return-1;1551 fragment->leading = leading;1552 fragment->trailing = trailing;15531554/*1555 * If a fragment ends with an incomplete line, we failed to include1556 * it in the above loop because we hit oldlines == newlines == 01557 * before seeing it.1558 */1559if(12< size && !memcmp(line,"\\",2))1560 offset +=linelen(line, size);15611562 patch->lines_added += added;1563 patch->lines_deleted += deleted;15641565if(0< patch->is_new && oldlines)1566returnerror(_("new file depends on old contents"));1567if(0< patch->is_delete && newlines)1568returnerror(_("deleted file still has contents"));1569return offset;1570}15711572static intparse_single_patch(char*line,unsigned long size,struct patch *patch)1573{1574unsigned long offset =0;1575unsigned long oldlines =0, newlines =0, context =0;1576struct fragment **fragp = &patch->fragments;15771578while(size >4&& !memcmp(line,"@@ -",4)) {1579struct fragment *fragment;1580int len;15811582 fragment =xcalloc(1,sizeof(*fragment));1583 fragment->linenr = linenr;1584 len =parse_fragment(line, size, patch, fragment);1585if(len <=0)1586die(_("corrupt patch at line%d"), linenr);1587 fragment->patch = line;1588 fragment->size = len;1589 oldlines += fragment->oldlines;1590 newlines += fragment->newlines;1591 context += fragment->leading + fragment->trailing;15921593*fragp = fragment;1594 fragp = &fragment->next;15951596 offset += len;1597 line += len;1598 size -= len;1599}16001601/*1602 * If something was removed (i.e. we have old-lines) it cannot1603 * be creation, and if something was added it cannot be1604 * deletion. However, the reverse is not true; --unified=01605 * patches that only add are not necessarily creation even1606 * though they do not have any old lines, and ones that only1607 * delete are not necessarily deletion.1608 *1609 * Unfortunately, a real creation/deletion patch do _not_ have1610 * any context line by definition, so we cannot safely tell it1611 * apart with --unified=0 insanity. At least if the patch has1612 * more than one hunk it is not creation or deletion.1613 */1614if(patch->is_new <0&&1615(oldlines || (patch->fragments && patch->fragments->next)))1616 patch->is_new =0;1617if(patch->is_delete <0&&1618(newlines || (patch->fragments && patch->fragments->next)))1619 patch->is_delete =0;16201621if(0< patch->is_new && oldlines)1622die(_("new file%sdepends on old contents"), patch->new_name);1623if(0< patch->is_delete && newlines)1624die(_("deleted file%sstill has contents"), patch->old_name);1625if(!patch->is_delete && !newlines && context)1626fprintf_ln(stderr,1627_("** warning: "1628"file%sbecomes empty but is not deleted"),1629 patch->new_name);16301631return offset;1632}16331634staticinlineintmetadata_changes(struct patch *patch)1635{1636return patch->is_rename >0||1637 patch->is_copy >0||1638 patch->is_new >0||1639 patch->is_delete ||1640(patch->old_mode && patch->new_mode &&1641 patch->old_mode != patch->new_mode);1642}16431644static char*inflate_it(const void*data,unsigned long size,1645unsigned long inflated_size)1646{1647 git_zstream stream;1648void*out;1649int st;16501651memset(&stream,0,sizeof(stream));16521653 stream.next_in = (unsigned char*)data;1654 stream.avail_in = size;1655 stream.next_out = out =xmalloc(inflated_size);1656 stream.avail_out = inflated_size;1657git_inflate_init(&stream);1658 st =git_inflate(&stream, Z_FINISH);1659git_inflate_end(&stream);1660if((st != Z_STREAM_END) || stream.total_out != inflated_size) {1661free(out);1662return NULL;1663}1664return out;1665}16661667static struct fragment *parse_binary_hunk(char**buf_p,1668unsigned long*sz_p,1669int*status_p,1670int*used_p)1671{1672/*1673 * Expect a line that begins with binary patch method ("literal"1674 * or "delta"), followed by the length of data before deflating.1675 * a sequence of 'length-byte' followed by base-85 encoded data1676 * should follow, terminated by a newline.1677 *1678 * Each 5-byte sequence of base-85 encodes up to 4 bytes,1679 * and we would limit the patch line to 66 characters,1680 * so one line can fit up to 13 groups that would decode1681 * to 52 bytes max. The length byte 'A'-'Z' corresponds1682 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.1683 */1684int llen, used;1685unsigned long size = *sz_p;1686char*buffer = *buf_p;1687int patch_method;1688unsigned long origlen;1689char*data = NULL;1690int hunk_size =0;1691struct fragment *frag;16921693 llen =linelen(buffer, size);1694 used = llen;16951696*status_p =0;16971698if(!prefixcmp(buffer,"delta ")) {1699 patch_method = BINARY_DELTA_DEFLATED;1700 origlen =strtoul(buffer +6, NULL,10);1701}1702else if(!prefixcmp(buffer,"literal ")) {1703 patch_method = BINARY_LITERAL_DEFLATED;1704 origlen =strtoul(buffer +8, NULL,10);1705}1706else1707return NULL;17081709 linenr++;1710 buffer += llen;1711while(1) {1712int byte_length, max_byte_length, newsize;1713 llen =linelen(buffer, size);1714 used += llen;1715 linenr++;1716if(llen ==1) {1717/* consume the blank line */1718 buffer++;1719 size--;1720break;1721}1722/*1723 * Minimum line is "A00000\n" which is 7-byte long,1724 * and the line length must be multiple of 5 plus 2.1725 */1726if((llen <7) || (llen-2) %5)1727goto corrupt;1728 max_byte_length = (llen -2) /5*4;1729 byte_length = *buffer;1730if('A'<= byte_length && byte_length <='Z')1731 byte_length = byte_length -'A'+1;1732else if('a'<= byte_length && byte_length <='z')1733 byte_length = byte_length -'a'+27;1734else1735goto corrupt;1736/* if the input length was not multiple of 4, we would1737 * have filler at the end but the filler should never1738 * exceed 3 bytes1739 */1740if(max_byte_length < byte_length ||1741 byte_length <= max_byte_length -4)1742goto corrupt;1743 newsize = hunk_size + byte_length;1744 data =xrealloc(data, newsize);1745if(decode_85(data + hunk_size, buffer +1, byte_length))1746goto corrupt;1747 hunk_size = newsize;1748 buffer += llen;1749 size -= llen;1750}17511752 frag =xcalloc(1,sizeof(*frag));1753 frag->patch =inflate_it(data, hunk_size, origlen);1754if(!frag->patch)1755goto corrupt;1756free(data);1757 frag->size = origlen;1758*buf_p = buffer;1759*sz_p = size;1760*used_p = used;1761 frag->binary_patch_method = patch_method;1762return frag;17631764 corrupt:1765free(data);1766*status_p = -1;1767error(_("corrupt binary patch at line%d: %.*s"),1768 linenr-1, llen-1, buffer);1769return NULL;1770}17711772static intparse_binary(char*buffer,unsigned long size,struct patch *patch)1773{1774/*1775 * We have read "GIT binary patch\n"; what follows is a line1776 * that says the patch method (currently, either "literal" or1777 * "delta") and the length of data before deflating; a1778 * sequence of 'length-byte' followed by base-85 encoded data1779 * follows.1780 *1781 * When a binary patch is reversible, there is another binary1782 * hunk in the same format, starting with patch method (either1783 * "literal" or "delta") with the length of data, and a sequence1784 * of length-byte + base-85 encoded data, terminated with another1785 * empty line. This data, when applied to the postimage, produces1786 * the preimage.1787 */1788struct fragment *forward;1789struct fragment *reverse;1790int status;1791int used, used_1;17921793 forward =parse_binary_hunk(&buffer, &size, &status, &used);1794if(!forward && !status)1795/* there has to be one hunk (forward hunk) */1796returnerror(_("unrecognized binary patch at line%d"), linenr-1);1797if(status)1798/* otherwise we already gave an error message */1799return status;18001801 reverse =parse_binary_hunk(&buffer, &size, &status, &used_1);1802if(reverse)1803 used += used_1;1804else if(status) {1805/*1806 * Not having reverse hunk is not an error, but having1807 * a corrupt reverse hunk is.1808 */1809free((void*) forward->patch);1810free(forward);1811return status;1812}1813 forward->next = reverse;1814 patch->fragments = forward;1815 patch->is_binary =1;1816return used;1817}18181819static intparse_chunk(char*buffer,unsigned long size,struct patch *patch)1820{1821int hdrsize, patchsize;1822int offset =find_header(buffer, size, &hdrsize, patch);18231824if(offset <0)1825return offset;18261827 patch->ws_rule =whitespace_rule(patch->new_name1828? patch->new_name1829: patch->old_name);18301831 patchsize =parse_single_patch(buffer + offset + hdrsize,1832 size - offset - hdrsize, patch);18331834if(!patchsize) {1835static const char*binhdr[] = {1836"Binary files ",1837"Files ",1838 NULL,1839};1840static const char git_binary[] ="GIT binary patch\n";1841int i;1842int hd = hdrsize + offset;1843unsigned long llen =linelen(buffer + hd, size - hd);18441845if(llen ==sizeof(git_binary) -1&&1846!memcmp(git_binary, buffer + hd, llen)) {1847int used;1848 linenr++;1849 used =parse_binary(buffer + hd + llen,1850 size - hd - llen, patch);1851if(used)1852 patchsize = used + llen;1853else1854 patchsize =0;1855}1856else if(!memcmp(" differ\n", buffer + hd + llen -8,8)) {1857for(i =0; binhdr[i]; i++) {1858int len =strlen(binhdr[i]);1859if(len < size - hd &&1860!memcmp(binhdr[i], buffer + hd, len)) {1861 linenr++;1862 patch->is_binary =1;1863 patchsize = llen;1864break;1865}1866}1867}18681869/* Empty patch cannot be applied if it is a text patch1870 * without metadata change. A binary patch appears1871 * empty to us here.1872 */1873if((apply || check) &&1874(!patch->is_binary && !metadata_changes(patch)))1875die(_("patch with only garbage at line%d"), linenr);1876}18771878return offset + hdrsize + patchsize;1879}18801881#define swap(a,b) myswap((a),(b),sizeof(a))18821883#define myswap(a, b, size) do { \1884 unsigned char mytmp[size]; \1885 memcpy(mytmp, &a, size); \1886 memcpy(&a, &b, size); \1887 memcpy(&b, mytmp, size); \1888} while (0)18891890static voidreverse_patches(struct patch *p)1891{1892for(; p; p = p->next) {1893struct fragment *frag = p->fragments;18941895swap(p->new_name, p->old_name);1896swap(p->new_mode, p->old_mode);1897swap(p->is_new, p->is_delete);1898swap(p->lines_added, p->lines_deleted);1899swap(p->old_sha1_prefix, p->new_sha1_prefix);19001901for(; frag; frag = frag->next) {1902swap(frag->newpos, frag->oldpos);1903swap(frag->newlines, frag->oldlines);1904}1905}1906}19071908static const char pluses[] =1909"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";1910static const char minuses[]=1911"----------------------------------------------------------------------";19121913static voidshow_stats(struct patch *patch)1914{1915struct strbuf qname = STRBUF_INIT;1916char*cp = patch->new_name ? patch->new_name : patch->old_name;1917int max, add, del;19181919quote_c_style(cp, &qname, NULL,0);19201921/*1922 * "scale" the filename1923 */1924 max = max_len;1925if(max >50)1926 max =50;19271928if(qname.len > max) {1929 cp =strchr(qname.buf + qname.len +3- max,'/');1930if(!cp)1931 cp = qname.buf + qname.len +3- max;1932strbuf_splice(&qname,0, cp - qname.buf,"...",3);1933}19341935if(patch->is_binary) {1936printf(" %-*s | Bin\n", max, qname.buf);1937strbuf_release(&qname);1938return;1939}19401941printf(" %-*s |", max, qname.buf);1942strbuf_release(&qname);19431944/*1945 * scale the add/delete1946 */1947 max = max + max_change >70?70- max : max_change;1948 add = patch->lines_added;1949 del = patch->lines_deleted;19501951if(max_change >0) {1952int total = ((add + del) * max + max_change /2) / max_change;1953 add = (add * max + max_change /2) / max_change;1954 del = total - add;1955}1956printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,1957 add, pluses, del, minuses);1958}19591960static intread_old_data(struct stat *st,const char*path,struct strbuf *buf)1961{1962switch(st->st_mode & S_IFMT) {1963case S_IFLNK:1964if(strbuf_readlink(buf, path, st->st_size) <0)1965returnerror(_("unable to read symlink%s"), path);1966return0;1967case S_IFREG:1968if(strbuf_read_file(buf, path, st->st_size) != st->st_size)1969returnerror(_("unable to open or read%s"), path);1970convert_to_git(path, buf->buf, buf->len, buf,0);1971return0;1972default:1973return-1;1974}1975}19761977/*1978 * Update the preimage, and the common lines in postimage,1979 * from buffer buf of length len. If postlen is 0 the postimage1980 * is updated in place, otherwise it's updated on a new buffer1981 * of length postlen1982 */19831984static voidupdate_pre_post_images(struct image *preimage,1985struct image *postimage,1986char*buf,1987size_t len,size_t postlen)1988{1989int i, ctx;1990char*new, *old, *fixed;1991struct image fixed_preimage;19921993/*1994 * Update the preimage with whitespace fixes. Note that we1995 * are not losing preimage->buf -- apply_one_fragment() will1996 * free "oldlines".1997 */1998prepare_image(&fixed_preimage, buf, len,1);1999assert(fixed_preimage.nr == preimage->nr);2000for(i =0; i < preimage->nr; i++)2001 fixed_preimage.line[i].flag = preimage->line[i].flag;2002free(preimage->line_allocated);2003*preimage = fixed_preimage;20042005/*2006 * Adjust the common context lines in postimage. This can be2007 * done in-place when we are just doing whitespace fixing,2008 * which does not make the string grow, but needs a new buffer2009 * when ignoring whitespace causes the update, since in this case2010 * we could have e.g. tabs converted to multiple spaces.2011 * We trust the caller to tell us if the update can be done2012 * in place (postlen==0) or not.2013 */2014 old = postimage->buf;2015if(postlen)2016new= postimage->buf =xmalloc(postlen);2017else2018new= old;2019 fixed = preimage->buf;2020for(i = ctx =0; i < postimage->nr; i++) {2021size_t len = postimage->line[i].len;2022if(!(postimage->line[i].flag & LINE_COMMON)) {2023/* an added line -- no counterparts in preimage */2024memmove(new, old, len);2025 old += len;2026new+= len;2027continue;2028}20292030/* a common context -- skip it in the original postimage */2031 old += len;20322033/* and find the corresponding one in the fixed preimage */2034while(ctx < preimage->nr &&2035!(preimage->line[ctx].flag & LINE_COMMON)) {2036 fixed += preimage->line[ctx].len;2037 ctx++;2038}2039if(preimage->nr <= ctx)2040die(_("oops"));20412042/* and copy it in, while fixing the line length */2043 len = preimage->line[ctx].len;2044memcpy(new, fixed, len);2045new+= len;2046 fixed += len;2047 postimage->line[i].len = len;2048 ctx++;2049}20502051/* Fix the length of the whole thing */2052 postimage->len =new- postimage->buf;2053}20542055static intmatch_fragment(struct image *img,2056struct image *preimage,2057struct image *postimage,2058unsigned longtry,2059int try_lno,2060unsigned ws_rule,2061int match_beginning,int match_end)2062{2063int i;2064char*fixed_buf, *buf, *orig, *target;2065struct strbuf fixed;2066size_t fixed_len;2067int preimage_limit;20682069if(preimage->nr + try_lno <= img->nr) {2070/*2071 * The hunk falls within the boundaries of img.2072 */2073 preimage_limit = preimage->nr;2074if(match_end && (preimage->nr + try_lno != img->nr))2075return0;2076}else if(ws_error_action == correct_ws_error &&2077(ws_rule & WS_BLANK_AT_EOF)) {2078/*2079 * This hunk extends beyond the end of img, and we are2080 * removing blank lines at the end of the file. This2081 * many lines from the beginning of the preimage must2082 * match with img, and the remainder of the preimage2083 * must be blank.2084 */2085 preimage_limit = img->nr - try_lno;2086}else{2087/*2088 * The hunk extends beyond the end of the img and2089 * we are not removing blanks at the end, so we2090 * should reject the hunk at this position.2091 */2092return0;2093}20942095if(match_beginning && try_lno)2096return0;20972098/* Quick hash check */2099for(i =0; i < preimage_limit; i++)2100if((img->line[try_lno + i].flag & LINE_PATCHED) ||2101(preimage->line[i].hash != img->line[try_lno + i].hash))2102return0;21032104if(preimage_limit == preimage->nr) {2105/*2106 * Do we have an exact match? If we were told to match2107 * at the end, size must be exactly at try+fragsize,2108 * otherwise try+fragsize must be still within the preimage,2109 * and either case, the old piece should match the preimage2110 * exactly.2111 */2112if((match_end2113? (try+ preimage->len == img->len)2114: (try+ preimage->len <= img->len)) &&2115!memcmp(img->buf +try, preimage->buf, preimage->len))2116return1;2117}else{2118/*2119 * The preimage extends beyond the end of img, so2120 * there cannot be an exact match.2121 *2122 * There must be one non-blank context line that match2123 * a line before the end of img.2124 */2125char*buf_end;21262127 buf = preimage->buf;2128 buf_end = buf;2129for(i =0; i < preimage_limit; i++)2130 buf_end += preimage->line[i].len;21312132for( ; buf < buf_end; buf++)2133if(!isspace(*buf))2134break;2135if(buf == buf_end)2136return0;2137}21382139/*2140 * No exact match. If we are ignoring whitespace, run a line-by-line2141 * fuzzy matching. We collect all the line length information because2142 * we need it to adjust whitespace if we match.2143 */2144if(ws_ignore_action == ignore_ws_change) {2145size_t imgoff =0;2146size_t preoff =0;2147size_t postlen = postimage->len;2148size_t extra_chars;2149char*preimage_eof;2150char*preimage_end;2151for(i =0; i < preimage_limit; i++) {2152size_t prelen = preimage->line[i].len;2153size_t imglen = img->line[try_lno+i].len;21542155if(!fuzzy_matchlines(img->buf +try+ imgoff, imglen,2156 preimage->buf + preoff, prelen))2157return0;2158if(preimage->line[i].flag & LINE_COMMON)2159 postlen += imglen - prelen;2160 imgoff += imglen;2161 preoff += prelen;2162}21632164/*2165 * Ok, the preimage matches with whitespace fuzz.2166 *2167 * imgoff now holds the true length of the target that2168 * matches the preimage before the end of the file.2169 *2170 * Count the number of characters in the preimage that fall2171 * beyond the end of the file and make sure that all of them2172 * are whitespace characters. (This can only happen if2173 * we are removing blank lines at the end of the file.)2174 */2175 buf = preimage_eof = preimage->buf + preoff;2176for( ; i < preimage->nr; i++)2177 preoff += preimage->line[i].len;2178 preimage_end = preimage->buf + preoff;2179for( ; buf < preimage_end; buf++)2180if(!isspace(*buf))2181return0;21822183/*2184 * Update the preimage and the common postimage context2185 * lines to use the same whitespace as the target.2186 * If whitespace is missing in the target (i.e.2187 * if the preimage extends beyond the end of the file),2188 * use the whitespace from the preimage.2189 */2190 extra_chars = preimage_end - preimage_eof;2191strbuf_init(&fixed, imgoff + extra_chars);2192strbuf_add(&fixed, img->buf +try, imgoff);2193strbuf_add(&fixed, preimage_eof, extra_chars);2194 fixed_buf =strbuf_detach(&fixed, &fixed_len);2195update_pre_post_images(preimage, postimage,2196 fixed_buf, fixed_len, postlen);2197return1;2198}21992200if(ws_error_action != correct_ws_error)2201return0;22022203/*2204 * The hunk does not apply byte-by-byte, but the hash says2205 * it might with whitespace fuzz. We haven't been asked to2206 * ignore whitespace, we were asked to correct whitespace2207 * errors, so let's try matching after whitespace correction.2208 *2209 * The preimage may extend beyond the end of the file,2210 * but in this loop we will only handle the part of the2211 * preimage that falls within the file.2212 */2213strbuf_init(&fixed, preimage->len +1);2214 orig = preimage->buf;2215 target = img->buf +try;2216for(i =0; i < preimage_limit; i++) {2217size_t oldlen = preimage->line[i].len;2218size_t tgtlen = img->line[try_lno + i].len;2219size_t fixstart = fixed.len;2220struct strbuf tgtfix;2221int match;22222223/* Try fixing the line in the preimage */2224ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);22252226/* Try fixing the line in the target */2227strbuf_init(&tgtfix, tgtlen);2228ws_fix_copy(&tgtfix, target, tgtlen, ws_rule, NULL);22292230/*2231 * If they match, either the preimage was based on2232 * a version before our tree fixed whitespace breakage,2233 * or we are lacking a whitespace-fix patch the tree2234 * the preimage was based on already had (i.e. target2235 * has whitespace breakage, the preimage doesn't).2236 * In either case, we are fixing the whitespace breakages2237 * so we might as well take the fix together with their2238 * real change.2239 */2240 match = (tgtfix.len == fixed.len - fixstart &&2241!memcmp(tgtfix.buf, fixed.buf + fixstart,2242 fixed.len - fixstart));22432244strbuf_release(&tgtfix);2245if(!match)2246goto unmatch_exit;22472248 orig += oldlen;2249 target += tgtlen;2250}225122522253/*2254 * Now handle the lines in the preimage that falls beyond the2255 * end of the file (if any). They will only match if they are2256 * empty or only contain whitespace (if WS_BLANK_AT_EOL is2257 * false).2258 */2259for( ; i < preimage->nr; i++) {2260size_t fixstart = fixed.len;/* start of the fixed preimage */2261size_t oldlen = preimage->line[i].len;2262int j;22632264/* Try fixing the line in the preimage */2265ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);22662267for(j = fixstart; j < fixed.len; j++)2268if(!isspace(fixed.buf[j]))2269goto unmatch_exit;22702271 orig += oldlen;2272}22732274/*2275 * Yes, the preimage is based on an older version that still2276 * has whitespace breakages unfixed, and fixing them makes the2277 * hunk match. Update the context lines in the postimage.2278 */2279 fixed_buf =strbuf_detach(&fixed, &fixed_len);2280update_pre_post_images(preimage, postimage,2281 fixed_buf, fixed_len,0);2282return1;22832284 unmatch_exit:2285strbuf_release(&fixed);2286return0;2287}22882289static intfind_pos(struct image *img,2290struct image *preimage,2291struct image *postimage,2292int line,2293unsigned ws_rule,2294int match_beginning,int match_end)2295{2296int i;2297unsigned long backwards, forwards,try;2298int backwards_lno, forwards_lno, try_lno;22992300/*2301 * If match_beginning or match_end is specified, there is no2302 * point starting from a wrong line that will never match and2303 * wander around and wait for a match at the specified end.2304 */2305if(match_beginning)2306 line =0;2307else if(match_end)2308 line = img->nr - preimage->nr;23092310/*2311 * Because the comparison is unsigned, the following test2312 * will also take care of a negative line number that can2313 * result when match_end and preimage is larger than the target.2314 */2315if((size_t) line > img->nr)2316 line = img->nr;23172318try=0;2319for(i =0; i < line; i++)2320try+= img->line[i].len;23212322/*2323 * There's probably some smart way to do this, but I'll leave2324 * that to the smart and beautiful people. I'm simple and stupid.2325 */2326 backwards =try;2327 backwards_lno = line;2328 forwards =try;2329 forwards_lno = line;2330 try_lno = line;23312332for(i =0; ; i++) {2333if(match_fragment(img, preimage, postimage,2334try, try_lno, ws_rule,2335 match_beginning, match_end))2336return try_lno;23372338 again:2339if(backwards_lno ==0&& forwards_lno == img->nr)2340break;23412342if(i &1) {2343if(backwards_lno ==0) {2344 i++;2345goto again;2346}2347 backwards_lno--;2348 backwards -= img->line[backwards_lno].len;2349try= backwards;2350 try_lno = backwards_lno;2351}else{2352if(forwards_lno == img->nr) {2353 i++;2354goto again;2355}2356 forwards += img->line[forwards_lno].len;2357 forwards_lno++;2358try= forwards;2359 try_lno = forwards_lno;2360}23612362}2363return-1;2364}23652366static voidremove_first_line(struct image *img)2367{2368 img->buf += img->line[0].len;2369 img->len -= img->line[0].len;2370 img->line++;2371 img->nr--;2372}23732374static voidremove_last_line(struct image *img)2375{2376 img->len -= img->line[--img->nr].len;2377}23782379static voidupdate_image(struct image *img,2380int applied_pos,2381struct image *preimage,2382struct image *postimage)2383{2384/*2385 * remove the copy of preimage at offset in img2386 * and replace it with postimage2387 */2388int i, nr;2389size_t remove_count, insert_count, applied_at =0;2390char*result;2391int preimage_limit;23922393/*2394 * If we are removing blank lines at the end of img,2395 * the preimage may extend beyond the end.2396 * If that is the case, we must be careful only to2397 * remove the part of the preimage that falls within2398 * the boundaries of img. Initialize preimage_limit2399 * to the number of lines in the preimage that falls2400 * within the boundaries.2401 */2402 preimage_limit = preimage->nr;2403if(preimage_limit > img->nr - applied_pos)2404 preimage_limit = img->nr - applied_pos;24052406for(i =0; i < applied_pos; i++)2407 applied_at += img->line[i].len;24082409 remove_count =0;2410for(i =0; i < preimage_limit; i++)2411 remove_count += img->line[applied_pos + i].len;2412 insert_count = postimage->len;24132414/* Adjust the contents */2415 result =xmalloc(img->len + insert_count - remove_count +1);2416memcpy(result, img->buf, applied_at);2417memcpy(result + applied_at, postimage->buf, postimage->len);2418memcpy(result + applied_at + postimage->len,2419 img->buf + (applied_at + remove_count),2420 img->len - (applied_at + remove_count));2421free(img->buf);2422 img->buf = result;2423 img->len += insert_count - remove_count;2424 result[img->len] ='\0';24252426/* Adjust the line table */2427 nr = img->nr + postimage->nr - preimage_limit;2428if(preimage_limit < postimage->nr) {2429/*2430 * NOTE: this knows that we never call remove_first_line()2431 * on anything other than pre/post image.2432 */2433 img->line =xrealloc(img->line, nr *sizeof(*img->line));2434 img->line_allocated = img->line;2435}2436if(preimage_limit != postimage->nr)2437memmove(img->line + applied_pos + postimage->nr,2438 img->line + applied_pos + preimage_limit,2439(img->nr - (applied_pos + preimage_limit)) *2440sizeof(*img->line));2441memcpy(img->line + applied_pos,2442 postimage->line,2443 postimage->nr *sizeof(*img->line));2444if(!allow_overlap)2445for(i =0; i < postimage->nr; i++)2446 img->line[applied_pos + i].flag |= LINE_PATCHED;2447 img->nr = nr;2448}24492450static intapply_one_fragment(struct image *img,struct fragment *frag,2451int inaccurate_eof,unsigned ws_rule,2452int nth_fragment)2453{2454int match_beginning, match_end;2455const char*patch = frag->patch;2456int size = frag->size;2457char*old, *oldlines;2458struct strbuf newlines;2459int new_blank_lines_at_end =0;2460int found_new_blank_lines_at_end =0;2461int hunk_linenr = frag->linenr;2462unsigned long leading, trailing;2463int pos, applied_pos;2464struct image preimage;2465struct image postimage;24662467memset(&preimage,0,sizeof(preimage));2468memset(&postimage,0,sizeof(postimage));2469 oldlines =xmalloc(size);2470strbuf_init(&newlines, size);24712472 old = oldlines;2473while(size >0) {2474char first;2475int len =linelen(patch, size);2476int plen;2477int added_blank_line =0;2478int is_blank_context =0;2479size_t start;24802481if(!len)2482break;24832484/*2485 * "plen" is how much of the line we should use for2486 * the actual patch data. Normally we just remove the2487 * first character on the line, but if the line is2488 * followed by "\ No newline", then we also remove the2489 * last one (which is the newline, of course).2490 */2491 plen = len -1;2492if(len < size && patch[len] =='\\')2493 plen--;2494 first = *patch;2495if(apply_in_reverse) {2496if(first =='-')2497 first ='+';2498else if(first =='+')2499 first ='-';2500}25012502switch(first) {2503case'\n':2504/* Newer GNU diff, empty context line */2505if(plen <0)2506/* ... followed by '\No newline'; nothing */2507break;2508*old++ ='\n';2509strbuf_addch(&newlines,'\n');2510add_line_info(&preimage,"\n",1, LINE_COMMON);2511add_line_info(&postimage,"\n",1, LINE_COMMON);2512 is_blank_context =1;2513break;2514case' ':2515if(plen && (ws_rule & WS_BLANK_AT_EOF) &&2516ws_blank_line(patch +1, plen, ws_rule))2517 is_blank_context =1;2518case'-':2519memcpy(old, patch +1, plen);2520add_line_info(&preimage, old, plen,2521(first ==' '? LINE_COMMON :0));2522 old += plen;2523if(first =='-')2524break;2525/* Fall-through for ' ' */2526case'+':2527/* --no-add does not add new lines */2528if(first =='+'&& no_add)2529break;25302531 start = newlines.len;2532if(first !='+'||2533!whitespace_error ||2534 ws_error_action != correct_ws_error) {2535strbuf_add(&newlines, patch +1, plen);2536}2537else{2538ws_fix_copy(&newlines, patch +1, plen, ws_rule, &applied_after_fixing_ws);2539}2540add_line_info(&postimage, newlines.buf + start, newlines.len - start,2541(first =='+'?0: LINE_COMMON));2542if(first =='+'&&2543(ws_rule & WS_BLANK_AT_EOF) &&2544ws_blank_line(patch +1, plen, ws_rule))2545 added_blank_line =1;2546break;2547case'@':case'\\':2548/* Ignore it, we already handled it */2549break;2550default:2551if(apply_verbosely)2552error(_("invalid start of line: '%c'"), first);2553return-1;2554}2555if(added_blank_line) {2556if(!new_blank_lines_at_end)2557 found_new_blank_lines_at_end = hunk_linenr;2558 new_blank_lines_at_end++;2559}2560else if(is_blank_context)2561;2562else2563 new_blank_lines_at_end =0;2564 patch += len;2565 size -= len;2566 hunk_linenr++;2567}2568if(inaccurate_eof &&2569 old > oldlines && old[-1] =='\n'&&2570 newlines.len >0&& newlines.buf[newlines.len -1] =='\n') {2571 old--;2572strbuf_setlen(&newlines, newlines.len -1);2573}25742575 leading = frag->leading;2576 trailing = frag->trailing;25772578/*2579 * A hunk to change lines at the beginning would begin with2580 * @@ -1,L +N,M @@2581 * but we need to be careful. -U0 that inserts before the second2582 * line also has this pattern.2583 *2584 * And a hunk to add to an empty file would begin with2585 * @@ -0,0 +N,M @@2586 *2587 * In other words, a hunk that is (frag->oldpos <= 1) with or2588 * without leading context must match at the beginning.2589 */2590 match_beginning = (!frag->oldpos ||2591(frag->oldpos ==1&& !unidiff_zero));25922593/*2594 * A hunk without trailing lines must match at the end.2595 * However, we simply cannot tell if a hunk must match end2596 * from the lack of trailing lines if the patch was generated2597 * with unidiff without any context.2598 */2599 match_end = !unidiff_zero && !trailing;26002601 pos = frag->newpos ? (frag->newpos -1) :0;2602 preimage.buf = oldlines;2603 preimage.len = old - oldlines;2604 postimage.buf = newlines.buf;2605 postimage.len = newlines.len;2606 preimage.line = preimage.line_allocated;2607 postimage.line = postimage.line_allocated;26082609for(;;) {26102611 applied_pos =find_pos(img, &preimage, &postimage, pos,2612 ws_rule, match_beginning, match_end);26132614if(applied_pos >=0)2615break;26162617/* Am I at my context limits? */2618if((leading <= p_context) && (trailing <= p_context))2619break;2620if(match_beginning || match_end) {2621 match_beginning = match_end =0;2622continue;2623}26242625/*2626 * Reduce the number of context lines; reduce both2627 * leading and trailing if they are equal otherwise2628 * just reduce the larger context.2629 */2630if(leading >= trailing) {2631remove_first_line(&preimage);2632remove_first_line(&postimage);2633 pos--;2634 leading--;2635}2636if(trailing > leading) {2637remove_last_line(&preimage);2638remove_last_line(&postimage);2639 trailing--;2640}2641}26422643if(applied_pos >=0) {2644if(new_blank_lines_at_end &&2645 preimage.nr + applied_pos >= img->nr &&2646(ws_rule & WS_BLANK_AT_EOF) &&2647 ws_error_action != nowarn_ws_error) {2648record_ws_error(WS_BLANK_AT_EOF,"+",1,2649 found_new_blank_lines_at_end);2650if(ws_error_action == correct_ws_error) {2651while(new_blank_lines_at_end--)2652remove_last_line(&postimage);2653}2654/*2655 * We would want to prevent write_out_results()2656 * from taking place in apply_patch() that follows2657 * the callchain led us here, which is:2658 * apply_patch->check_patch_list->check_patch->2659 * apply_data->apply_fragments->apply_one_fragment2660 */2661if(ws_error_action == die_on_ws_error)2662 apply =0;2663}26642665if(apply_verbosely && applied_pos != pos) {2666int offset = applied_pos - pos;2667if(apply_in_reverse)2668 offset =0- offset;2669fprintf_ln(stderr,2670Q_("Hunk #%dsucceeded at%d(offset%dline).",2671"Hunk #%dsucceeded at%d(offset%dlines).",2672 offset),2673 nth_fragment, applied_pos +1, offset);2674}26752676/*2677 * Warn if it was necessary to reduce the number2678 * of context lines.2679 */2680if((leading != frag->leading) ||2681(trailing != frag->trailing))2682fprintf_ln(stderr,_("Context reduced to (%ld/%ld)"2683" to apply fragment at%d"),2684 leading, trailing, applied_pos+1);2685update_image(img, applied_pos, &preimage, &postimage);2686}else{2687if(apply_verbosely)2688error(_("while searching for:\n%.*s"),2689(int)(old - oldlines), oldlines);2690}26912692free(oldlines);2693strbuf_release(&newlines);2694free(preimage.line_allocated);2695free(postimage.line_allocated);26962697return(applied_pos <0);2698}26992700static intapply_binary_fragment(struct image *img,struct patch *patch)2701{2702struct fragment *fragment = patch->fragments;2703unsigned long len;2704void*dst;27052706if(!fragment)2707returnerror(_("missing binary patch data for '%s'"),2708 patch->new_name ?2709 patch->new_name :2710 patch->old_name);27112712/* Binary patch is irreversible without the optional second hunk */2713if(apply_in_reverse) {2714if(!fragment->next)2715returnerror("cannot reverse-apply a binary patch "2716"without the reverse hunk to '%s'",2717 patch->new_name2718? patch->new_name : patch->old_name);2719 fragment = fragment->next;2720}2721switch(fragment->binary_patch_method) {2722case BINARY_DELTA_DEFLATED:2723 dst =patch_delta(img->buf, img->len, fragment->patch,2724 fragment->size, &len);2725if(!dst)2726return-1;2727clear_image(img);2728 img->buf = dst;2729 img->len = len;2730return0;2731case BINARY_LITERAL_DEFLATED:2732clear_image(img);2733 img->len = fragment->size;2734 img->buf =xmalloc(img->len+1);2735memcpy(img->buf, fragment->patch, img->len);2736 img->buf[img->len] ='\0';2737return0;2738}2739return-1;2740}27412742static intapply_binary(struct image *img,struct patch *patch)2743{2744const char*name = patch->old_name ? patch->old_name : patch->new_name;2745unsigned char sha1[20];27462747/*2748 * For safety, we require patch index line to contain2749 * full 40-byte textual SHA1 for old and new, at least for now.2750 */2751if(strlen(patch->old_sha1_prefix) !=40||2752strlen(patch->new_sha1_prefix) !=40||2753get_sha1_hex(patch->old_sha1_prefix, sha1) ||2754get_sha1_hex(patch->new_sha1_prefix, sha1))2755returnerror("cannot apply binary patch to '%s' "2756"without full index line", name);27572758if(patch->old_name) {2759/*2760 * See if the old one matches what the patch2761 * applies to.2762 */2763hash_sha1_file(img->buf, img->len, blob_type, sha1);2764if(strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))2765returnerror("the patch applies to '%s' (%s), "2766"which does not match the "2767"current contents.",2768 name,sha1_to_hex(sha1));2769}2770else{2771/* Otherwise, the old one must be empty. */2772if(img->len)2773returnerror("the patch applies to an empty "2774"'%s' but it is not empty", name);2775}27762777get_sha1_hex(patch->new_sha1_prefix, sha1);2778if(is_null_sha1(sha1)) {2779clear_image(img);2780return0;/* deletion patch */2781}27822783if(has_sha1_file(sha1)) {2784/* We already have the postimage */2785enum object_type type;2786unsigned long size;2787char*result;27882789 result =read_sha1_file(sha1, &type, &size);2790if(!result)2791returnerror("the necessary postimage%sfor "2792"'%s' cannot be read",2793 patch->new_sha1_prefix, name);2794clear_image(img);2795 img->buf = result;2796 img->len = size;2797}else{2798/*2799 * We have verified buf matches the preimage;2800 * apply the patch data to it, which is stored2801 * in the patch->fragments->{patch,size}.2802 */2803if(apply_binary_fragment(img, patch))2804returnerror(_("binary patch does not apply to '%s'"),2805 name);28062807/* verify that the result matches */2808hash_sha1_file(img->buf, img->len, blob_type, sha1);2809if(strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))2810returnerror(_("binary patch to '%s' creates incorrect result (expecting%s, got%s)"),2811 name, patch->new_sha1_prefix,sha1_to_hex(sha1));2812}28132814return0;2815}28162817static intapply_fragments(struct image *img,struct patch *patch)2818{2819struct fragment *frag = patch->fragments;2820const char*name = patch->old_name ? patch->old_name : patch->new_name;2821unsigned ws_rule = patch->ws_rule;2822unsigned inaccurate_eof = patch->inaccurate_eof;2823int nth =0;28242825if(patch->is_binary)2826returnapply_binary(img, patch);28272828while(frag) {2829 nth++;2830if(apply_one_fragment(img, frag, inaccurate_eof, ws_rule, nth)) {2831error(_("patch failed:%s:%ld"), name, frag->oldpos);2832if(!apply_with_reject)2833return-1;2834 frag->rejected =1;2835}2836 frag = frag->next;2837}2838return0;2839}28402841static intread_file_or_gitlink(struct cache_entry *ce,struct strbuf *buf)2842{2843if(!ce)2844return0;28452846if(S_ISGITLINK(ce->ce_mode)) {2847strbuf_grow(buf,100);2848strbuf_addf(buf,"Subproject commit%s\n",sha1_to_hex(ce->sha1));2849}else{2850enum object_type type;2851unsigned long sz;2852char*result;28532854 result =read_sha1_file(ce->sha1, &type, &sz);2855if(!result)2856return-1;2857/* XXX read_sha1_file NUL-terminates */2858strbuf_attach(buf, result, sz, sz +1);2859}2860return0;2861}28622863static struct patch *in_fn_table(const char*name)2864{2865struct string_list_item *item;28662867if(name == NULL)2868return NULL;28692870 item =string_list_lookup(&fn_table, name);2871if(item != NULL)2872return(struct patch *)item->util;28732874return NULL;2875}28762877/*2878 * item->util in the filename table records the status of the path.2879 * Usually it points at a patch (whose result records the contents2880 * of it after applying it), but it could be PATH_WAS_DELETED for a2881 * path that a previously applied patch has already removed.2882 */2883#define PATH_TO_BE_DELETED ((struct patch *) -2)2884#define PATH_WAS_DELETED ((struct patch *) -1)28852886static intto_be_deleted(struct patch *patch)2887{2888return patch == PATH_TO_BE_DELETED;2889}28902891static intwas_deleted(struct patch *patch)2892{2893return patch == PATH_WAS_DELETED;2894}28952896static voidadd_to_fn_table(struct patch *patch)2897{2898struct string_list_item *item;28992900/*2901 * Always add new_name unless patch is a deletion2902 * This should cover the cases for normal diffs,2903 * file creations and copies2904 */2905if(patch->new_name != NULL) {2906 item =string_list_insert(&fn_table, patch->new_name);2907 item->util = patch;2908}29092910/*2911 * store a failure on rename/deletion cases because2912 * later chunks shouldn't patch old names2913 */2914if((patch->new_name == NULL) || (patch->is_rename)) {2915 item =string_list_insert(&fn_table, patch->old_name);2916 item->util = PATH_WAS_DELETED;2917}2918}29192920static voidprepare_fn_table(struct patch *patch)2921{2922/*2923 * store information about incoming file deletion2924 */2925while(patch) {2926if((patch->new_name == NULL) || (patch->is_rename)) {2927struct string_list_item *item;2928 item =string_list_insert(&fn_table, patch->old_name);2929 item->util = PATH_TO_BE_DELETED;2930}2931 patch = patch->next;2932}2933}29342935static intapply_data(struct patch *patch,struct stat *st,struct cache_entry *ce)2936{2937struct strbuf buf = STRBUF_INIT;2938struct image image;2939size_t len;2940char*img;2941struct patch *tpatch;29422943if(!(patch->is_copy || patch->is_rename) &&2944(tpatch =in_fn_table(patch->old_name)) != NULL && !to_be_deleted(tpatch)) {2945if(was_deleted(tpatch)) {2946returnerror(_("patch%shas been renamed/deleted"),2947 patch->old_name);2948}2949/* We have a patched copy in memory use that */2950strbuf_add(&buf, tpatch->result, tpatch->resultsize);2951}else if(cached) {2952if(read_file_or_gitlink(ce, &buf))2953returnerror(_("read of%sfailed"), patch->old_name);2954}else if(patch->old_name) {2955if(S_ISGITLINK(patch->old_mode)) {2956if(ce) {2957read_file_or_gitlink(ce, &buf);2958}else{2959/*2960 * There is no way to apply subproject2961 * patch without looking at the index.2962 */2963 patch->fragments = NULL;2964}2965}else{2966if(read_old_data(st, patch->old_name, &buf))2967returnerror(_("read of%sfailed"), patch->old_name);2968}2969}29702971 img =strbuf_detach(&buf, &len);2972prepare_image(&image, img, len, !patch->is_binary);29732974if(apply_fragments(&image, patch) <0)2975return-1;/* note with --reject this succeeds. */2976 patch->result = image.buf;2977 patch->resultsize = image.len;2978add_to_fn_table(patch);2979free(image.line_allocated);29802981if(0< patch->is_delete && patch->resultsize)2982returnerror(_("removal patch leaves file contents"));29832984return0;2985}29862987static intcheck_to_create_blob(const char*new_name,int ok_if_exists)2988{2989struct stat nst;2990if(!lstat(new_name, &nst)) {2991if(S_ISDIR(nst.st_mode) || ok_if_exists)2992return0;2993/*2994 * A leading component of new_name might be a symlink2995 * that is going to be removed with this patch, but2996 * still pointing at somewhere that has the path.2997 * In such a case, path "new_name" does not exist as2998 * far as git is concerned.2999 */3000if(has_symlink_leading_path(new_name,strlen(new_name)))3001return0;30023003returnerror(_("%s: already exists in working directory"), new_name);3004}3005else if((errno != ENOENT) && (errno != ENOTDIR))3006returnerror("%s:%s", new_name,strerror(errno));3007return0;3008}30093010static intverify_index_match(struct cache_entry *ce,struct stat *st)3011{3012if(S_ISGITLINK(ce->ce_mode)) {3013if(!S_ISDIR(st->st_mode))3014return-1;3015return0;3016}3017returnce_match_stat(ce, st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE);3018}30193020static intcheck_preimage(struct patch *patch,struct cache_entry **ce,struct stat *st)3021{3022const char*old_name = patch->old_name;3023struct patch *tpatch = NULL;3024int stat_ret =0;3025unsigned st_mode =0;30263027/*3028 * Make sure that we do not have local modifications from the3029 * index when we are looking at the index. Also make sure3030 * we have the preimage file to be patched in the work tree,3031 * unless --cached, which tells git to apply only in the index.3032 */3033if(!old_name)3034return0;30353036assert(patch->is_new <=0);30373038if(!(patch->is_copy || patch->is_rename) &&3039(tpatch =in_fn_table(old_name)) != NULL && !to_be_deleted(tpatch)) {3040if(was_deleted(tpatch))3041returnerror(_("%s: has been deleted/renamed"), old_name);3042 st_mode = tpatch->new_mode;3043}else if(!cached) {3044 stat_ret =lstat(old_name, st);3045if(stat_ret && errno != ENOENT)3046returnerror(_("%s:%s"), old_name,strerror(errno));3047}30483049if(to_be_deleted(tpatch))3050 tpatch = NULL;30513052if(check_index && !tpatch) {3053int pos =cache_name_pos(old_name,strlen(old_name));3054if(pos <0) {3055if(patch->is_new <0)3056goto is_new;3057returnerror(_("%s: does not exist in index"), old_name);3058}3059*ce = active_cache[pos];3060if(stat_ret <0) {3061struct checkout costate;3062/* checkout */3063memset(&costate,0,sizeof(costate));3064 costate.base_dir ="";3065 costate.refresh_cache =1;3066if(checkout_entry(*ce, &costate, NULL) ||3067lstat(old_name, st))3068return-1;3069}3070if(!cached &&verify_index_match(*ce, st))3071returnerror(_("%s: does not match index"), old_name);3072if(cached)3073 st_mode = (*ce)->ce_mode;3074}else if(stat_ret <0) {3075if(patch->is_new <0)3076goto is_new;3077returnerror(_("%s:%s"), old_name,strerror(errno));3078}30793080if(!cached && !tpatch)3081 st_mode =ce_mode_from_stat(*ce, st->st_mode);30823083if(patch->is_new <0)3084 patch->is_new =0;3085if(!patch->old_mode)3086 patch->old_mode = st_mode;3087if((st_mode ^ patch->old_mode) & S_IFMT)3088returnerror(_("%s: wrong type"), old_name);3089if(st_mode != patch->old_mode)3090warning(_("%shas type%o, expected%o"),3091 old_name, st_mode, patch->old_mode);3092if(!patch->new_mode && !patch->is_delete)3093 patch->new_mode = st_mode;3094return0;30953096 is_new:3097 patch->is_new =1;3098 patch->is_delete =0;3099 patch->old_name = NULL;3100return0;3101}31023103static intcheck_patch(struct patch *patch)3104{3105struct stat st;3106const char*old_name = patch->old_name;3107const char*new_name = patch->new_name;3108const char*name = old_name ? old_name : new_name;3109struct cache_entry *ce = NULL;3110struct patch *tpatch;3111int ok_if_exists;3112int status;31133114 patch->rejected =1;/* we will drop this after we succeed */31153116 status =check_preimage(patch, &ce, &st);3117if(status)3118return status;3119 old_name = patch->old_name;31203121if((tpatch =in_fn_table(new_name)) &&3122(was_deleted(tpatch) ||to_be_deleted(tpatch)))3123/*3124 * A type-change diff is always split into a patch to3125 * delete old, immediately followed by a patch to3126 * create new (see diff.c::run_diff()); in such a case3127 * it is Ok that the entry to be deleted by the3128 * previous patch is still in the working tree and in3129 * the index.3130 */3131 ok_if_exists =1;3132else3133 ok_if_exists =0;31343135if(new_name &&3136((0< patch->is_new) | (0< patch->is_rename) | patch->is_copy)) {3137if(check_index &&3138cache_name_pos(new_name,strlen(new_name)) >=0&&3139!ok_if_exists)3140returnerror(_("%s: already exists in index"), new_name);3141if(!cached) {3142int err =check_to_create_blob(new_name, ok_if_exists);3143if(err)3144return err;3145}3146if(!patch->new_mode) {3147if(0< patch->is_new)3148 patch->new_mode = S_IFREG |0644;3149else3150 patch->new_mode = patch->old_mode;3151}3152}31533154if(new_name && old_name) {3155int same = !strcmp(old_name, new_name);3156if(!patch->new_mode)3157 patch->new_mode = patch->old_mode;3158if((patch->old_mode ^ patch->new_mode) & S_IFMT)3159returnerror(_("new mode (%o) of%sdoes not match old mode (%o)%s%s"),3160 patch->new_mode, new_name, patch->old_mode,3161 same ?"":" of ", same ?"": old_name);3162}31633164if(apply_data(patch, &st, ce) <0)3165returnerror(_("%s: patch does not apply"), name);3166 patch->rejected =0;3167return0;3168}31693170static intcheck_patch_list(struct patch *patch)3171{3172int err =0;31733174prepare_fn_table(patch);3175while(patch) {3176if(apply_verbosely)3177say_patch_name(stderr,3178_("Checking patch%s..."), patch);3179 err |=check_patch(patch);3180 patch = patch->next;3181}3182return err;3183}31843185/* This function tries to read the sha1 from the current index */3186static intget_current_sha1(const char*path,unsigned char*sha1)3187{3188int pos;31893190if(read_cache() <0)3191return-1;3192 pos =cache_name_pos(path,strlen(path));3193if(pos <0)3194return-1;3195hashcpy(sha1, active_cache[pos]->sha1);3196return0;3197}31983199/* Build an index that contains the just the files needed for a 3way merge */3200static voidbuild_fake_ancestor(struct patch *list,const char*filename)3201{3202struct patch *patch;3203struct index_state result = { NULL };3204int fd;32053206/* Once we start supporting the reverse patch, it may be3207 * worth showing the new sha1 prefix, but until then...3208 */3209for(patch = list; patch; patch = patch->next) {3210const unsigned char*sha1_ptr;3211unsigned char sha1[20];3212struct cache_entry *ce;3213const char*name;32143215 name = patch->old_name ? patch->old_name : patch->new_name;3216if(0< patch->is_new)3217continue;3218else if(get_sha1(patch->old_sha1_prefix, sha1))3219/* git diff has no index line for mode/type changes */3220if(!patch->lines_added && !patch->lines_deleted) {3221if(get_current_sha1(patch->old_name, sha1))3222die("mode change for%s, which is not "3223"in current HEAD", name);3224 sha1_ptr = sha1;3225}else3226die("sha1 information is lacking or useless "3227"(%s).", name);3228else3229 sha1_ptr = sha1;32303231 ce =make_cache_entry(patch->old_mode, sha1_ptr, name,0,0);3232if(!ce)3233die(_("make_cache_entry failed for path '%s'"), name);3234if(add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD))3235die("Could not add%sto temporary index", name);3236}32373238 fd =open(filename, O_WRONLY | O_CREAT,0666);3239if(fd <0||write_index(&result, fd) ||close(fd))3240die("Could not write temporary index to%s", filename);32413242discard_index(&result);3243}32443245static voidstat_patch_list(struct patch *patch)3246{3247int files, adds, dels;32483249for(files = adds = dels =0; patch ; patch = patch->next) {3250 files++;3251 adds += patch->lines_added;3252 dels += patch->lines_deleted;3253show_stats(patch);3254}32553256print_stat_summary(stdout, files, adds, dels);3257}32583259static voidnumstat_patch_list(struct patch *patch)3260{3261for( ; patch; patch = patch->next) {3262const char*name;3263 name = patch->new_name ? patch->new_name : patch->old_name;3264if(patch->is_binary)3265printf("-\t-\t");3266else3267printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);3268write_name_quoted(name, stdout, line_termination);3269}3270}32713272static voidshow_file_mode_name(const char*newdelete,unsigned int mode,const char*name)3273{3274if(mode)3275printf("%smode%06o%s\n", newdelete, mode, name);3276else3277printf("%s %s\n", newdelete, name);3278}32793280static voidshow_mode_change(struct patch *p,int show_name)3281{3282if(p->old_mode && p->new_mode && p->old_mode != p->new_mode) {3283if(show_name)3284printf(" mode change%06o =>%06o%s\n",3285 p->old_mode, p->new_mode, p->new_name);3286else3287printf(" mode change%06o =>%06o\n",3288 p->old_mode, p->new_mode);3289}3290}32913292static voidshow_rename_copy(struct patch *p)3293{3294const char*renamecopy = p->is_rename ?"rename":"copy";3295const char*old, *new;32963297/* Find common prefix */3298 old = p->old_name;3299new= p->new_name;3300while(1) {3301const char*slash_old, *slash_new;3302 slash_old =strchr(old,'/');3303 slash_new =strchr(new,'/');3304if(!slash_old ||3305!slash_new ||3306 slash_old - old != slash_new -new||3307memcmp(old,new, slash_new -new))3308break;3309 old = slash_old +1;3310new= slash_new +1;3311}3312/* p->old_name thru old is the common prefix, and old and new3313 * through the end of names are renames3314 */3315if(old != p->old_name)3316printf("%s%.*s{%s=>%s} (%d%%)\n", renamecopy,3317(int)(old - p->old_name), p->old_name,3318 old,new, p->score);3319else3320printf("%s %s=>%s(%d%%)\n", renamecopy,3321 p->old_name, p->new_name, p->score);3322show_mode_change(p,0);3323}33243325static voidsummary_patch_list(struct patch *patch)3326{3327struct patch *p;33283329for(p = patch; p; p = p->next) {3330if(p->is_new)3331show_file_mode_name("create", p->new_mode, p->new_name);3332else if(p->is_delete)3333show_file_mode_name("delete", p->old_mode, p->old_name);3334else{3335if(p->is_rename || p->is_copy)3336show_rename_copy(p);3337else{3338if(p->score) {3339printf(" rewrite%s(%d%%)\n",3340 p->new_name, p->score);3341show_mode_change(p,0);3342}3343else3344show_mode_change(p,1);3345}3346}3347}3348}33493350static voidpatch_stats(struct patch *patch)3351{3352int lines = patch->lines_added + patch->lines_deleted;33533354if(lines > max_change)3355 max_change = lines;3356if(patch->old_name) {3357int len =quote_c_style(patch->old_name, NULL, NULL,0);3358if(!len)3359 len =strlen(patch->old_name);3360if(len > max_len)3361 max_len = len;3362}3363if(patch->new_name) {3364int len =quote_c_style(patch->new_name, NULL, NULL,0);3365if(!len)3366 len =strlen(patch->new_name);3367if(len > max_len)3368 max_len = len;3369}3370}33713372static voidremove_file(struct patch *patch,int rmdir_empty)3373{3374if(update_index) {3375if(remove_file_from_cache(patch->old_name) <0)3376die(_("unable to remove%sfrom index"), patch->old_name);3377}3378if(!cached) {3379if(!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {3380remove_path(patch->old_name);3381}3382}3383}33843385static voidadd_index_file(const char*path,unsigned mode,void*buf,unsigned long size)3386{3387struct stat st;3388struct cache_entry *ce;3389int namelen =strlen(path);3390unsigned ce_size =cache_entry_size(namelen);33913392if(!update_index)3393return;33943395 ce =xcalloc(1, ce_size);3396memcpy(ce->name, path, namelen);3397 ce->ce_mode =create_ce_mode(mode);3398 ce->ce_flags = namelen;3399if(S_ISGITLINK(mode)) {3400const char*s = buf;34013402if(get_sha1_hex(s +strlen("Subproject commit "), ce->sha1))3403die(_("corrupt patch for subproject%s"), path);3404}else{3405if(!cached) {3406if(lstat(path, &st) <0)3407die_errno(_("unable to stat newly created file '%s'"),3408 path);3409fill_stat_cache_info(ce, &st);3410}3411if(write_sha1_file(buf, size, blob_type, ce->sha1) <0)3412die(_("unable to create backing store for newly created file%s"), path);3413}3414if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0)3415die(_("unable to add cache entry for%s"), path);3416}34173418static inttry_create_file(const char*path,unsigned int mode,const char*buf,unsigned long size)3419{3420int fd;3421struct strbuf nbuf = STRBUF_INIT;34223423if(S_ISGITLINK(mode)) {3424struct stat st;3425if(!lstat(path, &st) &&S_ISDIR(st.st_mode))3426return0;3427returnmkdir(path,0777);3428}34293430if(has_symlinks &&S_ISLNK(mode))3431/* Although buf:size is counted string, it also is NUL3432 * terminated.3433 */3434returnsymlink(buf, path);34353436 fd =open(path, O_CREAT | O_EXCL | O_WRONLY, (mode &0100) ?0777:0666);3437if(fd <0)3438return-1;34393440if(convert_to_working_tree(path, buf, size, &nbuf)) {3441 size = nbuf.len;3442 buf = nbuf.buf;3443}3444write_or_die(fd, buf, size);3445strbuf_release(&nbuf);34463447if(close(fd) <0)3448die_errno(_("closing file '%s'"), path);3449return0;3450}34513452/*3453 * We optimistically assume that the directories exist,3454 * which is true 99% of the time anyway. If they don't,3455 * we create them and try again.3456 */3457static voidcreate_one_file(char*path,unsigned mode,const char*buf,unsigned long size)3458{3459if(cached)3460return;3461if(!try_create_file(path, mode, buf, size))3462return;34633464if(errno == ENOENT) {3465if(safe_create_leading_directories(path))3466return;3467if(!try_create_file(path, mode, buf, size))3468return;3469}34703471if(errno == EEXIST || errno == EACCES) {3472/* We may be trying to create a file where a directory3473 * used to be.3474 */3475struct stat st;3476if(!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))3477 errno = EEXIST;3478}34793480if(errno == EEXIST) {3481unsigned int nr =getpid();34823483for(;;) {3484char newpath[PATH_MAX];3485mksnpath(newpath,sizeof(newpath),"%s~%u", path, nr);3486if(!try_create_file(newpath, mode, buf, size)) {3487if(!rename(newpath, path))3488return;3489unlink_or_warn(newpath);3490break;3491}3492if(errno != EEXIST)3493break;3494++nr;3495}3496}3497die_errno(_("unable to write file '%s' mode%o"), path, mode);3498}34993500static voidcreate_file(struct patch *patch)3501{3502char*path = patch->new_name;3503unsigned mode = patch->new_mode;3504unsigned long size = patch->resultsize;3505char*buf = patch->result;35063507if(!mode)3508 mode = S_IFREG |0644;3509create_one_file(path, mode, buf, size);3510add_index_file(path, mode, buf, size);3511}35123513/* phase zero is to remove, phase one is to create */3514static voidwrite_out_one_result(struct patch *patch,int phase)3515{3516if(patch->is_delete >0) {3517if(phase ==0)3518remove_file(patch,1);3519return;3520}3521if(patch->is_new >0|| patch->is_copy) {3522if(phase ==1)3523create_file(patch);3524return;3525}3526/*3527 * Rename or modification boils down to the same3528 * thing: remove the old, write the new3529 */3530if(phase ==0)3531remove_file(patch, patch->is_rename);3532if(phase ==1)3533create_file(patch);3534}35353536static intwrite_out_one_reject(struct patch *patch)3537{3538FILE*rej;3539char namebuf[PATH_MAX];3540struct fragment *frag;3541int cnt =0;3542struct strbuf sb = STRBUF_INIT;35433544for(cnt =0, frag = patch->fragments; frag; frag = frag->next) {3545if(!frag->rejected)3546continue;3547 cnt++;3548}35493550if(!cnt) {3551if(apply_verbosely)3552say_patch_name(stderr,3553_("Applied patch%scleanly."), patch);3554return0;3555}35563557/* This should not happen, because a removal patch that leaves3558 * contents are marked "rejected" at the patch level.3559 */3560if(!patch->new_name)3561die(_("internal error"));35623563/* Say this even without --verbose */3564strbuf_addf(&sb,Q_("Applying patch %%swith%dreject...",3565"Applying patch %%swith%drejects...",3566 cnt),3567 cnt);3568say_patch_name(stderr, sb.buf, patch);3569strbuf_release(&sb);35703571 cnt =strlen(patch->new_name);3572if(ARRAY_SIZE(namebuf) <= cnt +5) {3573 cnt =ARRAY_SIZE(namebuf) -5;3574warning(_("truncating .rej filename to %.*s.rej"),3575 cnt -1, patch->new_name);3576}3577memcpy(namebuf, patch->new_name, cnt);3578memcpy(namebuf + cnt,".rej",5);35793580 rej =fopen(namebuf,"w");3581if(!rej)3582returnerror(_("cannot open%s:%s"), namebuf,strerror(errno));35833584/* Normal git tools never deal with .rej, so do not pretend3585 * this is a git patch by saying --git nor give extended3586 * headers. While at it, maybe please "kompare" that wants3587 * the trailing TAB and some garbage at the end of line ;-).3588 */3589fprintf(rej,"diff a/%sb/%s\t(rejected hunks)\n",3590 patch->new_name, patch->new_name);3591for(cnt =1, frag = patch->fragments;3592 frag;3593 cnt++, frag = frag->next) {3594if(!frag->rejected) {3595fprintf_ln(stderr,_("Hunk #%dapplied cleanly."), cnt);3596continue;3597}3598fprintf_ln(stderr,_("Rejected hunk #%d."), cnt);3599fprintf(rej,"%.*s", frag->size, frag->patch);3600if(frag->patch[frag->size-1] !='\n')3601fputc('\n', rej);3602}3603fclose(rej);3604return-1;3605}36063607static intwrite_out_results(struct patch *list)3608{3609int phase;3610int errs =0;3611struct patch *l;36123613for(phase =0; phase <2; phase++) {3614 l = list;3615while(l) {3616if(l->rejected)3617 errs =1;3618else{3619write_out_one_result(l, phase);3620if(phase ==1&&write_out_one_reject(l))3621 errs =1;3622}3623 l = l->next;3624}3625}3626return errs;3627}36283629static struct lock_file lock_file;36303631static struct string_list limit_by_name;3632static int has_include;3633static voidadd_name_limit(const char*name,int exclude)3634{3635struct string_list_item *it;36363637 it =string_list_append(&limit_by_name, name);3638 it->util = exclude ? NULL : (void*)1;3639}36403641static intuse_patch(struct patch *p)3642{3643const char*pathname = p->new_name ? p->new_name : p->old_name;3644int i;36453646/* Paths outside are not touched regardless of "--include" */3647if(0< prefix_length) {3648int pathlen =strlen(pathname);3649if(pathlen <= prefix_length ||3650memcmp(prefix, pathname, prefix_length))3651return0;3652}36533654/* See if it matches any of exclude/include rule */3655for(i =0; i < limit_by_name.nr; i++) {3656struct string_list_item *it = &limit_by_name.items[i];3657if(!fnmatch(it->string, pathname,0))3658return(it->util != NULL);3659}36603661/*3662 * If we had any include, a path that does not match any rule is3663 * not used. Otherwise, we saw bunch of exclude rules (or none)3664 * and such a path is used.3665 */3666return!has_include;3667}366836693670static voidprefix_one(char**name)3671{3672char*old_name = *name;3673if(!old_name)3674return;3675*name =xstrdup(prefix_filename(prefix, prefix_length, *name));3676free(old_name);3677}36783679static voidprefix_patches(struct patch *p)3680{3681if(!prefix || p->is_toplevel_relative)3682return;3683for( ; p; p = p->next) {3684if(p->new_name == p->old_name) {3685char*prefixed = p->new_name;3686prefix_one(&prefixed);3687 p->new_name = p->old_name = prefixed;3688}3689else{3690prefix_one(&p->new_name);3691prefix_one(&p->old_name);3692}3693}3694}36953696#define INACCURATE_EOF (1<<0)3697#define RECOUNT (1<<1)36983699static intapply_patch(int fd,const char*filename,int options)3700{3701size_t offset;3702struct strbuf buf = STRBUF_INIT;3703struct patch *list = NULL, **listp = &list;3704int skipped_patch =0;37053706/* FIXME - memory leak when using multiple patch files as inputs */3707memset(&fn_table,0,sizeof(struct string_list));3708 patch_input_file = filename;3709read_patch_file(&buf, fd);3710 offset =0;3711while(offset < buf.len) {3712struct patch *patch;3713int nr;37143715 patch =xcalloc(1,sizeof(*patch));3716 patch->inaccurate_eof = !!(options & INACCURATE_EOF);3717 patch->recount = !!(options & RECOUNT);3718 nr =parse_chunk(buf.buf + offset, buf.len - offset, patch);3719if(nr <0)3720break;3721if(apply_in_reverse)3722reverse_patches(patch);3723if(prefix)3724prefix_patches(patch);3725if(use_patch(patch)) {3726patch_stats(patch);3727*listp = patch;3728 listp = &patch->next;3729}3730else{3731/* perhaps free it a bit better? */3732free(patch);3733 skipped_patch++;3734}3735 offset += nr;3736}37373738if(!list && !skipped_patch)3739die(_("unrecognized input"));37403741if(whitespace_error && (ws_error_action == die_on_ws_error))3742 apply =0;37433744 update_index = check_index && apply;3745if(update_index && newfd <0)3746 newfd =hold_locked_index(&lock_file,1);37473748if(check_index) {3749if(read_cache() <0)3750die(_("unable to read index file"));3751}37523753if((check || apply) &&3754check_patch_list(list) <0&&3755!apply_with_reject)3756exit(1);37573758if(apply &&write_out_results(list))3759exit(1);37603761if(fake_ancestor)3762build_fake_ancestor(list, fake_ancestor);37633764if(diffstat)3765stat_patch_list(list);37663767if(numstat)3768numstat_patch_list(list);37693770if(summary)3771summary_patch_list(list);37723773strbuf_release(&buf);3774return0;3775}37763777static intgit_apply_config(const char*var,const char*value,void*cb)3778{3779if(!strcmp(var,"apply.whitespace"))3780returngit_config_string(&apply_default_whitespace, var, value);3781else if(!strcmp(var,"apply.ignorewhitespace"))3782returngit_config_string(&apply_default_ignorewhitespace, var, value);3783returngit_default_config(var, value, cb);3784}37853786static intoption_parse_exclude(const struct option *opt,3787const char*arg,int unset)3788{3789add_name_limit(arg,1);3790return0;3791}37923793static intoption_parse_include(const struct option *opt,3794const char*arg,int unset)3795{3796add_name_limit(arg,0);3797 has_include =1;3798return0;3799}38003801static intoption_parse_p(const struct option *opt,3802const char*arg,int unset)3803{3804 p_value =atoi(arg);3805 p_value_known =1;3806return0;3807}38083809static intoption_parse_z(const struct option *opt,3810const char*arg,int unset)3811{3812if(unset)3813 line_termination ='\n';3814else3815 line_termination =0;3816return0;3817}38183819static intoption_parse_space_change(const struct option *opt,3820const char*arg,int unset)3821{3822if(unset)3823 ws_ignore_action = ignore_ws_none;3824else3825 ws_ignore_action = ignore_ws_change;3826return0;3827}38283829static intoption_parse_whitespace(const struct option *opt,3830const char*arg,int unset)3831{3832const char**whitespace_option = opt->value;38333834*whitespace_option = arg;3835parse_whitespace_option(arg);3836return0;3837}38383839static intoption_parse_directory(const struct option *opt,3840const char*arg,int unset)3841{3842 root_len =strlen(arg);3843if(root_len && arg[root_len -1] !='/') {3844char*new_root;3845 root = new_root =xmalloc(root_len +2);3846strcpy(new_root, arg);3847strcpy(new_root + root_len++,"/");3848}else3849 root = arg;3850return0;3851}38523853intcmd_apply(int argc,const char**argv,const char*prefix_)3854{3855int i;3856int errs =0;3857int is_not_gitdir = !startup_info->have_repository;3858int force_apply =0;38593860const char*whitespace_option = NULL;38613862struct option builtin_apply_options[] = {3863{ OPTION_CALLBACK,0,"exclude", NULL,"path",3864"don't apply changes matching the given path",38650, option_parse_exclude },3866{ OPTION_CALLBACK,0,"include", NULL,"path",3867"apply changes matching the given path",38680, option_parse_include },3869{ OPTION_CALLBACK,'p', NULL, NULL,"num",3870"remove <num> leading slashes from traditional diff paths",38710, option_parse_p },3872OPT_BOOLEAN(0,"no-add", &no_add,3873"ignore additions made by the patch"),3874OPT_BOOLEAN(0,"stat", &diffstat,3875"instead of applying the patch, output diffstat for the input"),3876OPT_NOOP_NOARG(0,"allow-binary-replacement"),3877OPT_NOOP_NOARG(0,"binary"),3878OPT_BOOLEAN(0,"numstat", &numstat,3879"shows number of added and deleted lines in decimal notation"),3880OPT_BOOLEAN(0,"summary", &summary,3881"instead of applying the patch, output a summary for the input"),3882OPT_BOOLEAN(0,"check", &check,3883"instead of applying the patch, see if the patch is applicable"),3884OPT_BOOLEAN(0,"index", &check_index,3885"make sure the patch is applicable to the current index"),3886OPT_BOOLEAN(0,"cached", &cached,3887"apply a patch without touching the working tree"),3888OPT_BOOLEAN(0,"apply", &force_apply,3889"also apply the patch (use with --stat/--summary/--check)"),3890OPT_FILENAME(0,"build-fake-ancestor", &fake_ancestor,3891"build a temporary index based on embedded index information"),3892{ OPTION_CALLBACK,'z', NULL, NULL, NULL,3893"paths are separated with NUL character",3894 PARSE_OPT_NOARG, option_parse_z },3895OPT_INTEGER('C', NULL, &p_context,3896"ensure at least <n> lines of context match"),3897{ OPTION_CALLBACK,0,"whitespace", &whitespace_option,"action",3898"detect new or modified lines that have whitespace errors",38990, option_parse_whitespace },3900{ OPTION_CALLBACK,0,"ignore-space-change", NULL, NULL,3901"ignore changes in whitespace when finding context",3902 PARSE_OPT_NOARG, option_parse_space_change },3903{ OPTION_CALLBACK,0,"ignore-whitespace", NULL, NULL,3904"ignore changes in whitespace when finding context",3905 PARSE_OPT_NOARG, option_parse_space_change },3906OPT_BOOLEAN('R',"reverse", &apply_in_reverse,3907"apply the patch in reverse"),3908OPT_BOOLEAN(0,"unidiff-zero", &unidiff_zero,3909"don't expect at least one line of context"),3910OPT_BOOLEAN(0,"reject", &apply_with_reject,3911"leave the rejected hunks in corresponding *.rej files"),3912OPT_BOOLEAN(0,"allow-overlap", &allow_overlap,3913"allow overlapping hunks"),3914OPT__VERBOSE(&apply_verbosely,"be verbose"),3915OPT_BIT(0,"inaccurate-eof", &options,3916"tolerate incorrectly detected missing new-line at the end of file",3917 INACCURATE_EOF),3918OPT_BIT(0,"recount", &options,3919"do not trust the line counts in the hunk headers",3920 RECOUNT),3921{ OPTION_CALLBACK,0,"directory", NULL,"root",3922"prepend <root> to all filenames",39230, option_parse_directory },3924OPT_END()3925};39263927 prefix = prefix_;3928 prefix_length = prefix ?strlen(prefix) :0;3929git_config(git_apply_config, NULL);3930if(apply_default_whitespace)3931parse_whitespace_option(apply_default_whitespace);3932if(apply_default_ignorewhitespace)3933parse_ignorewhitespace_option(apply_default_ignorewhitespace);39343935 argc =parse_options(argc, argv, prefix, builtin_apply_options,3936 apply_usage,0);39373938if(apply_with_reject)3939 apply = apply_verbosely =1;3940if(!force_apply && (diffstat || numstat || summary || check || fake_ancestor))3941 apply =0;3942if(check_index && is_not_gitdir)3943die(_("--index outside a repository"));3944if(cached) {3945if(is_not_gitdir)3946die(_("--cached outside a repository"));3947 check_index =1;3948}3949for(i =0; i < argc; i++) {3950const char*arg = argv[i];3951int fd;39523953if(!strcmp(arg,"-")) {3954 errs |=apply_patch(0,"<stdin>", options);3955 read_stdin =0;3956continue;3957}else if(0< prefix_length)3958 arg =prefix_filename(prefix, prefix_length, arg);39593960 fd =open(arg, O_RDONLY);3961if(fd <0)3962die_errno(_("can't open patch '%s'"), arg);3963 read_stdin =0;3964set_default_whitespace_mode(whitespace_option);3965 errs |=apply_patch(fd, arg, options);3966close(fd);3967}3968set_default_whitespace_mode(whitespace_option);3969if(read_stdin)3970 errs |=apply_patch(0,"<stdin>", options);3971if(whitespace_error) {3972if(squelch_whitespace_errors &&3973 squelch_whitespace_errors < whitespace_error) {3974int squelched =3975 whitespace_error - squelch_whitespace_errors;3976warning(Q_("squelched%dwhitespace error",3977"squelched%dwhitespace errors",3978 squelched),3979 squelched);3980}3981if(ws_error_action == die_on_ws_error)3982die(Q_("%dline adds whitespace errors.",3983"%dlines add whitespace errors.",3984 whitespace_error),3985 whitespace_error);3986if(applied_after_fixing_ws && apply)3987warning("%dline%sapplied after"3988" fixing whitespace errors.",3989 applied_after_fixing_ws,3990 applied_after_fixing_ws ==1?"":"s");3991else if(whitespace_error)3992warning(Q_("%dline adds whitespace errors.",3993"%dlines add whitespace errors.",3994 whitespace_error),3995 whitespace_error);3996}39973998if(update_index) {3999if(write_cache(newfd, active_cache, active_nr) ||4000commit_locked_index(&lock_file))4001die(_("Unable to write new index file"));4002}40034004return!!errs;4005}