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 "lockfile.h" 11#include "cache-tree.h" 12#include "quote.h" 13#include "blob.h" 14#include "delta.h" 15#include "builtin.h" 16#include "string-list.h" 17#include "dir.h" 18#include "diff.h" 19#include "parse-options.h" 20#include "xdiff-interface.h" 21#include "ll-merge.h" 22#include "rerere.h" 23 24struct apply_state { 25 const char *prefix; 26 int prefix_length; 27 28 /* These control what gets looked at and modified */ 29 int check; /* preimage must match working tree, don't actually apply */ 30 int check_index; /* preimage must match the indexed version */ 31 32 /* These boolean parameters control how the apply is done */ 33 int apply_in_reverse; 34 int unidiff_zero; 35}; 36 37/* 38 * --stat does just a diffstat, and doesn't actually apply 39 * --numstat does numeric diffstat, and doesn't actually apply 40 * --index-info shows the old and new index info for paths if available. 41 * --cached updates only the cache without ever touching the working tree. 42 */ 43static int newfd = -1; 44 45static int state_p_value = 1; 46static int p_value_known; 47static int update_index; 48static int cached; 49static int diffstat; 50static int numstat; 51static int summary; 52static int apply = 1; 53static int apply_with_reject; 54static int apply_verbosely; 55static int allow_overlap; 56static int no_add; 57static int threeway; 58static int unsafe_paths; 59static const char *fake_ancestor; 60static int line_termination = '\n'; 61static unsigned int p_context = UINT_MAX; 62static const char * const apply_usage[] = { 63 N_("git apply [<options>] [<patch>...]"), 64 NULL 65}; 66 67static enum ws_error_action { 68 nowarn_ws_error, 69 warn_on_ws_error, 70 die_on_ws_error, 71 correct_ws_error 72} ws_error_action = warn_on_ws_error; 73static int whitespace_error; 74static int squelch_whitespace_errors = 5; 75static int applied_after_fixing_ws; 76 77static enum ws_ignore { 78 ignore_ws_none, 79 ignore_ws_change 80} ws_ignore_action = ignore_ws_none; 81 82 83static const char *patch_input_file; 84static struct strbuf root = STRBUF_INIT; 85 86static void parse_whitespace_option(const char *option) 87{ 88 if (!option) { 89 ws_error_action = warn_on_ws_error; 90 return; 91 } 92 if (!strcmp(option, "warn")) { 93 ws_error_action = warn_on_ws_error; 94 return; 95 } 96 if (!strcmp(option, "nowarn")) { 97 ws_error_action = nowarn_ws_error; 98 return; 99 } 100 if (!strcmp(option, "error")) { 101 ws_error_action = die_on_ws_error; 102 return; 103 } 104 if (!strcmp(option, "error-all")) { 105 ws_error_action = die_on_ws_error; 106 squelch_whitespace_errors = 0; 107 return; 108 } 109 if (!strcmp(option, "strip") || !strcmp(option, "fix")) { 110 ws_error_action = correct_ws_error; 111 return; 112 } 113 die(_("unrecognized whitespace option '%s'"), option); 114} 115 116static void parse_ignorewhitespace_option(const char *option) 117{ 118 if (!option || !strcmp(option, "no") || 119 !strcmp(option, "false") || !strcmp(option, "never") || 120 !strcmp(option, "none")) { 121 ws_ignore_action = ignore_ws_none; 122 return; 123 } 124 if (!strcmp(option, "change")) { 125 ws_ignore_action = ignore_ws_change; 126 return; 127 } 128 die(_("unrecognized whitespace ignore option '%s'"), option); 129} 130 131static void set_default_whitespace_mode(const char *whitespace_option) 132{ 133 if (!whitespace_option && !apply_default_whitespace) 134 ws_error_action = (apply ? warn_on_ws_error : nowarn_ws_error); 135} 136 137/* 138 * For "diff-stat" like behaviour, we keep track of the biggest change 139 * we've seen, and the longest filename. That allows us to do simple 140 * scaling. 141 */ 142static int max_change, max_len; 143 144/* 145 * Various "current state", notably line numbers and what 146 * file (and how) we're patching right now.. The "is_xxxx" 147 * things are flags, where -1 means "don't know yet". 148 */ 149static int state_linenr = 1; 150 151/* 152 * This represents one "hunk" from a patch, starting with 153 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The 154 * patch text is pointed at by patch, and its byte length 155 * is stored in size. leading and trailing are the number 156 * of context lines. 157 */ 158struct fragment { 159 unsigned long leading, trailing; 160 unsigned long oldpos, oldlines; 161 unsigned long newpos, newlines; 162 /* 163 * 'patch' is usually borrowed from buf in apply_patch(), 164 * but some codepaths store an allocated buffer. 165 */ 166 const char *patch; 167 unsigned free_patch:1, 168 rejected:1; 169 int size; 170 int linenr; 171 struct fragment *next; 172}; 173 174/* 175 * When dealing with a binary patch, we reuse "leading" field 176 * to store the type of the binary hunk, either deflated "delta" 177 * or deflated "literal". 178 */ 179#define binary_patch_method leading 180#define BINARY_DELTA_DEFLATED 1 181#define BINARY_LITERAL_DEFLATED 2 182 183/* 184 * This represents a "patch" to a file, both metainfo changes 185 * such as creation/deletion, filemode and content changes represented 186 * as a series of fragments. 187 */ 188struct patch { 189 char *new_name, *old_name, *def_name; 190 unsigned int old_mode, new_mode; 191 int is_new, is_delete; /* -1 = unknown, 0 = false, 1 = true */ 192 int rejected; 193 unsigned ws_rule; 194 int lines_added, lines_deleted; 195 int score; 196 unsigned int is_toplevel_relative:1; 197 unsigned int inaccurate_eof:1; 198 unsigned int is_binary:1; 199 unsigned int is_copy:1; 200 unsigned int is_rename:1; 201 unsigned int recount:1; 202 unsigned int conflicted_threeway:1; 203 unsigned int direct_to_threeway:1; 204 struct fragment *fragments; 205 char *result; 206 size_t resultsize; 207 char old_sha1_prefix[41]; 208 char new_sha1_prefix[41]; 209 struct patch *next; 210 211 /* three-way fallback result */ 212 struct object_id threeway_stage[3]; 213}; 214 215static void free_fragment_list(struct fragment *list) 216{ 217 while (list) { 218 struct fragment *next = list->next; 219 if (list->free_patch) 220 free((char *)list->patch); 221 free(list); 222 list = next; 223 } 224} 225 226static void free_patch(struct patch *patch) 227{ 228 free_fragment_list(patch->fragments); 229 free(patch->def_name); 230 free(patch->old_name); 231 free(patch->new_name); 232 free(patch->result); 233 free(patch); 234} 235 236static void free_patch_list(struct patch *list) 237{ 238 while (list) { 239 struct patch *next = list->next; 240 free_patch(list); 241 list = next; 242 } 243} 244 245/* 246 * A line in a file, len-bytes long (includes the terminating LF, 247 * except for an incomplete line at the end if the file ends with 248 * one), and its contents hashes to 'hash'. 249 */ 250struct line { 251 size_t len; 252 unsigned hash : 24; 253 unsigned flag : 8; 254#define LINE_COMMON 1 255#define LINE_PATCHED 2 256}; 257 258/* 259 * This represents a "file", which is an array of "lines". 260 */ 261struct image { 262 char *buf; 263 size_t len; 264 size_t nr; 265 size_t alloc; 266 struct line *line_allocated; 267 struct line *line; 268}; 269 270/* 271 * Records filenames that have been touched, in order to handle 272 * the case where more than one patches touch the same file. 273 */ 274 275static struct string_list fn_table; 276 277static uint32_t hash_line(const char *cp, size_t len) 278{ 279 size_t i; 280 uint32_t h; 281 for (i = 0, h = 0; i < len; i++) { 282 if (!isspace(cp[i])) { 283 h = h * 3 + (cp[i] & 0xff); 284 } 285 } 286 return h; 287} 288 289/* 290 * Compare lines s1 of length n1 and s2 of length n2, ignoring 291 * whitespace difference. Returns 1 if they match, 0 otherwise 292 */ 293static int fuzzy_matchlines(const char *s1, size_t n1, 294 const char *s2, size_t n2) 295{ 296 const char *last1 = s1 + n1 - 1; 297 const char *last2 = s2 + n2 - 1; 298 int result = 0; 299 300 /* ignore line endings */ 301 while ((*last1 == '\r') || (*last1 == '\n')) 302 last1--; 303 while ((*last2 == '\r') || (*last2 == '\n')) 304 last2--; 305 306 /* skip leading whitespaces, if both begin with whitespace */ 307 if (s1 <= last1 && s2 <= last2 && isspace(*s1) && isspace(*s2)) { 308 while (isspace(*s1) && (s1 <= last1)) 309 s1++; 310 while (isspace(*s2) && (s2 <= last2)) 311 s2++; 312 } 313 /* early return if both lines are empty */ 314 if ((s1 > last1) && (s2 > last2)) 315 return 1; 316 while (!result) { 317 result = *s1++ - *s2++; 318 /* 319 * Skip whitespace inside. We check for whitespace on 320 * both buffers because we don't want "a b" to match 321 * "ab" 322 */ 323 if (isspace(*s1) && isspace(*s2)) { 324 while (isspace(*s1) && s1 <= last1) 325 s1++; 326 while (isspace(*s2) && s2 <= last2) 327 s2++; 328 } 329 /* 330 * If we reached the end on one side only, 331 * lines don't match 332 */ 333 if ( 334 ((s2 > last2) && (s1 <= last1)) || 335 ((s1 > last1) && (s2 <= last2))) 336 return 0; 337 if ((s1 > last1) && (s2 > last2)) 338 break; 339 } 340 341 return !result; 342} 343 344static void add_line_info(struct image *img, const char *bol, size_t len, unsigned flag) 345{ 346 ALLOC_GROW(img->line_allocated, img->nr + 1, img->alloc); 347 img->line_allocated[img->nr].len = len; 348 img->line_allocated[img->nr].hash = hash_line(bol, len); 349 img->line_allocated[img->nr].flag = flag; 350 img->nr++; 351} 352 353/* 354 * "buf" has the file contents to be patched (read from various sources). 355 * attach it to "image" and add line-based index to it. 356 * "image" now owns the "buf". 357 */ 358static void prepare_image(struct image *image, char *buf, size_t len, 359 int prepare_linetable) 360{ 361 const char *cp, *ep; 362 363 memset(image, 0, sizeof(*image)); 364 image->buf = buf; 365 image->len = len; 366 367 if (!prepare_linetable) 368 return; 369 370 ep = image->buf + image->len; 371 cp = image->buf; 372 while (cp < ep) { 373 const char *next; 374 for (next = cp; next < ep && *next != '\n'; next++) 375 ; 376 if (next < ep) 377 next++; 378 add_line_info(image, cp, next - cp, 0); 379 cp = next; 380 } 381 image->line = image->line_allocated; 382} 383 384static void clear_image(struct image *image) 385{ 386 free(image->buf); 387 free(image->line_allocated); 388 memset(image, 0, sizeof(*image)); 389} 390 391/* fmt must contain _one_ %s and no other substitution */ 392static void say_patch_name(FILE *output, const char *fmt, struct patch *patch) 393{ 394 struct strbuf sb = STRBUF_INIT; 395 396 if (patch->old_name && patch->new_name && 397 strcmp(patch->old_name, patch->new_name)) { 398 quote_c_style(patch->old_name, &sb, NULL, 0); 399 strbuf_addstr(&sb, " => "); 400 quote_c_style(patch->new_name, &sb, NULL, 0); 401 } else { 402 const char *n = patch->new_name; 403 if (!n) 404 n = patch->old_name; 405 quote_c_style(n, &sb, NULL, 0); 406 } 407 fprintf(output, fmt, sb.buf); 408 fputc('\n', output); 409 strbuf_release(&sb); 410} 411 412#define SLOP (16) 413 414static void read_patch_file(struct strbuf *sb, int fd) 415{ 416 if (strbuf_read(sb, fd, 0) < 0) 417 die_errno("git apply: failed to read"); 418 419 /* 420 * Make sure that we have some slop in the buffer 421 * so that we can do speculative "memcmp" etc, and 422 * see to it that it is NUL-filled. 423 */ 424 strbuf_grow(sb, SLOP); 425 memset(sb->buf + sb->len, 0, SLOP); 426} 427 428static unsigned long linelen(const char *buffer, unsigned long size) 429{ 430 unsigned long len = 0; 431 while (size--) { 432 len++; 433 if (*buffer++ == '\n') 434 break; 435 } 436 return len; 437} 438 439static int is_dev_null(const char *str) 440{ 441 return skip_prefix(str, "/dev/null", &str) && isspace(*str); 442} 443 444#define TERM_SPACE 1 445#define TERM_TAB 2 446 447static int name_terminate(const char *name, int namelen, int c, int terminate) 448{ 449 if (c == ' ' && !(terminate & TERM_SPACE)) 450 return 0; 451 if (c == '\t' && !(terminate & TERM_TAB)) 452 return 0; 453 454 return 1; 455} 456 457/* remove double slashes to make --index work with such filenames */ 458static char *squash_slash(char *name) 459{ 460 int i = 0, j = 0; 461 462 if (!name) 463 return NULL; 464 465 while (name[i]) { 466 if ((name[j++] = name[i++]) == '/') 467 while (name[i] == '/') 468 i++; 469 } 470 name[j] = '\0'; 471 return name; 472} 473 474static char *find_name_gnu(const char *line, const char *def, int p_value) 475{ 476 struct strbuf name = STRBUF_INIT; 477 char *cp; 478 479 /* 480 * Proposed "new-style" GNU patch/diff format; see 481 * http://marc.info/?l=git&m=112927316408690&w=2 482 */ 483 if (unquote_c_style(&name, line, NULL)) { 484 strbuf_release(&name); 485 return NULL; 486 } 487 488 for (cp = name.buf; p_value; p_value--) { 489 cp = strchr(cp, '/'); 490 if (!cp) { 491 strbuf_release(&name); 492 return NULL; 493 } 494 cp++; 495 } 496 497 strbuf_remove(&name, 0, cp - name.buf); 498 if (root.len) 499 strbuf_insert(&name, 0, root.buf, root.len); 500 return squash_slash(strbuf_detach(&name, NULL)); 501} 502 503static size_t sane_tz_len(const char *line, size_t len) 504{ 505 const char *tz, *p; 506 507 if (len < strlen(" +0500") || line[len-strlen(" +0500")] != ' ') 508 return 0; 509 tz = line + len - strlen(" +0500"); 510 511 if (tz[1] != '+' && tz[1] != '-') 512 return 0; 513 514 for (p = tz + 2; p != line + len; p++) 515 if (!isdigit(*p)) 516 return 0; 517 518 return line + len - tz; 519} 520 521static size_t tz_with_colon_len(const char *line, size_t len) 522{ 523 const char *tz, *p; 524 525 if (len < strlen(" +08:00") || line[len - strlen(":00")] != ':') 526 return 0; 527 tz = line + len - strlen(" +08:00"); 528 529 if (tz[0] != ' ' || (tz[1] != '+' && tz[1] != '-')) 530 return 0; 531 p = tz + 2; 532 if (!isdigit(*p++) || !isdigit(*p++) || *p++ != ':' || 533 !isdigit(*p++) || !isdigit(*p++)) 534 return 0; 535 536 return line + len - tz; 537} 538 539static size_t date_len(const char *line, size_t len) 540{ 541 const char *date, *p; 542 543 if (len < strlen("72-02-05") || line[len-strlen("-05")] != '-') 544 return 0; 545 p = date = line + len - strlen("72-02-05"); 546 547 if (!isdigit(*p++) || !isdigit(*p++) || *p++ != '-' || 548 !isdigit(*p++) || !isdigit(*p++) || *p++ != '-' || 549 !isdigit(*p++) || !isdigit(*p++)) /* Not a date. */ 550 return 0; 551 552 if (date - line >= strlen("19") && 553 isdigit(date[-1]) && isdigit(date[-2])) /* 4-digit year */ 554 date -= strlen("19"); 555 556 return line + len - date; 557} 558 559static size_t short_time_len(const char *line, size_t len) 560{ 561 const char *time, *p; 562 563 if (len < strlen(" 07:01:32") || line[len-strlen(":32")] != ':') 564 return 0; 565 p = time = line + len - strlen(" 07:01:32"); 566 567 /* Permit 1-digit hours? */ 568 if (*p++ != ' ' || 569 !isdigit(*p++) || !isdigit(*p++) || *p++ != ':' || 570 !isdigit(*p++) || !isdigit(*p++) || *p++ != ':' || 571 !isdigit(*p++) || !isdigit(*p++)) /* Not a time. */ 572 return 0; 573 574 return line + len - time; 575} 576 577static size_t fractional_time_len(const char *line, size_t len) 578{ 579 const char *p; 580 size_t n; 581 582 /* Expected format: 19:41:17.620000023 */ 583 if (!len || !isdigit(line[len - 1])) 584 return 0; 585 p = line + len - 1; 586 587 /* Fractional seconds. */ 588 while (p > line && isdigit(*p)) 589 p--; 590 if (*p != '.') 591 return 0; 592 593 /* Hours, minutes, and whole seconds. */ 594 n = short_time_len(line, p - line); 595 if (!n) 596 return 0; 597 598 return line + len - p + n; 599} 600 601static size_t trailing_spaces_len(const char *line, size_t len) 602{ 603 const char *p; 604 605 /* Expected format: ' ' x (1 or more) */ 606 if (!len || line[len - 1] != ' ') 607 return 0; 608 609 p = line + len; 610 while (p != line) { 611 p--; 612 if (*p != ' ') 613 return line + len - (p + 1); 614 } 615 616 /* All spaces! */ 617 return len; 618} 619 620static size_t diff_timestamp_len(const char *line, size_t len) 621{ 622 const char *end = line + len; 623 size_t n; 624 625 /* 626 * Posix: 2010-07-05 19:41:17 627 * GNU: 2010-07-05 19:41:17.620000023 -0500 628 */ 629 630 if (!isdigit(end[-1])) 631 return 0; 632 633 n = sane_tz_len(line, end - line); 634 if (!n) 635 n = tz_with_colon_len(line, end - line); 636 end -= n; 637 638 n = short_time_len(line, end - line); 639 if (!n) 640 n = fractional_time_len(line, end - line); 641 end -= n; 642 643 n = date_len(line, end - line); 644 if (!n) /* No date. Too bad. */ 645 return 0; 646 end -= n; 647 648 if (end == line) /* No space before date. */ 649 return 0; 650 if (end[-1] == '\t') { /* Success! */ 651 end--; 652 return line + len - end; 653 } 654 if (end[-1] != ' ') /* No space before date. */ 655 return 0; 656 657 /* Whitespace damage. */ 658 end -= trailing_spaces_len(line, end - line); 659 return line + len - end; 660} 661 662static char *find_name_common(const char *line, const char *def, 663 int p_value, const char *end, int terminate) 664{ 665 int len; 666 const char *start = NULL; 667 668 if (p_value == 0) 669 start = line; 670 while (line != end) { 671 char c = *line; 672 673 if (!end && isspace(c)) { 674 if (c == '\n') 675 break; 676 if (name_terminate(start, line-start, c, terminate)) 677 break; 678 } 679 line++; 680 if (c == '/' && !--p_value) 681 start = line; 682 } 683 if (!start) 684 return squash_slash(xstrdup_or_null(def)); 685 len = line - start; 686 if (!len) 687 return squash_slash(xstrdup_or_null(def)); 688 689 /* 690 * Generally we prefer the shorter name, especially 691 * if the other one is just a variation of that with 692 * something else tacked on to the end (ie "file.orig" 693 * or "file~"). 694 */ 695 if (def) { 696 int deflen = strlen(def); 697 if (deflen < len && !strncmp(start, def, deflen)) 698 return squash_slash(xstrdup(def)); 699 } 700 701 if (root.len) { 702 char *ret = xstrfmt("%s%.*s", root.buf, len, start); 703 return squash_slash(ret); 704 } 705 706 return squash_slash(xmemdupz(start, len)); 707} 708 709static char *find_name(const char *line, char *def, int p_value, int terminate) 710{ 711 if (*line == '"') { 712 char *name = find_name_gnu(line, def, p_value); 713 if (name) 714 return name; 715 } 716 717 return find_name_common(line, def, p_value, NULL, terminate); 718} 719 720static char *find_name_traditional(const char *line, char *def, int p_value) 721{ 722 size_t len; 723 size_t date_len; 724 725 if (*line == '"') { 726 char *name = find_name_gnu(line, def, p_value); 727 if (name) 728 return name; 729 } 730 731 len = strchrnul(line, '\n') - line; 732 date_len = diff_timestamp_len(line, len); 733 if (!date_len) 734 return find_name_common(line, def, p_value, NULL, TERM_TAB); 735 len -= date_len; 736 737 return find_name_common(line, def, p_value, line + len, 0); 738} 739 740static int count_slashes(const char *cp) 741{ 742 int cnt = 0; 743 char ch; 744 745 while ((ch = *cp++)) 746 if (ch == '/') 747 cnt++; 748 return cnt; 749} 750 751/* 752 * Given the string after "--- " or "+++ ", guess the appropriate 753 * p_value for the given patch. 754 */ 755static int guess_p_value(struct apply_state *state, const char *nameline) 756{ 757 char *name, *cp; 758 int val = -1; 759 760 if (is_dev_null(nameline)) 761 return -1; 762 name = find_name_traditional(nameline, NULL, 0); 763 if (!name) 764 return -1; 765 cp = strchr(name, '/'); 766 if (!cp) 767 val = 0; 768 else if (state->prefix) { 769 /* 770 * Does it begin with "a/$our-prefix" and such? Then this is 771 * very likely to apply to our directory. 772 */ 773 if (!strncmp(name, state->prefix, state->prefix_length)) 774 val = count_slashes(state->prefix); 775 else { 776 cp++; 777 if (!strncmp(cp, state->prefix, state->prefix_length)) 778 val = count_slashes(state->prefix) + 1; 779 } 780 } 781 free(name); 782 return val; 783} 784 785/* 786 * Does the ---/+++ line have the POSIX timestamp after the last HT? 787 * GNU diff puts epoch there to signal a creation/deletion event. Is 788 * this such a timestamp? 789 */ 790static int has_epoch_timestamp(const char *nameline) 791{ 792 /* 793 * We are only interested in epoch timestamp; any non-zero 794 * fraction cannot be one, hence "(\.0+)?" in the regexp below. 795 * For the same reason, the date must be either 1969-12-31 or 796 * 1970-01-01, and the seconds part must be "00". 797 */ 798 const char stamp_regexp[] = 799 "^(1969-12-31|1970-01-01)" 800 " " 801 "[0-2][0-9]:[0-5][0-9]:00(\\.0+)?" 802 " " 803 "([-+][0-2][0-9]:?[0-5][0-9])\n"; 804 const char *timestamp = NULL, *cp, *colon; 805 static regex_t *stamp; 806 regmatch_t m[10]; 807 int zoneoffset; 808 int hourminute; 809 int status; 810 811 for (cp = nameline; *cp != '\n'; cp++) { 812 if (*cp == '\t') 813 timestamp = cp + 1; 814 } 815 if (!timestamp) 816 return 0; 817 if (!stamp) { 818 stamp = xmalloc(sizeof(*stamp)); 819 if (regcomp(stamp, stamp_regexp, REG_EXTENDED)) { 820 warning(_("Cannot prepare timestamp regexp %s"), 821 stamp_regexp); 822 return 0; 823 } 824 } 825 826 status = regexec(stamp, timestamp, ARRAY_SIZE(m), m, 0); 827 if (status) { 828 if (status != REG_NOMATCH) 829 warning(_("regexec returned %d for input: %s"), 830 status, timestamp); 831 return 0; 832 } 833 834 zoneoffset = strtol(timestamp + m[3].rm_so + 1, (char **) &colon, 10); 835 if (*colon == ':') 836 zoneoffset = zoneoffset * 60 + strtol(colon + 1, NULL, 10); 837 else 838 zoneoffset = (zoneoffset / 100) * 60 + (zoneoffset % 100); 839 if (timestamp[m[3].rm_so] == '-') 840 zoneoffset = -zoneoffset; 841 842 /* 843 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31 844 * (west of GMT) or 1970-01-01 (east of GMT) 845 */ 846 if ((zoneoffset < 0 && memcmp(timestamp, "1969-12-31", 10)) || 847 (0 <= zoneoffset && memcmp(timestamp, "1970-01-01", 10))) 848 return 0; 849 850 hourminute = (strtol(timestamp + 11, NULL, 10) * 60 + 851 strtol(timestamp + 14, NULL, 10) - 852 zoneoffset); 853 854 return ((zoneoffset < 0 && hourminute == 1440) || 855 (0 <= zoneoffset && !hourminute)); 856} 857 858/* 859 * Get the name etc info from the ---/+++ lines of a traditional patch header 860 * 861 * FIXME! The end-of-filename heuristics are kind of screwy. For existing 862 * files, we can happily check the index for a match, but for creating a 863 * new file we should try to match whatever "patch" does. I have no idea. 864 */ 865static void parse_traditional_patch(struct apply_state *state, 866 const char *first, 867 const char *second, 868 struct patch *patch) 869{ 870 char *name; 871 872 first += 4; /* skip "--- " */ 873 second += 4; /* skip "+++ " */ 874 if (!p_value_known) { 875 int p, q; 876 p = guess_p_value(state, first); 877 q = guess_p_value(state, second); 878 if (p < 0) p = q; 879 if (0 <= p && p == q) { 880 state_p_value = p; 881 p_value_known = 1; 882 } 883 } 884 if (is_dev_null(first)) { 885 patch->is_new = 1; 886 patch->is_delete = 0; 887 name = find_name_traditional(second, NULL, state_p_value); 888 patch->new_name = name; 889 } else if (is_dev_null(second)) { 890 patch->is_new = 0; 891 patch->is_delete = 1; 892 name = find_name_traditional(first, NULL, state_p_value); 893 patch->old_name = name; 894 } else { 895 char *first_name; 896 first_name = find_name_traditional(first, NULL, state_p_value); 897 name = find_name_traditional(second, first_name, state_p_value); 898 free(first_name); 899 if (has_epoch_timestamp(first)) { 900 patch->is_new = 1; 901 patch->is_delete = 0; 902 patch->new_name = name; 903 } else if (has_epoch_timestamp(second)) { 904 patch->is_new = 0; 905 patch->is_delete = 1; 906 patch->old_name = name; 907 } else { 908 patch->old_name = name; 909 patch->new_name = xstrdup_or_null(name); 910 } 911 } 912 if (!name) 913 die(_("unable to find filename in patch at line %d"), state_linenr); 914} 915 916static int gitdiff_hdrend(const char *line, struct patch *patch) 917{ 918 return -1; 919} 920 921/* 922 * We're anal about diff header consistency, to make 923 * sure that we don't end up having strange ambiguous 924 * patches floating around. 925 * 926 * As a result, gitdiff_{old|new}name() will check 927 * their names against any previous information, just 928 * to make sure.. 929 */ 930#define DIFF_OLD_NAME 0 931#define DIFF_NEW_NAME 1 932 933static void gitdiff_verify_name(const char *line, int isnull, char **name, int side) 934{ 935 if (!*name && !isnull) { 936 *name = find_name(line, NULL, state_p_value, TERM_TAB); 937 return; 938 } 939 940 if (*name) { 941 int len = strlen(*name); 942 char *another; 943 if (isnull) 944 die(_("git apply: bad git-diff - expected /dev/null, got %s on line %d"), 945 *name, state_linenr); 946 another = find_name(line, NULL, state_p_value, TERM_TAB); 947 if (!another || memcmp(another, *name, len + 1)) 948 die((side == DIFF_NEW_NAME) ? 949 _("git apply: bad git-diff - inconsistent new filename on line %d") : 950 _("git apply: bad git-diff - inconsistent old filename on line %d"), state_linenr); 951 free(another); 952 } else { 953 /* expect "/dev/null" */ 954 if (memcmp("/dev/null", line, 9) || line[9] != '\n') 955 die(_("git apply: bad git-diff - expected /dev/null on line %d"), state_linenr); 956 } 957} 958 959static int gitdiff_oldname(const char *line, struct patch *patch) 960{ 961 gitdiff_verify_name(line, patch->is_new, &patch->old_name, 962 DIFF_OLD_NAME); 963 return 0; 964} 965 966static int gitdiff_newname(const char *line, struct patch *patch) 967{ 968 gitdiff_verify_name(line, patch->is_delete, &patch->new_name, 969 DIFF_NEW_NAME); 970 return 0; 971} 972 973static int gitdiff_oldmode(const char *line, struct patch *patch) 974{ 975 patch->old_mode = strtoul(line, NULL, 8); 976 return 0; 977} 978 979static int gitdiff_newmode(const char *line, struct patch *patch) 980{ 981 patch->new_mode = strtoul(line, NULL, 8); 982 return 0; 983} 984 985static int gitdiff_delete(const char *line, struct patch *patch) 986{ 987 patch->is_delete = 1; 988 free(patch->old_name); 989 patch->old_name = xstrdup_or_null(patch->def_name); 990 return gitdiff_oldmode(line, patch); 991} 992 993static int gitdiff_newfile(const char *line, struct patch *patch) 994{ 995 patch->is_new = 1; 996 free(patch->new_name); 997 patch->new_name = xstrdup_or_null(patch->def_name); 998 return gitdiff_newmode(line, patch); 999}10001001static int gitdiff_copysrc(const char *line, struct patch *patch)1002{1003 patch->is_copy = 1;1004 free(patch->old_name);1005 patch->old_name = find_name(line, NULL, state_p_value ? state_p_value - 1 : 0, 0);1006 return 0;1007}10081009static int gitdiff_copydst(const char *line, struct patch *patch)1010{1011 patch->is_copy = 1;1012 free(patch->new_name);1013 patch->new_name = find_name(line, NULL, state_p_value ? state_p_value - 1 : 0, 0);1014 return 0;1015}10161017static int gitdiff_renamesrc(const char *line, struct patch *patch)1018{1019 patch->is_rename = 1;1020 free(patch->old_name);1021 patch->old_name = find_name(line, NULL, state_p_value ? state_p_value - 1 : 0, 0);1022 return 0;1023}10241025static int gitdiff_renamedst(const char *line, struct patch *patch)1026{1027 patch->is_rename = 1;1028 free(patch->new_name);1029 patch->new_name = find_name(line, NULL, state_p_value ? state_p_value - 1 : 0, 0);1030 return 0;1031}10321033static int gitdiff_similarity(const char *line, struct patch *patch)1034{1035 unsigned long val = strtoul(line, NULL, 10);1036 if (val <= 100)1037 patch->score = val;1038 return 0;1039}10401041static int gitdiff_dissimilarity(const char *line, struct patch *patch)1042{1043 unsigned long val = strtoul(line, NULL, 10);1044 if (val <= 100)1045 patch->score = val;1046 return 0;1047}10481049static int gitdiff_index(const char *line, struct patch *patch)1050{1051 /*1052 * index line is N hexadecimal, "..", N hexadecimal,1053 * and optional space with octal mode.1054 */1055 const char *ptr, *eol;1056 int len;10571058 ptr = strchr(line, '.');1059 if (!ptr || ptr[1] != '.' || 40 < ptr - line)1060 return 0;1061 len = ptr - line;1062 memcpy(patch->old_sha1_prefix, line, len);1063 patch->old_sha1_prefix[len] = 0;10641065 line = ptr + 2;1066 ptr = strchr(line, ' ');1067 eol = strchrnul(line, '\n');10681069 if (!ptr || eol < ptr)1070 ptr = eol;1071 len = ptr - line;10721073 if (40 < len)1074 return 0;1075 memcpy(patch->new_sha1_prefix, line, len);1076 patch->new_sha1_prefix[len] = 0;1077 if (*ptr == ' ')1078 patch->old_mode = strtoul(ptr+1, NULL, 8);1079 return 0;1080}10811082/*1083 * This is normal for a diff that doesn't change anything: we'll fall through1084 * into the next diff. Tell the parser to break out.1085 */1086static int gitdiff_unrecognized(const char *line, struct patch *patch)1087{1088 return -1;1089}10901091/*1092 * Skip p_value leading components from "line"; as we do not accept1093 * absolute paths, return NULL in that case.1094 */1095static const char *skip_tree_prefix(const char *line, int llen)1096{1097 int nslash;1098 int i;10991100 if (!state_p_value)1101 return (llen && line[0] == '/') ? NULL : line;11021103 nslash = state_p_value;1104 for (i = 0; i < llen; i++) {1105 int ch = line[i];1106 if (ch == '/' && --nslash <= 0)1107 return (i == 0) ? NULL : &line[i + 1];1108 }1109 return NULL;1110}11111112/*1113 * This is to extract the same name that appears on "diff --git"1114 * line. We do not find and return anything if it is a rename1115 * patch, and it is OK because we will find the name elsewhere.1116 * We need to reliably find name only when it is mode-change only,1117 * creation or deletion of an empty file. In any of these cases,1118 * both sides are the same name under a/ and b/ respectively.1119 */1120static char *git_header_name(const char *line, int llen)1121{1122 const char *name;1123 const char *second = NULL;1124 size_t len, line_len;11251126 line += strlen("diff --git ");1127 llen -= strlen("diff --git ");11281129 if (*line == '"') {1130 const char *cp;1131 struct strbuf first = STRBUF_INIT;1132 struct strbuf sp = STRBUF_INIT;11331134 if (unquote_c_style(&first, line, &second))1135 goto free_and_fail1;11361137 /* strip the a/b prefix including trailing slash */1138 cp = skip_tree_prefix(first.buf, first.len);1139 if (!cp)1140 goto free_and_fail1;1141 strbuf_remove(&first, 0, cp - first.buf);11421143 /*1144 * second points at one past closing dq of name.1145 * find the second name.1146 */1147 while ((second < line + llen) && isspace(*second))1148 second++;11491150 if (line + llen <= second)1151 goto free_and_fail1;1152 if (*second == '"') {1153 if (unquote_c_style(&sp, second, NULL))1154 goto free_and_fail1;1155 cp = skip_tree_prefix(sp.buf, sp.len);1156 if (!cp)1157 goto free_and_fail1;1158 /* They must match, otherwise ignore */1159 if (strcmp(cp, first.buf))1160 goto free_and_fail1;1161 strbuf_release(&sp);1162 return strbuf_detach(&first, NULL);1163 }11641165 /* unquoted second */1166 cp = skip_tree_prefix(second, line + llen - second);1167 if (!cp)1168 goto free_and_fail1;1169 if (line + llen - cp != first.len ||1170 memcmp(first.buf, cp, first.len))1171 goto free_and_fail1;1172 return strbuf_detach(&first, NULL);11731174 free_and_fail1:1175 strbuf_release(&first);1176 strbuf_release(&sp);1177 return NULL;1178 }11791180 /* unquoted first name */1181 name = skip_tree_prefix(line, llen);1182 if (!name)1183 return NULL;11841185 /*1186 * since the first name is unquoted, a dq if exists must be1187 * the beginning of the second name.1188 */1189 for (second = name; second < line + llen; second++) {1190 if (*second == '"') {1191 struct strbuf sp = STRBUF_INIT;1192 const char *np;11931194 if (unquote_c_style(&sp, second, NULL))1195 goto free_and_fail2;11961197 np = skip_tree_prefix(sp.buf, sp.len);1198 if (!np)1199 goto free_and_fail2;12001201 len = sp.buf + sp.len - np;1202 if (len < second - name &&1203 !strncmp(np, name, len) &&1204 isspace(name[len])) {1205 /* Good */1206 strbuf_remove(&sp, 0, np - sp.buf);1207 return strbuf_detach(&sp, NULL);1208 }12091210 free_and_fail2:1211 strbuf_release(&sp);1212 return NULL;1213 }1214 }12151216 /*1217 * Accept a name only if it shows up twice, exactly the same1218 * form.1219 */1220 second = strchr(name, '\n');1221 if (!second)1222 return NULL;1223 line_len = second - name;1224 for (len = 0 ; ; len++) {1225 switch (name[len]) {1226 default:1227 continue;1228 case '\n':1229 return NULL;1230 case '\t': case ' ':1231 /*1232 * Is this the separator between the preimage1233 * and the postimage pathname? Again, we are1234 * only interested in the case where there is1235 * no rename, as this is only to set def_name1236 * and a rename patch has the names elsewhere1237 * in an unambiguous form.1238 */1239 if (!name[len + 1])1240 return NULL; /* no postimage name */1241 second = skip_tree_prefix(name + len + 1,1242 line_len - (len + 1));1243 if (!second)1244 return NULL;1245 /*1246 * Does len bytes starting at "name" and "second"1247 * (that are separated by one HT or SP we just1248 * found) exactly match?1249 */1250 if (second[len] == '\n' && !strncmp(name, second, len))1251 return xmemdupz(name, len);1252 }1253 }1254}12551256/* Verify that we recognize the lines following a git header */1257static int parse_git_header(const char *line, int len, unsigned int size, struct patch *patch)1258{1259 unsigned long offset;12601261 /* A git diff has explicit new/delete information, so we don't guess */1262 patch->is_new = 0;1263 patch->is_delete = 0;12641265 /*1266 * Some things may not have the old name in the1267 * rest of the headers anywhere (pure mode changes,1268 * or removing or adding empty files), so we get1269 * the default name from the header.1270 */1271 patch->def_name = git_header_name(line, len);1272 if (patch->def_name && root.len) {1273 char *s = xstrfmt("%s%s", root.buf, patch->def_name);1274 free(patch->def_name);1275 patch->def_name = s;1276 }12771278 line += len;1279 size -= len;1280 state_linenr++;1281 for (offset = len ; size > 0 ; offset += len, size -= len, line += len, state_linenr++) {1282 static const struct opentry {1283 const char *str;1284 int (*fn)(const char *, struct patch *);1285 } optable[] = {1286 { "@@ -", gitdiff_hdrend },1287 { "--- ", gitdiff_oldname },1288 { "+++ ", gitdiff_newname },1289 { "old mode ", gitdiff_oldmode },1290 { "new mode ", gitdiff_newmode },1291 { "deleted file mode ", gitdiff_delete },1292 { "new file mode ", gitdiff_newfile },1293 { "copy from ", gitdiff_copysrc },1294 { "copy to ", gitdiff_copydst },1295 { "rename old ", gitdiff_renamesrc },1296 { "rename new ", gitdiff_renamedst },1297 { "rename from ", gitdiff_renamesrc },1298 { "rename to ", gitdiff_renamedst },1299 { "similarity index ", gitdiff_similarity },1300 { "dissimilarity index ", gitdiff_dissimilarity },1301 { "index ", gitdiff_index },1302 { "", gitdiff_unrecognized },1303 };1304 int i;13051306 len = linelen(line, size);1307 if (!len || line[len-1] != '\n')1308 break;1309 for (i = 0; i < ARRAY_SIZE(optable); i++) {1310 const struct opentry *p = optable + i;1311 int oplen = strlen(p->str);1312 if (len < oplen || memcmp(p->str, line, oplen))1313 continue;1314 if (p->fn(line + oplen, patch) < 0)1315 return offset;1316 break;1317 }1318 }13191320 return offset;1321}13221323static int parse_num(const char *line, unsigned long *p)1324{1325 char *ptr;13261327 if (!isdigit(*line))1328 return 0;1329 *p = strtoul(line, &ptr, 10);1330 return ptr - line;1331}13321333static int parse_range(const char *line, int len, int offset, const char *expect,1334 unsigned long *p1, unsigned long *p2)1335{1336 int digits, ex;13371338 if (offset < 0 || offset >= len)1339 return -1;1340 line += offset;1341 len -= offset;13421343 digits = parse_num(line, p1);1344 if (!digits)1345 return -1;13461347 offset += digits;1348 line += digits;1349 len -= digits;13501351 *p2 = 1;1352 if (*line == ',') {1353 digits = parse_num(line+1, p2);1354 if (!digits)1355 return -1;13561357 offset += digits+1;1358 line += digits+1;1359 len -= digits+1;1360 }13611362 ex = strlen(expect);1363 if (ex > len)1364 return -1;1365 if (memcmp(line, expect, ex))1366 return -1;13671368 return offset + ex;1369}13701371static void recount_diff(const char *line, int size, struct fragment *fragment)1372{1373 int oldlines = 0, newlines = 0, ret = 0;13741375 if (size < 1) {1376 warning("recount: ignore empty hunk");1377 return;1378 }13791380 for (;;) {1381 int len = linelen(line, size);1382 size -= len;1383 line += len;13841385 if (size < 1)1386 break;13871388 switch (*line) {1389 case ' ': case '\n':1390 newlines++;1391 /* fall through */1392 case '-':1393 oldlines++;1394 continue;1395 case '+':1396 newlines++;1397 continue;1398 case '\\':1399 continue;1400 case '@':1401 ret = size < 3 || !starts_with(line, "@@ ");1402 break;1403 case 'd':1404 ret = size < 5 || !starts_with(line, "diff ");1405 break;1406 default:1407 ret = -1;1408 break;1409 }1410 if (ret) {1411 warning(_("recount: unexpected line: %.*s"),1412 (int)linelen(line, size), line);1413 return;1414 }1415 break;1416 }1417 fragment->oldlines = oldlines;1418 fragment->newlines = newlines;1419}14201421/*1422 * Parse a unified diff fragment header of the1423 * form "@@ -a,b +c,d @@"1424 */1425static int parse_fragment_header(const char *line, int len, struct fragment *fragment)1426{1427 int offset;14281429 if (!len || line[len-1] != '\n')1430 return -1;14311432 /* Figure out the number of lines in a fragment */1433 offset = parse_range(line, len, 4, " +", &fragment->oldpos, &fragment->oldlines);1434 offset = parse_range(line, len, offset, " @@", &fragment->newpos, &fragment->newlines);14351436 return offset;1437}14381439static int find_header(struct apply_state *state,1440 const char *line,1441 unsigned long size,1442 int *hdrsize,1443 struct patch *patch)1444{1445 unsigned long offset, len;14461447 patch->is_toplevel_relative = 0;1448 patch->is_rename = patch->is_copy = 0;1449 patch->is_new = patch->is_delete = -1;1450 patch->old_mode = patch->new_mode = 0;1451 patch->old_name = patch->new_name = NULL;1452 for (offset = 0; size > 0; offset += len, size -= len, line += len, state_linenr++) {1453 unsigned long nextlen;14541455 len = linelen(line, size);1456 if (!len)1457 break;14581459 /* Testing this early allows us to take a few shortcuts.. */1460 if (len < 6)1461 continue;14621463 /*1464 * Make sure we don't find any unconnected patch fragments.1465 * That's a sign that we didn't find a header, and that a1466 * patch has become corrupted/broken up.1467 */1468 if (!memcmp("@@ -", line, 4)) {1469 struct fragment dummy;1470 if (parse_fragment_header(line, len, &dummy) < 0)1471 continue;1472 die(_("patch fragment without header at line %d: %.*s"),1473 state_linenr, (int)len-1, line);1474 }14751476 if (size < len + 6)1477 break;14781479 /*1480 * Git patch? It might not have a real patch, just a rename1481 * or mode change, so we handle that specially1482 */1483 if (!memcmp("diff --git ", line, 11)) {1484 int git_hdr_len = parse_git_header(line, len, size, patch);1485 if (git_hdr_len <= len)1486 continue;1487 if (!patch->old_name && !patch->new_name) {1488 if (!patch->def_name)1489 die(Q_("git diff header lacks filename information when removing "1490 "%d leading pathname component (line %d)",1491 "git diff header lacks filename information when removing "1492 "%d leading pathname components (line %d)",1493 state_p_value),1494 state_p_value, state_linenr);1495 patch->old_name = xstrdup(patch->def_name);1496 patch->new_name = xstrdup(patch->def_name);1497 }1498 if (!patch->is_delete && !patch->new_name)1499 die("git diff header lacks filename information "1500 "(line %d)", state_linenr);1501 patch->is_toplevel_relative = 1;1502 *hdrsize = git_hdr_len;1503 return offset;1504 }15051506 /* --- followed by +++ ? */1507 if (memcmp("--- ", line, 4) || memcmp("+++ ", line + len, 4))1508 continue;15091510 /*1511 * We only accept unified patches, so we want it to1512 * at least have "@@ -a,b +c,d @@\n", which is 14 chars1513 * minimum ("@@ -0,0 +1 @@\n" is the shortest).1514 */1515 nextlen = linelen(line + len, size - len);1516 if (size < nextlen + 14 || memcmp("@@ -", line + len + nextlen, 4))1517 continue;15181519 /* Ok, we'll consider it a patch */1520 parse_traditional_patch(state, line, line+len, patch);1521 *hdrsize = len + nextlen;1522 state_linenr += 2;1523 return offset;1524 }1525 return -1;1526}15271528static void record_ws_error(unsigned result, const char *line, int len, int linenr)1529{1530 char *err;15311532 if (!result)1533 return;15341535 whitespace_error++;1536 if (squelch_whitespace_errors &&1537 squelch_whitespace_errors < whitespace_error)1538 return;15391540 err = whitespace_error_string(result);1541 fprintf(stderr, "%s:%d: %s.\n%.*s\n",1542 patch_input_file, linenr, err, len, line);1543 free(err);1544}15451546static void check_whitespace(const char *line, int len, unsigned ws_rule)1547{1548 unsigned result = ws_check(line + 1, len - 1, ws_rule);15491550 record_ws_error(result, line + 1, len - 2, state_linenr);1551}15521553/*1554 * Parse a unified diff. Note that this really needs to parse each1555 * fragment separately, since the only way to know the difference1556 * between a "---" that is part of a patch, and a "---" that starts1557 * the next patch is to look at the line counts..1558 */1559static int parse_fragment(struct apply_state *state,1560 const char *line,1561 unsigned long size,1562 struct patch *patch,1563 struct fragment *fragment)1564{1565 int added, deleted;1566 int len = linelen(line, size), offset;1567 unsigned long oldlines, newlines;1568 unsigned long leading, trailing;15691570 offset = parse_fragment_header(line, len, fragment);1571 if (offset < 0)1572 return -1;1573 if (offset > 0 && patch->recount)1574 recount_diff(line + offset, size - offset, fragment);1575 oldlines = fragment->oldlines;1576 newlines = fragment->newlines;1577 leading = 0;1578 trailing = 0;15791580 /* Parse the thing.. */1581 line += len;1582 size -= len;1583 state_linenr++;1584 added = deleted = 0;1585 for (offset = len;1586 0 < size;1587 offset += len, size -= len, line += len, state_linenr++) {1588 if (!oldlines && !newlines)1589 break;1590 len = linelen(line, size);1591 if (!len || line[len-1] != '\n')1592 return -1;1593 switch (*line) {1594 default:1595 return -1;1596 case '\n': /* newer GNU diff, an empty context line */1597 case ' ':1598 oldlines--;1599 newlines--;1600 if (!deleted && !added)1601 leading++;1602 trailing++;1603 if (!state->apply_in_reverse &&1604 ws_error_action == correct_ws_error)1605 check_whitespace(line, len, patch->ws_rule);1606 break;1607 case '-':1608 if (state->apply_in_reverse &&1609 ws_error_action != nowarn_ws_error)1610 check_whitespace(line, len, patch->ws_rule);1611 deleted++;1612 oldlines--;1613 trailing = 0;1614 break;1615 case '+':1616 if (!state->apply_in_reverse &&1617 ws_error_action != nowarn_ws_error)1618 check_whitespace(line, len, patch->ws_rule);1619 added++;1620 newlines--;1621 trailing = 0;1622 break;16231624 /*1625 * We allow "\ No newline at end of file". Depending1626 * on locale settings when the patch was produced we1627 * don't know what this line looks like. The only1628 * thing we do know is that it begins with "\ ".1629 * Checking for 12 is just for sanity check -- any1630 * l10n of "\ No newline..." is at least that long.1631 */1632 case '\\':1633 if (len < 12 || memcmp(line, "\\ ", 2))1634 return -1;1635 break;1636 }1637 }1638 if (oldlines || newlines)1639 return -1;1640 if (!deleted && !added)1641 return -1;16421643 fragment->leading = leading;1644 fragment->trailing = trailing;16451646 /*1647 * If a fragment ends with an incomplete line, we failed to include1648 * it in the above loop because we hit oldlines == newlines == 01649 * before seeing it.1650 */1651 if (12 < size && !memcmp(line, "\\ ", 2))1652 offset += linelen(line, size);16531654 patch->lines_added += added;1655 patch->lines_deleted += deleted;16561657 if (0 < patch->is_new && oldlines)1658 return error(_("new file depends on old contents"));1659 if (0 < patch->is_delete && newlines)1660 return error(_("deleted file still has contents"));1661 return offset;1662}16631664/*1665 * We have seen "diff --git a/... b/..." header (or a traditional patch1666 * header). Read hunks that belong to this patch into fragments and hang1667 * them to the given patch structure.1668 *1669 * The (fragment->patch, fragment->size) pair points into the memory given1670 * by the caller, not a copy, when we return.1671 */1672static int parse_single_patch(struct apply_state *state,1673 const char *line,1674 unsigned long size,1675 struct patch *patch)1676{1677 unsigned long offset = 0;1678 unsigned long oldlines = 0, newlines = 0, context = 0;1679 struct fragment **fragp = &patch->fragments;16801681 while (size > 4 && !memcmp(line, "@@ -", 4)) {1682 struct fragment *fragment;1683 int len;16841685 fragment = xcalloc(1, sizeof(*fragment));1686 fragment->linenr = state_linenr;1687 len = parse_fragment(state, line, size, patch, fragment);1688 if (len <= 0)1689 die(_("corrupt patch at line %d"), state_linenr);1690 fragment->patch = line;1691 fragment->size = len;1692 oldlines += fragment->oldlines;1693 newlines += fragment->newlines;1694 context += fragment->leading + fragment->trailing;16951696 *fragp = fragment;1697 fragp = &fragment->next;16981699 offset += len;1700 line += len;1701 size -= len;1702 }17031704 /*1705 * If something was removed (i.e. we have old-lines) it cannot1706 * be creation, and if something was added it cannot be1707 * deletion. However, the reverse is not true; --unified=01708 * patches that only add are not necessarily creation even1709 * though they do not have any old lines, and ones that only1710 * delete are not necessarily deletion.1711 *1712 * Unfortunately, a real creation/deletion patch do _not_ have1713 * any context line by definition, so we cannot safely tell it1714 * apart with --unified=0 insanity. At least if the patch has1715 * more than one hunk it is not creation or deletion.1716 */1717 if (patch->is_new < 0 &&1718 (oldlines || (patch->fragments && patch->fragments->next)))1719 patch->is_new = 0;1720 if (patch->is_delete < 0 &&1721 (newlines || (patch->fragments && patch->fragments->next)))1722 patch->is_delete = 0;17231724 if (0 < patch->is_new && oldlines)1725 die(_("new file %s depends on old contents"), patch->new_name);1726 if (0 < patch->is_delete && newlines)1727 die(_("deleted file %s still has contents"), patch->old_name);1728 if (!patch->is_delete && !newlines && context)1729 fprintf_ln(stderr,1730 _("** warning: "1731 "file %s becomes empty but is not deleted"),1732 patch->new_name);17331734 return offset;1735}17361737static inline int metadata_changes(struct patch *patch)1738{1739 return patch->is_rename > 0 ||1740 patch->is_copy > 0 ||1741 patch->is_new > 0 ||1742 patch->is_delete ||1743 (patch->old_mode && patch->new_mode &&1744 patch->old_mode != patch->new_mode);1745}17461747static char *inflate_it(const void *data, unsigned long size,1748 unsigned long inflated_size)1749{1750 git_zstream stream;1751 void *out;1752 int st;17531754 memset(&stream, 0, sizeof(stream));17551756 stream.next_in = (unsigned char *)data;1757 stream.avail_in = size;1758 stream.next_out = out = xmalloc(inflated_size);1759 stream.avail_out = inflated_size;1760 git_inflate_init(&stream);1761 st = git_inflate(&stream, Z_FINISH);1762 git_inflate_end(&stream);1763 if ((st != Z_STREAM_END) || stream.total_out != inflated_size) {1764 free(out);1765 return NULL;1766 }1767 return out;1768}17691770/*1771 * Read a binary hunk and return a new fragment; fragment->patch1772 * points at an allocated memory that the caller must free, so1773 * it is marked as "->free_patch = 1".1774 */1775static struct fragment *parse_binary_hunk(char **buf_p,1776 unsigned long *sz_p,1777 int *status_p,1778 int *used_p)1779{1780 /*1781 * Expect a line that begins with binary patch method ("literal"1782 * or "delta"), followed by the length of data before deflating.1783 * a sequence of 'length-byte' followed by base-85 encoded data1784 * should follow, terminated by a newline.1785 *1786 * Each 5-byte sequence of base-85 encodes up to 4 bytes,1787 * and we would limit the patch line to 66 characters,1788 * so one line can fit up to 13 groups that would decode1789 * to 52 bytes max. The length byte 'A'-'Z' corresponds1790 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.1791 */1792 int llen, used;1793 unsigned long size = *sz_p;1794 char *buffer = *buf_p;1795 int patch_method;1796 unsigned long origlen;1797 char *data = NULL;1798 int hunk_size = 0;1799 struct fragment *frag;18001801 llen = linelen(buffer, size);1802 used = llen;18031804 *status_p = 0;18051806 if (starts_with(buffer, "delta ")) {1807 patch_method = BINARY_DELTA_DEFLATED;1808 origlen = strtoul(buffer + 6, NULL, 10);1809 }1810 else if (starts_with(buffer, "literal ")) {1811 patch_method = BINARY_LITERAL_DEFLATED;1812 origlen = strtoul(buffer + 8, NULL, 10);1813 }1814 else1815 return NULL;18161817 state_linenr++;1818 buffer += llen;1819 while (1) {1820 int byte_length, max_byte_length, newsize;1821 llen = linelen(buffer, size);1822 used += llen;1823 state_linenr++;1824 if (llen == 1) {1825 /* consume the blank line */1826 buffer++;1827 size--;1828 break;1829 }1830 /*1831 * Minimum line is "A00000\n" which is 7-byte long,1832 * and the line length must be multiple of 5 plus 2.1833 */1834 if ((llen < 7) || (llen-2) % 5)1835 goto corrupt;1836 max_byte_length = (llen - 2) / 5 * 4;1837 byte_length = *buffer;1838 if ('A' <= byte_length && byte_length <= 'Z')1839 byte_length = byte_length - 'A' + 1;1840 else if ('a' <= byte_length && byte_length <= 'z')1841 byte_length = byte_length - 'a' + 27;1842 else1843 goto corrupt;1844 /* if the input length was not multiple of 4, we would1845 * have filler at the end but the filler should never1846 * exceed 3 bytes1847 */1848 if (max_byte_length < byte_length ||1849 byte_length <= max_byte_length - 4)1850 goto corrupt;1851 newsize = hunk_size + byte_length;1852 data = xrealloc(data, newsize);1853 if (decode_85(data + hunk_size, buffer + 1, byte_length))1854 goto corrupt;1855 hunk_size = newsize;1856 buffer += llen;1857 size -= llen;1858 }18591860 frag = xcalloc(1, sizeof(*frag));1861 frag->patch = inflate_it(data, hunk_size, origlen);1862 frag->free_patch = 1;1863 if (!frag->patch)1864 goto corrupt;1865 free(data);1866 frag->size = origlen;1867 *buf_p = buffer;1868 *sz_p = size;1869 *used_p = used;1870 frag->binary_patch_method = patch_method;1871 return frag;18721873 corrupt:1874 free(data);1875 *status_p = -1;1876 error(_("corrupt binary patch at line %d: %.*s"),1877 state_linenr-1, llen-1, buffer);1878 return NULL;1879}18801881/*1882 * Returns:1883 * -1 in case of error,1884 * the length of the parsed binary patch otherwise1885 */1886static int parse_binary(char *buffer, unsigned long size, struct patch *patch)1887{1888 /*1889 * We have read "GIT binary patch\n"; what follows is a line1890 * that says the patch method (currently, either "literal" or1891 * "delta") and the length of data before deflating; a1892 * sequence of 'length-byte' followed by base-85 encoded data1893 * follows.1894 *1895 * When a binary patch is reversible, there is another binary1896 * hunk in the same format, starting with patch method (either1897 * "literal" or "delta") with the length of data, and a sequence1898 * of length-byte + base-85 encoded data, terminated with another1899 * empty line. This data, when applied to the postimage, produces1900 * the preimage.1901 */1902 struct fragment *forward;1903 struct fragment *reverse;1904 int status;1905 int used, used_1;19061907 forward = parse_binary_hunk(&buffer, &size, &status, &used);1908 if (!forward && !status)1909 /* there has to be one hunk (forward hunk) */1910 return error(_("unrecognized binary patch at line %d"), state_linenr-1);1911 if (status)1912 /* otherwise we already gave an error message */1913 return status;19141915 reverse = parse_binary_hunk(&buffer, &size, &status, &used_1);1916 if (reverse)1917 used += used_1;1918 else if (status) {1919 /*1920 * Not having reverse hunk is not an error, but having1921 * a corrupt reverse hunk is.1922 */1923 free((void*) forward->patch);1924 free(forward);1925 return status;1926 }1927 forward->next = reverse;1928 patch->fragments = forward;1929 patch->is_binary = 1;1930 return used;1931}19321933static void prefix_one(struct apply_state *state, char **name)1934{1935 char *old_name = *name;1936 if (!old_name)1937 return;1938 *name = xstrdup(prefix_filename(state->prefix, state->prefix_length, *name));1939 free(old_name);1940}19411942static void prefix_patch(struct apply_state *state, struct patch *p)1943{1944 if (!state->prefix || p->is_toplevel_relative)1945 return;1946 prefix_one(state, &p->new_name);1947 prefix_one(state, &p->old_name);1948}19491950/*1951 * include/exclude1952 */19531954static struct string_list limit_by_name;1955static int has_include;1956static void add_name_limit(const char *name, int exclude)1957{1958 struct string_list_item *it;19591960 it = string_list_append(&limit_by_name, name);1961 it->util = exclude ? NULL : (void *) 1;1962}19631964static int use_patch(struct apply_state *state, struct patch *p)1965{1966 const char *pathname = p->new_name ? p->new_name : p->old_name;1967 int i;19681969 /* Paths outside are not touched regardless of "--include" */1970 if (0 < state->prefix_length) {1971 int pathlen = strlen(pathname);1972 if (pathlen <= state->prefix_length ||1973 memcmp(state->prefix, pathname, state->prefix_length))1974 return 0;1975 }19761977 /* See if it matches any of exclude/include rule */1978 for (i = 0; i < limit_by_name.nr; i++) {1979 struct string_list_item *it = &limit_by_name.items[i];1980 if (!wildmatch(it->string, pathname, 0, NULL))1981 return (it->util != NULL);1982 }19831984 /*1985 * If we had any include, a path that does not match any rule is1986 * not used. Otherwise, we saw bunch of exclude rules (or none)1987 * and such a path is used.1988 */1989 return !has_include;1990}199119921993/*1994 * Read the patch text in "buffer" that extends for "size" bytes; stop1995 * reading after seeing a single patch (i.e. changes to a single file).1996 * Create fragments (i.e. patch hunks) and hang them to the given patch.1997 * Return the number of bytes consumed, so that the caller can call us1998 * again for the next patch.1999 */2000static int parse_chunk(struct apply_state *state, char *buffer, unsigned long size, struct patch *patch)2001{2002 int hdrsize, patchsize;2003 int offset = find_header(state, buffer, size, &hdrsize, patch);20042005 if (offset < 0)2006 return offset;20072008 prefix_patch(state, patch);20092010 if (!use_patch(state, patch))2011 patch->ws_rule = 0;2012 else2013 patch->ws_rule = whitespace_rule(patch->new_name2014 ? patch->new_name2015 : patch->old_name);20162017 patchsize = parse_single_patch(state,2018 buffer + offset + hdrsize,2019 size - offset - hdrsize,2020 patch);20212022 if (!patchsize) {2023 static const char git_binary[] = "GIT binary patch\n";2024 int hd = hdrsize + offset;2025 unsigned long llen = linelen(buffer + hd, size - hd);20262027 if (llen == sizeof(git_binary) - 1 &&2028 !memcmp(git_binary, buffer + hd, llen)) {2029 int used;2030 state_linenr++;2031 used = parse_binary(buffer + hd + llen,2032 size - hd - llen, patch);2033 if (used < 0)2034 return -1;2035 if (used)2036 patchsize = used + llen;2037 else2038 patchsize = 0;2039 }2040 else if (!memcmp(" differ\n", buffer + hd + llen - 8, 8)) {2041 static const char *binhdr[] = {2042 "Binary files ",2043 "Files ",2044 NULL,2045 };2046 int i;2047 for (i = 0; binhdr[i]; i++) {2048 int len = strlen(binhdr[i]);2049 if (len < size - hd &&2050 !memcmp(binhdr[i], buffer + hd, len)) {2051 state_linenr++;2052 patch->is_binary = 1;2053 patchsize = llen;2054 break;2055 }2056 }2057 }20582059 /* Empty patch cannot be applied if it is a text patch2060 * without metadata change. A binary patch appears2061 * empty to us here.2062 */2063 if ((apply || state->check) &&2064 (!patch->is_binary && !metadata_changes(patch)))2065 die(_("patch with only garbage at line %d"), state_linenr);2066 }20672068 return offset + hdrsize + patchsize;2069}20702071#define swap(a,b) myswap((a),(b),sizeof(a))20722073#define myswap(a, b, size) do { \2074 unsigned char mytmp[size]; \2075 memcpy(mytmp, &a, size); \2076 memcpy(&a, &b, size); \2077 memcpy(&b, mytmp, size); \2078} while (0)20792080static void reverse_patches(struct patch *p)2081{2082 for (; p; p = p->next) {2083 struct fragment *frag = p->fragments;20842085 swap(p->new_name, p->old_name);2086 swap(p->new_mode, p->old_mode);2087 swap(p->is_new, p->is_delete);2088 swap(p->lines_added, p->lines_deleted);2089 swap(p->old_sha1_prefix, p->new_sha1_prefix);20902091 for (; frag; frag = frag->next) {2092 swap(frag->newpos, frag->oldpos);2093 swap(frag->newlines, frag->oldlines);2094 }2095 }2096}20972098static const char pluses[] =2099"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";2100static const char minuses[]=2101"----------------------------------------------------------------------";21022103static void show_stats(struct patch *patch)2104{2105 struct strbuf qname = STRBUF_INIT;2106 char *cp = patch->new_name ? patch->new_name : patch->old_name;2107 int max, add, del;21082109 quote_c_style(cp, &qname, NULL, 0);21102111 /*2112 * "scale" the filename2113 */2114 max = max_len;2115 if (max > 50)2116 max = 50;21172118 if (qname.len > max) {2119 cp = strchr(qname.buf + qname.len + 3 - max, '/');2120 if (!cp)2121 cp = qname.buf + qname.len + 3 - max;2122 strbuf_splice(&qname, 0, cp - qname.buf, "...", 3);2123 }21242125 if (patch->is_binary) {2126 printf(" %-*s | Bin\n", max, qname.buf);2127 strbuf_release(&qname);2128 return;2129 }21302131 printf(" %-*s |", max, qname.buf);2132 strbuf_release(&qname);21332134 /*2135 * scale the add/delete2136 */2137 max = max + max_change > 70 ? 70 - max : max_change;2138 add = patch->lines_added;2139 del = patch->lines_deleted;21402141 if (max_change > 0) {2142 int total = ((add + del) * max + max_change / 2) / max_change;2143 add = (add * max + max_change / 2) / max_change;2144 del = total - add;2145 }2146 printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,2147 add, pluses, del, minuses);2148}21492150static int read_old_data(struct stat *st, const char *path, struct strbuf *buf)2151{2152 switch (st->st_mode & S_IFMT) {2153 case S_IFLNK:2154 if (strbuf_readlink(buf, path, st->st_size) < 0)2155 return error(_("unable to read symlink %s"), path);2156 return 0;2157 case S_IFREG:2158 if (strbuf_read_file(buf, path, st->st_size) != st->st_size)2159 return error(_("unable to open or read %s"), path);2160 convert_to_git(path, buf->buf, buf->len, buf, 0);2161 return 0;2162 default:2163 return -1;2164 }2165}21662167/*2168 * Update the preimage, and the common lines in postimage,2169 * from buffer buf of length len. If postlen is 0 the postimage2170 * is updated in place, otherwise it's updated on a new buffer2171 * of length postlen2172 */21732174static void update_pre_post_images(struct image *preimage,2175 struct image *postimage,2176 char *buf,2177 size_t len, size_t postlen)2178{2179 int i, ctx, reduced;2180 char *new, *old, *fixed;2181 struct image fixed_preimage;21822183 /*2184 * Update the preimage with whitespace fixes. Note that we2185 * are not losing preimage->buf -- apply_one_fragment() will2186 * free "oldlines".2187 */2188 prepare_image(&fixed_preimage, buf, len, 1);2189 assert(postlen2190 ? fixed_preimage.nr == preimage->nr2191 : fixed_preimage.nr <= preimage->nr);2192 for (i = 0; i < fixed_preimage.nr; i++)2193 fixed_preimage.line[i].flag = preimage->line[i].flag;2194 free(preimage->line_allocated);2195 *preimage = fixed_preimage;21962197 /*2198 * Adjust the common context lines in postimage. This can be2199 * done in-place when we are shrinking it with whitespace2200 * fixing, but needs a new buffer when ignoring whitespace or2201 * expanding leading tabs to spaces.2202 *2203 * We trust the caller to tell us if the update can be done2204 * in place (postlen==0) or not.2205 */2206 old = postimage->buf;2207 if (postlen)2208 new = postimage->buf = xmalloc(postlen);2209 else2210 new = old;2211 fixed = preimage->buf;22122213 for (i = reduced = ctx = 0; i < postimage->nr; i++) {2214 size_t l_len = postimage->line[i].len;2215 if (!(postimage->line[i].flag & LINE_COMMON)) {2216 /* an added line -- no counterparts in preimage */2217 memmove(new, old, l_len);2218 old += l_len;2219 new += l_len;2220 continue;2221 }22222223 /* a common context -- skip it in the original postimage */2224 old += l_len;22252226 /* and find the corresponding one in the fixed preimage */2227 while (ctx < preimage->nr &&2228 !(preimage->line[ctx].flag & LINE_COMMON)) {2229 fixed += preimage->line[ctx].len;2230 ctx++;2231 }22322233 /*2234 * preimage is expected to run out, if the caller2235 * fixed addition of trailing blank lines.2236 */2237 if (preimage->nr <= ctx) {2238 reduced++;2239 continue;2240 }22412242 /* and copy it in, while fixing the line length */2243 l_len = preimage->line[ctx].len;2244 memcpy(new, fixed, l_len);2245 new += l_len;2246 fixed += l_len;2247 postimage->line[i].len = l_len;2248 ctx++;2249 }22502251 if (postlen2252 ? postlen < new - postimage->buf2253 : postimage->len < new - postimage->buf)2254 die("BUG: caller miscounted postlen: asked %d, orig = %d, used = %d",2255 (int)postlen, (int) postimage->len, (int)(new - postimage->buf));22562257 /* Fix the length of the whole thing */2258 postimage->len = new - postimage->buf;2259 postimage->nr -= reduced;2260}22612262static int line_by_line_fuzzy_match(struct image *img,2263 struct image *preimage,2264 struct image *postimage,2265 unsigned long try,2266 int try_lno,2267 int preimage_limit)2268{2269 int i;2270 size_t imgoff = 0;2271 size_t preoff = 0;2272 size_t postlen = postimage->len;2273 size_t extra_chars;2274 char *buf;2275 char *preimage_eof;2276 char *preimage_end;2277 struct strbuf fixed;2278 char *fixed_buf;2279 size_t fixed_len;22802281 for (i = 0; i < preimage_limit; i++) {2282 size_t prelen = preimage->line[i].len;2283 size_t imglen = img->line[try_lno+i].len;22842285 if (!fuzzy_matchlines(img->buf + try + imgoff, imglen,2286 preimage->buf + preoff, prelen))2287 return 0;2288 if (preimage->line[i].flag & LINE_COMMON)2289 postlen += imglen - prelen;2290 imgoff += imglen;2291 preoff += prelen;2292 }22932294 /*2295 * Ok, the preimage matches with whitespace fuzz.2296 *2297 * imgoff now holds the true length of the target that2298 * matches the preimage before the end of the file.2299 *2300 * Count the number of characters in the preimage that fall2301 * beyond the end of the file and make sure that all of them2302 * are whitespace characters. (This can only happen if2303 * we are removing blank lines at the end of the file.)2304 */2305 buf = preimage_eof = preimage->buf + preoff;2306 for ( ; i < preimage->nr; i++)2307 preoff += preimage->line[i].len;2308 preimage_end = preimage->buf + preoff;2309 for ( ; buf < preimage_end; buf++)2310 if (!isspace(*buf))2311 return 0;23122313 /*2314 * Update the preimage and the common postimage context2315 * lines to use the same whitespace as the target.2316 * If whitespace is missing in the target (i.e.2317 * if the preimage extends beyond the end of the file),2318 * use the whitespace from the preimage.2319 */2320 extra_chars = preimage_end - preimage_eof;2321 strbuf_init(&fixed, imgoff + extra_chars);2322 strbuf_add(&fixed, img->buf + try, imgoff);2323 strbuf_add(&fixed, preimage_eof, extra_chars);2324 fixed_buf = strbuf_detach(&fixed, &fixed_len);2325 update_pre_post_images(preimage, postimage,2326 fixed_buf, fixed_len, postlen);2327 return 1;2328}23292330static int match_fragment(struct image *img,2331 struct image *preimage,2332 struct image *postimage,2333 unsigned long try,2334 int try_lno,2335 unsigned ws_rule,2336 int match_beginning, int match_end)2337{2338 int i;2339 char *fixed_buf, *buf, *orig, *target;2340 struct strbuf fixed;2341 size_t fixed_len, postlen;2342 int preimage_limit;23432344 if (preimage->nr + try_lno <= img->nr) {2345 /*2346 * The hunk falls within the boundaries of img.2347 */2348 preimage_limit = preimage->nr;2349 if (match_end && (preimage->nr + try_lno != img->nr))2350 return 0;2351 } else if (ws_error_action == correct_ws_error &&2352 (ws_rule & WS_BLANK_AT_EOF)) {2353 /*2354 * This hunk extends beyond the end of img, and we are2355 * removing blank lines at the end of the file. This2356 * many lines from the beginning of the preimage must2357 * match with img, and the remainder of the preimage2358 * must be blank.2359 */2360 preimage_limit = img->nr - try_lno;2361 } else {2362 /*2363 * The hunk extends beyond the end of the img and2364 * we are not removing blanks at the end, so we2365 * should reject the hunk at this position.2366 */2367 return 0;2368 }23692370 if (match_beginning && try_lno)2371 return 0;23722373 /* Quick hash check */2374 for (i = 0; i < preimage_limit; i++)2375 if ((img->line[try_lno + i].flag & LINE_PATCHED) ||2376 (preimage->line[i].hash != img->line[try_lno + i].hash))2377 return 0;23782379 if (preimage_limit == preimage->nr) {2380 /*2381 * Do we have an exact match? If we were told to match2382 * at the end, size must be exactly at try+fragsize,2383 * otherwise try+fragsize must be still within the preimage,2384 * and either case, the old piece should match the preimage2385 * exactly.2386 */2387 if ((match_end2388 ? (try + preimage->len == img->len)2389 : (try + preimage->len <= img->len)) &&2390 !memcmp(img->buf + try, preimage->buf, preimage->len))2391 return 1;2392 } else {2393 /*2394 * The preimage extends beyond the end of img, so2395 * there cannot be an exact match.2396 *2397 * There must be one non-blank context line that match2398 * a line before the end of img.2399 */2400 char *buf_end;24012402 buf = preimage->buf;2403 buf_end = buf;2404 for (i = 0; i < preimage_limit; i++)2405 buf_end += preimage->line[i].len;24062407 for ( ; buf < buf_end; buf++)2408 if (!isspace(*buf))2409 break;2410 if (buf == buf_end)2411 return 0;2412 }24132414 /*2415 * No exact match. If we are ignoring whitespace, run a line-by-line2416 * fuzzy matching. We collect all the line length information because2417 * we need it to adjust whitespace if we match.2418 */2419 if (ws_ignore_action == ignore_ws_change)2420 return line_by_line_fuzzy_match(img, preimage, postimage,2421 try, try_lno, preimage_limit);24222423 if (ws_error_action != correct_ws_error)2424 return 0;24252426 /*2427 * The hunk does not apply byte-by-byte, but the hash says2428 * it might with whitespace fuzz. We weren't asked to2429 * ignore whitespace, we were asked to correct whitespace2430 * errors, so let's try matching after whitespace correction.2431 *2432 * While checking the preimage against the target, whitespace2433 * errors in both fixed, we count how large the corresponding2434 * postimage needs to be. The postimage prepared by2435 * apply_one_fragment() has whitespace errors fixed on added2436 * lines already, but the common lines were propagated as-is,2437 * which may become longer when their whitespace errors are2438 * fixed.2439 */24402441 /* First count added lines in postimage */2442 postlen = 0;2443 for (i = 0; i < postimage->nr; i++) {2444 if (!(postimage->line[i].flag & LINE_COMMON))2445 postlen += postimage->line[i].len;2446 }24472448 /*2449 * The preimage may extend beyond the end of the file,2450 * but in this loop we will only handle the part of the2451 * preimage that falls within the file.2452 */2453 strbuf_init(&fixed, preimage->len + 1);2454 orig = preimage->buf;2455 target = img->buf + try;2456 for (i = 0; i < preimage_limit; i++) {2457 size_t oldlen = preimage->line[i].len;2458 size_t tgtlen = img->line[try_lno + i].len;2459 size_t fixstart = fixed.len;2460 struct strbuf tgtfix;2461 int match;24622463 /* Try fixing the line in the preimage */2464 ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);24652466 /* Try fixing the line in the target */2467 strbuf_init(&tgtfix, tgtlen);2468 ws_fix_copy(&tgtfix, target, tgtlen, ws_rule, NULL);24692470 /*2471 * If they match, either the preimage was based on2472 * a version before our tree fixed whitespace breakage,2473 * or we are lacking a whitespace-fix patch the tree2474 * the preimage was based on already had (i.e. target2475 * has whitespace breakage, the preimage doesn't).2476 * In either case, we are fixing the whitespace breakages2477 * so we might as well take the fix together with their2478 * real change.2479 */2480 match = (tgtfix.len == fixed.len - fixstart &&2481 !memcmp(tgtfix.buf, fixed.buf + fixstart,2482 fixed.len - fixstart));24832484 /* Add the length if this is common with the postimage */2485 if (preimage->line[i].flag & LINE_COMMON)2486 postlen += tgtfix.len;24872488 strbuf_release(&tgtfix);2489 if (!match)2490 goto unmatch_exit;24912492 orig += oldlen;2493 target += tgtlen;2494 }249524962497 /*2498 * Now handle the lines in the preimage that falls beyond the2499 * end of the file (if any). They will only match if they are2500 * empty or only contain whitespace (if WS_BLANK_AT_EOL is2501 * false).2502 */2503 for ( ; i < preimage->nr; i++) {2504 size_t fixstart = fixed.len; /* start of the fixed preimage */2505 size_t oldlen = preimage->line[i].len;2506 int j;25072508 /* Try fixing the line in the preimage */2509 ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);25102511 for (j = fixstart; j < fixed.len; j++)2512 if (!isspace(fixed.buf[j]))2513 goto unmatch_exit;25142515 orig += oldlen;2516 }25172518 /*2519 * Yes, the preimage is based on an older version that still2520 * has whitespace breakages unfixed, and fixing them makes the2521 * hunk match. Update the context lines in the postimage.2522 */2523 fixed_buf = strbuf_detach(&fixed, &fixed_len);2524 if (postlen < postimage->len)2525 postlen = 0;2526 update_pre_post_images(preimage, postimage,2527 fixed_buf, fixed_len, postlen);2528 return 1;25292530 unmatch_exit:2531 strbuf_release(&fixed);2532 return 0;2533}25342535static int find_pos(struct image *img,2536 struct image *preimage,2537 struct image *postimage,2538 int line,2539 unsigned ws_rule,2540 int match_beginning, int match_end)2541{2542 int i;2543 unsigned long backwards, forwards, try;2544 int backwards_lno, forwards_lno, try_lno;25452546 /*2547 * If match_beginning or match_end is specified, there is no2548 * point starting from a wrong line that will never match and2549 * wander around and wait for a match at the specified end.2550 */2551 if (match_beginning)2552 line = 0;2553 else if (match_end)2554 line = img->nr - preimage->nr;25552556 /*2557 * Because the comparison is unsigned, the following test2558 * will also take care of a negative line number that can2559 * result when match_end and preimage is larger than the target.2560 */2561 if ((size_t) line > img->nr)2562 line = img->nr;25632564 try = 0;2565 for (i = 0; i < line; i++)2566 try += img->line[i].len;25672568 /*2569 * There's probably some smart way to do this, but I'll leave2570 * that to the smart and beautiful people. I'm simple and stupid.2571 */2572 backwards = try;2573 backwards_lno = line;2574 forwards = try;2575 forwards_lno = line;2576 try_lno = line;25772578 for (i = 0; ; i++) {2579 if (match_fragment(img, preimage, postimage,2580 try, try_lno, ws_rule,2581 match_beginning, match_end))2582 return try_lno;25832584 again:2585 if (backwards_lno == 0 && forwards_lno == img->nr)2586 break;25872588 if (i & 1) {2589 if (backwards_lno == 0) {2590 i++;2591 goto again;2592 }2593 backwards_lno--;2594 backwards -= img->line[backwards_lno].len;2595 try = backwards;2596 try_lno = backwards_lno;2597 } else {2598 if (forwards_lno == img->nr) {2599 i++;2600 goto again;2601 }2602 forwards += img->line[forwards_lno].len;2603 forwards_lno++;2604 try = forwards;2605 try_lno = forwards_lno;2606 }26072608 }2609 return -1;2610}26112612static void remove_first_line(struct image *img)2613{2614 img->buf += img->line[0].len;2615 img->len -= img->line[0].len;2616 img->line++;2617 img->nr--;2618}26192620static void remove_last_line(struct image *img)2621{2622 img->len -= img->line[--img->nr].len;2623}26242625/*2626 * The change from "preimage" and "postimage" has been found to2627 * apply at applied_pos (counts in line numbers) in "img".2628 * Update "img" to remove "preimage" and replace it with "postimage".2629 */2630static void update_image(struct image *img,2631 int applied_pos,2632 struct image *preimage,2633 struct image *postimage)2634{2635 /*2636 * remove the copy of preimage at offset in img2637 * and replace it with postimage2638 */2639 int i, nr;2640 size_t remove_count, insert_count, applied_at = 0;2641 char *result;2642 int preimage_limit;26432644 /*2645 * If we are removing blank lines at the end of img,2646 * the preimage may extend beyond the end.2647 * If that is the case, we must be careful only to2648 * remove the part of the preimage that falls within2649 * the boundaries of img. Initialize preimage_limit2650 * to the number of lines in the preimage that falls2651 * within the boundaries.2652 */2653 preimage_limit = preimage->nr;2654 if (preimage_limit > img->nr - applied_pos)2655 preimage_limit = img->nr - applied_pos;26562657 for (i = 0; i < applied_pos; i++)2658 applied_at += img->line[i].len;26592660 remove_count = 0;2661 for (i = 0; i < preimage_limit; i++)2662 remove_count += img->line[applied_pos + i].len;2663 insert_count = postimage->len;26642665 /* Adjust the contents */2666 result = xmalloc(st_add3(st_sub(img->len, remove_count), insert_count, 1));2667 memcpy(result, img->buf, applied_at);2668 memcpy(result + applied_at, postimage->buf, postimage->len);2669 memcpy(result + applied_at + postimage->len,2670 img->buf + (applied_at + remove_count),2671 img->len - (applied_at + remove_count));2672 free(img->buf);2673 img->buf = result;2674 img->len += insert_count - remove_count;2675 result[img->len] = '\0';26762677 /* Adjust the line table */2678 nr = img->nr + postimage->nr - preimage_limit;2679 if (preimage_limit < postimage->nr) {2680 /*2681 * NOTE: this knows that we never call remove_first_line()2682 * on anything other than pre/post image.2683 */2684 REALLOC_ARRAY(img->line, nr);2685 img->line_allocated = img->line;2686 }2687 if (preimage_limit != postimage->nr)2688 memmove(img->line + applied_pos + postimage->nr,2689 img->line + applied_pos + preimage_limit,2690 (img->nr - (applied_pos + preimage_limit)) *2691 sizeof(*img->line));2692 memcpy(img->line + applied_pos,2693 postimage->line,2694 postimage->nr * sizeof(*img->line));2695 if (!allow_overlap)2696 for (i = 0; i < postimage->nr; i++)2697 img->line[applied_pos + i].flag |= LINE_PATCHED;2698 img->nr = nr;2699}27002701/*2702 * Use the patch-hunk text in "frag" to prepare two images (preimage and2703 * postimage) for the hunk. Find lines that match "preimage" in "img" and2704 * replace the part of "img" with "postimage" text.2705 */2706static int apply_one_fragment(struct apply_state *state,2707 struct image *img, struct fragment *frag,2708 int inaccurate_eof, unsigned ws_rule,2709 int nth_fragment)2710{2711 int match_beginning, match_end;2712 const char *patch = frag->patch;2713 int size = frag->size;2714 char *old, *oldlines;2715 struct strbuf newlines;2716 int new_blank_lines_at_end = 0;2717 int found_new_blank_lines_at_end = 0;2718 int hunk_linenr = frag->linenr;2719 unsigned long leading, trailing;2720 int pos, applied_pos;2721 struct image preimage;2722 struct image postimage;27232724 memset(&preimage, 0, sizeof(preimage));2725 memset(&postimage, 0, sizeof(postimage));2726 oldlines = xmalloc(size);2727 strbuf_init(&newlines, size);27282729 old = oldlines;2730 while (size > 0) {2731 char first;2732 int len = linelen(patch, size);2733 int plen;2734 int added_blank_line = 0;2735 int is_blank_context = 0;2736 size_t start;27372738 if (!len)2739 break;27402741 /*2742 * "plen" is how much of the line we should use for2743 * the actual patch data. Normally we just remove the2744 * first character on the line, but if the line is2745 * followed by "\ No newline", then we also remove the2746 * last one (which is the newline, of course).2747 */2748 plen = len - 1;2749 if (len < size && patch[len] == '\\')2750 plen--;2751 first = *patch;2752 if (state->apply_in_reverse) {2753 if (first == '-')2754 first = '+';2755 else if (first == '+')2756 first = '-';2757 }27582759 switch (first) {2760 case '\n':2761 /* Newer GNU diff, empty context line */2762 if (plen < 0)2763 /* ... followed by '\No newline'; nothing */2764 break;2765 *old++ = '\n';2766 strbuf_addch(&newlines, '\n');2767 add_line_info(&preimage, "\n", 1, LINE_COMMON);2768 add_line_info(&postimage, "\n", 1, LINE_COMMON);2769 is_blank_context = 1;2770 break;2771 case ' ':2772 if (plen && (ws_rule & WS_BLANK_AT_EOF) &&2773 ws_blank_line(patch + 1, plen, ws_rule))2774 is_blank_context = 1;2775 case '-':2776 memcpy(old, patch + 1, plen);2777 add_line_info(&preimage, old, plen,2778 (first == ' ' ? LINE_COMMON : 0));2779 old += plen;2780 if (first == '-')2781 break;2782 /* Fall-through for ' ' */2783 case '+':2784 /* --no-add does not add new lines */2785 if (first == '+' && no_add)2786 break;27872788 start = newlines.len;2789 if (first != '+' ||2790 !whitespace_error ||2791 ws_error_action != correct_ws_error) {2792 strbuf_add(&newlines, patch + 1, plen);2793 }2794 else {2795 ws_fix_copy(&newlines, patch + 1, plen, ws_rule, &applied_after_fixing_ws);2796 }2797 add_line_info(&postimage, newlines.buf + start, newlines.len - start,2798 (first == '+' ? 0 : LINE_COMMON));2799 if (first == '+' &&2800 (ws_rule & WS_BLANK_AT_EOF) &&2801 ws_blank_line(patch + 1, plen, ws_rule))2802 added_blank_line = 1;2803 break;2804 case '@': case '\\':2805 /* Ignore it, we already handled it */2806 break;2807 default:2808 if (apply_verbosely)2809 error(_("invalid start of line: '%c'"), first);2810 applied_pos = -1;2811 goto out;2812 }2813 if (added_blank_line) {2814 if (!new_blank_lines_at_end)2815 found_new_blank_lines_at_end = hunk_linenr;2816 new_blank_lines_at_end++;2817 }2818 else if (is_blank_context)2819 ;2820 else2821 new_blank_lines_at_end = 0;2822 patch += len;2823 size -= len;2824 hunk_linenr++;2825 }2826 if (inaccurate_eof &&2827 old > oldlines && old[-1] == '\n' &&2828 newlines.len > 0 && newlines.buf[newlines.len - 1] == '\n') {2829 old--;2830 strbuf_setlen(&newlines, newlines.len - 1);2831 }28322833 leading = frag->leading;2834 trailing = frag->trailing;28352836 /*2837 * A hunk to change lines at the beginning would begin with2838 * @@ -1,L +N,M @@2839 * but we need to be careful. -U0 that inserts before the second2840 * line also has this pattern.2841 *2842 * And a hunk to add to an empty file would begin with2843 * @@ -0,0 +N,M @@2844 *2845 * In other words, a hunk that is (frag->oldpos <= 1) with or2846 * without leading context must match at the beginning.2847 */2848 match_beginning = (!frag->oldpos ||2849 (frag->oldpos == 1 && !state->unidiff_zero));28502851 /*2852 * A hunk without trailing lines must match at the end.2853 * However, we simply cannot tell if a hunk must match end2854 * from the lack of trailing lines if the patch was generated2855 * with unidiff without any context.2856 */2857 match_end = !state->unidiff_zero && !trailing;28582859 pos = frag->newpos ? (frag->newpos - 1) : 0;2860 preimage.buf = oldlines;2861 preimage.len = old - oldlines;2862 postimage.buf = newlines.buf;2863 postimage.len = newlines.len;2864 preimage.line = preimage.line_allocated;2865 postimage.line = postimage.line_allocated;28662867 for (;;) {28682869 applied_pos = find_pos(img, &preimage, &postimage, pos,2870 ws_rule, match_beginning, match_end);28712872 if (applied_pos >= 0)2873 break;28742875 /* Am I at my context limits? */2876 if ((leading <= p_context) && (trailing <= p_context))2877 break;2878 if (match_beginning || match_end) {2879 match_beginning = match_end = 0;2880 continue;2881 }28822883 /*2884 * Reduce the number of context lines; reduce both2885 * leading and trailing if they are equal otherwise2886 * just reduce the larger context.2887 */2888 if (leading >= trailing) {2889 remove_first_line(&preimage);2890 remove_first_line(&postimage);2891 pos--;2892 leading--;2893 }2894 if (trailing > leading) {2895 remove_last_line(&preimage);2896 remove_last_line(&postimage);2897 trailing--;2898 }2899 }29002901 if (applied_pos >= 0) {2902 if (new_blank_lines_at_end &&2903 preimage.nr + applied_pos >= img->nr &&2904 (ws_rule & WS_BLANK_AT_EOF) &&2905 ws_error_action != nowarn_ws_error) {2906 record_ws_error(WS_BLANK_AT_EOF, "+", 1,2907 found_new_blank_lines_at_end);2908 if (ws_error_action == correct_ws_error) {2909 while (new_blank_lines_at_end--)2910 remove_last_line(&postimage);2911 }2912 /*2913 * We would want to prevent write_out_results()2914 * from taking place in apply_patch() that follows2915 * the callchain led us here, which is:2916 * apply_patch->check_patch_list->check_patch->2917 * apply_data->apply_fragments->apply_one_fragment2918 */2919 if (ws_error_action == die_on_ws_error)2920 apply = 0;2921 }29222923 if (apply_verbosely && applied_pos != pos) {2924 int offset = applied_pos - pos;2925 if (state->apply_in_reverse)2926 offset = 0 - offset;2927 fprintf_ln(stderr,2928 Q_("Hunk #%d succeeded at %d (offset %d line).",2929 "Hunk #%d succeeded at %d (offset %d lines).",2930 offset),2931 nth_fragment, applied_pos + 1, offset);2932 }29332934 /*2935 * Warn if it was necessary to reduce the number2936 * of context lines.2937 */2938 if ((leading != frag->leading) ||2939 (trailing != frag->trailing))2940 fprintf_ln(stderr, _("Context reduced to (%ld/%ld)"2941 " to apply fragment at %d"),2942 leading, trailing, applied_pos+1);2943 update_image(img, applied_pos, &preimage, &postimage);2944 } else {2945 if (apply_verbosely)2946 error(_("while searching for:\n%.*s"),2947 (int)(old - oldlines), oldlines);2948 }29492950out:2951 free(oldlines);2952 strbuf_release(&newlines);2953 free(preimage.line_allocated);2954 free(postimage.line_allocated);29552956 return (applied_pos < 0);2957}29582959static int apply_binary_fragment(struct apply_state *state,2960 struct image *img,2961 struct patch *patch)2962{2963 struct fragment *fragment = patch->fragments;2964 unsigned long len;2965 void *dst;29662967 if (!fragment)2968 return error(_("missing binary patch data for '%s'"),2969 patch->new_name ?2970 patch->new_name :2971 patch->old_name);29722973 /* Binary patch is irreversible without the optional second hunk */2974 if (state->apply_in_reverse) {2975 if (!fragment->next)2976 return error("cannot reverse-apply a binary patch "2977 "without the reverse hunk to '%s'",2978 patch->new_name2979 ? patch->new_name : patch->old_name);2980 fragment = fragment->next;2981 }2982 switch (fragment->binary_patch_method) {2983 case BINARY_DELTA_DEFLATED:2984 dst = patch_delta(img->buf, img->len, fragment->patch,2985 fragment->size, &len);2986 if (!dst)2987 return -1;2988 clear_image(img);2989 img->buf = dst;2990 img->len = len;2991 return 0;2992 case BINARY_LITERAL_DEFLATED:2993 clear_image(img);2994 img->len = fragment->size;2995 img->buf = xmemdupz(fragment->patch, img->len);2996 return 0;2997 }2998 return -1;2999}30003001/*3002 * Replace "img" with the result of applying the binary patch.3003 * The binary patch data itself in patch->fragment is still kept3004 * but the preimage prepared by the caller in "img" is freed here3005 * or in the helper function apply_binary_fragment() this calls.3006 */3007static int apply_binary(struct apply_state *state,3008 struct image *img,3009 struct patch *patch)3010{3011 const char *name = patch->old_name ? patch->old_name : patch->new_name;3012 unsigned char sha1[20];30133014 /*3015 * For safety, we require patch index line to contain3016 * full 40-byte textual SHA1 for old and new, at least for now.3017 */3018 if (strlen(patch->old_sha1_prefix) != 40 ||3019 strlen(patch->new_sha1_prefix) != 40 ||3020 get_sha1_hex(patch->old_sha1_prefix, sha1) ||3021 get_sha1_hex(patch->new_sha1_prefix, sha1))3022 return error("cannot apply binary patch to '%s' "3023 "without full index line", name);30243025 if (patch->old_name) {3026 /*3027 * See if the old one matches what the patch3028 * applies to.3029 */3030 hash_sha1_file(img->buf, img->len, blob_type, sha1);3031 if (strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))3032 return error("the patch applies to '%s' (%s), "3033 "which does not match the "3034 "current contents.",3035 name, sha1_to_hex(sha1));3036 }3037 else {3038 /* Otherwise, the old one must be empty. */3039 if (img->len)3040 return error("the patch applies to an empty "3041 "'%s' but it is not empty", name);3042 }30433044 get_sha1_hex(patch->new_sha1_prefix, sha1);3045 if (is_null_sha1(sha1)) {3046 clear_image(img);3047 return 0; /* deletion patch */3048 }30493050 if (has_sha1_file(sha1)) {3051 /* We already have the postimage */3052 enum object_type type;3053 unsigned long size;3054 char *result;30553056 result = read_sha1_file(sha1, &type, &size);3057 if (!result)3058 return error("the necessary postimage %s for "3059 "'%s' cannot be read",3060 patch->new_sha1_prefix, name);3061 clear_image(img);3062 img->buf = result;3063 img->len = size;3064 } else {3065 /*3066 * We have verified buf matches the preimage;3067 * apply the patch data to it, which is stored3068 * in the patch->fragments->{patch,size}.3069 */3070 if (apply_binary_fragment(state, img, patch))3071 return error(_("binary patch does not apply to '%s'"),3072 name);30733074 /* verify that the result matches */3075 hash_sha1_file(img->buf, img->len, blob_type, sha1);3076 if (strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))3077 return error(_("binary patch to '%s' creates incorrect result (expecting %s, got %s)"),3078 name, patch->new_sha1_prefix, sha1_to_hex(sha1));3079 }30803081 return 0;3082}30833084static int apply_fragments(struct apply_state *state, struct image *img, struct patch *patch)3085{3086 struct fragment *frag = patch->fragments;3087 const char *name = patch->old_name ? patch->old_name : patch->new_name;3088 unsigned ws_rule = patch->ws_rule;3089 unsigned inaccurate_eof = patch->inaccurate_eof;3090 int nth = 0;30913092 if (patch->is_binary)3093 return apply_binary(state, img, patch);30943095 while (frag) {3096 nth++;3097 if (apply_one_fragment(state, img, frag, inaccurate_eof, ws_rule, nth)) {3098 error(_("patch failed: %s:%ld"), name, frag->oldpos);3099 if (!apply_with_reject)3100 return -1;3101 frag->rejected = 1;3102 }3103 frag = frag->next;3104 }3105 return 0;3106}31073108static int read_blob_object(struct strbuf *buf, const unsigned char *sha1, unsigned mode)3109{3110 if (S_ISGITLINK(mode)) {3111 strbuf_grow(buf, 100);3112 strbuf_addf(buf, "Subproject commit %s\n", sha1_to_hex(sha1));3113 } else {3114 enum object_type type;3115 unsigned long sz;3116 char *result;31173118 result = read_sha1_file(sha1, &type, &sz);3119 if (!result)3120 return -1;3121 /* XXX read_sha1_file NUL-terminates */3122 strbuf_attach(buf, result, sz, sz + 1);3123 }3124 return 0;3125}31263127static int read_file_or_gitlink(const struct cache_entry *ce, struct strbuf *buf)3128{3129 if (!ce)3130 return 0;3131 return read_blob_object(buf, ce->sha1, ce->ce_mode);3132}31333134static struct patch *in_fn_table(const char *name)3135{3136 struct string_list_item *item;31373138 if (name == NULL)3139 return NULL;31403141 item = string_list_lookup(&fn_table, name);3142 if (item != NULL)3143 return (struct patch *)item->util;31443145 return NULL;3146}31473148/*3149 * item->util in the filename table records the status of the path.3150 * Usually it points at a patch (whose result records the contents3151 * of it after applying it), but it could be PATH_WAS_DELETED for a3152 * path that a previously applied patch has already removed, or3153 * PATH_TO_BE_DELETED for a path that a later patch would remove.3154 *3155 * The latter is needed to deal with a case where two paths A and B3156 * are swapped by first renaming A to B and then renaming B to A;3157 * moving A to B should not be prevented due to presence of B as we3158 * will remove it in a later patch.3159 */3160#define PATH_TO_BE_DELETED ((struct patch *) -2)3161#define PATH_WAS_DELETED ((struct patch *) -1)31623163static int to_be_deleted(struct patch *patch)3164{3165 return patch == PATH_TO_BE_DELETED;3166}31673168static int was_deleted(struct patch *patch)3169{3170 return patch == PATH_WAS_DELETED;3171}31723173static void add_to_fn_table(struct patch *patch)3174{3175 struct string_list_item *item;31763177 /*3178 * Always add new_name unless patch is a deletion3179 * This should cover the cases for normal diffs,3180 * file creations and copies3181 */3182 if (patch->new_name != NULL) {3183 item = string_list_insert(&fn_table, patch->new_name);3184 item->util = patch;3185 }31863187 /*3188 * store a failure on rename/deletion cases because3189 * later chunks shouldn't patch old names3190 */3191 if ((patch->new_name == NULL) || (patch->is_rename)) {3192 item = string_list_insert(&fn_table, patch->old_name);3193 item->util = PATH_WAS_DELETED;3194 }3195}31963197static void prepare_fn_table(struct patch *patch)3198{3199 /*3200 * store information about incoming file deletion3201 */3202 while (patch) {3203 if ((patch->new_name == NULL) || (patch->is_rename)) {3204 struct string_list_item *item;3205 item = string_list_insert(&fn_table, patch->old_name);3206 item->util = PATH_TO_BE_DELETED;3207 }3208 patch = patch->next;3209 }3210}32113212static int checkout_target(struct index_state *istate,3213 struct cache_entry *ce, struct stat *st)3214{3215 struct checkout costate;32163217 memset(&costate, 0, sizeof(costate));3218 costate.base_dir = "";3219 costate.refresh_cache = 1;3220 costate.istate = istate;3221 if (checkout_entry(ce, &costate, NULL) || lstat(ce->name, st))3222 return error(_("cannot checkout %s"), ce->name);3223 return 0;3224}32253226static struct patch *previous_patch(struct patch *patch, int *gone)3227{3228 struct patch *previous;32293230 *gone = 0;3231 if (patch->is_copy || patch->is_rename)3232 return NULL; /* "git" patches do not depend on the order */32333234 previous = in_fn_table(patch->old_name);3235 if (!previous)3236 return NULL;32373238 if (to_be_deleted(previous))3239 return NULL; /* the deletion hasn't happened yet */32403241 if (was_deleted(previous))3242 *gone = 1;32433244 return previous;3245}32463247static int verify_index_match(const struct cache_entry *ce, struct stat *st)3248{3249 if (S_ISGITLINK(ce->ce_mode)) {3250 if (!S_ISDIR(st->st_mode))3251 return -1;3252 return 0;3253 }3254 return ce_match_stat(ce, st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE);3255}32563257#define SUBMODULE_PATCH_WITHOUT_INDEX 132583259static int load_patch_target(struct apply_state *state,3260 struct strbuf *buf,3261 const struct cache_entry *ce,3262 struct stat *st,3263 const char *name,3264 unsigned expected_mode)3265{3266 if (cached || state->check_index) {3267 if (read_file_or_gitlink(ce, buf))3268 return error(_("read of %s failed"), name);3269 } else if (name) {3270 if (S_ISGITLINK(expected_mode)) {3271 if (ce)3272 return read_file_or_gitlink(ce, buf);3273 else3274 return SUBMODULE_PATCH_WITHOUT_INDEX;3275 } else if (has_symlink_leading_path(name, strlen(name))) {3276 return error(_("reading from '%s' beyond a symbolic link"), name);3277 } else {3278 if (read_old_data(st, name, buf))3279 return error(_("read of %s failed"), name);3280 }3281 }3282 return 0;3283}32843285/*3286 * We are about to apply "patch"; populate the "image" with the3287 * current version we have, from the working tree or from the index,3288 * depending on the situation e.g. --cached/--index. If we are3289 * applying a non-git patch that incrementally updates the tree,3290 * we read from the result of a previous diff.3291 */3292static int load_preimage(struct apply_state *state,3293 struct image *image,3294 struct patch *patch, struct stat *st,3295 const struct cache_entry *ce)3296{3297 struct strbuf buf = STRBUF_INIT;3298 size_t len;3299 char *img;3300 struct patch *previous;3301 int status;33023303 previous = previous_patch(patch, &status);3304 if (status)3305 return error(_("path %s has been renamed/deleted"),3306 patch->old_name);3307 if (previous) {3308 /* We have a patched copy in memory; use that. */3309 strbuf_add(&buf, previous->result, previous->resultsize);3310 } else {3311 status = load_patch_target(state, &buf, ce, st,3312 patch->old_name, patch->old_mode);3313 if (status < 0)3314 return status;3315 else if (status == SUBMODULE_PATCH_WITHOUT_INDEX) {3316 /*3317 * There is no way to apply subproject3318 * patch without looking at the index.3319 * NEEDSWORK: shouldn't this be flagged3320 * as an error???3321 */3322 free_fragment_list(patch->fragments);3323 patch->fragments = NULL;3324 } else if (status) {3325 return error(_("read of %s failed"), patch->old_name);3326 }3327 }33283329 img = strbuf_detach(&buf, &len);3330 prepare_image(image, img, len, !patch->is_binary);3331 return 0;3332}33333334static int three_way_merge(struct image *image,3335 char *path,3336 const unsigned char *base,3337 const unsigned char *ours,3338 const unsigned char *theirs)3339{3340 mmfile_t base_file, our_file, their_file;3341 mmbuffer_t result = { NULL };3342 int status;33433344 read_mmblob(&base_file, base);3345 read_mmblob(&our_file, ours);3346 read_mmblob(&their_file, theirs);3347 status = ll_merge(&result, path,3348 &base_file, "base",3349 &our_file, "ours",3350 &their_file, "theirs", NULL);3351 free(base_file.ptr);3352 free(our_file.ptr);3353 free(their_file.ptr);3354 if (status < 0 || !result.ptr) {3355 free(result.ptr);3356 return -1;3357 }3358 clear_image(image);3359 image->buf = result.ptr;3360 image->len = result.size;33613362 return status;3363}33643365/*3366 * When directly falling back to add/add three-way merge, we read from3367 * the current contents of the new_name. In no cases other than that3368 * this function will be called.3369 */3370static int load_current(struct apply_state *state,3371 struct image *image,3372 struct patch *patch)3373{3374 struct strbuf buf = STRBUF_INIT;3375 int status, pos;3376 size_t len;3377 char *img;3378 struct stat st;3379 struct cache_entry *ce;3380 char *name = patch->new_name;3381 unsigned mode = patch->new_mode;33823383 if (!patch->is_new)3384 die("BUG: patch to %s is not a creation", patch->old_name);33853386 pos = cache_name_pos(name, strlen(name));3387 if (pos < 0)3388 return error(_("%s: does not exist in index"), name);3389 ce = active_cache[pos];3390 if (lstat(name, &st)) {3391 if (errno != ENOENT)3392 return error(_("%s: %s"), name, strerror(errno));3393 if (checkout_target(&the_index, ce, &st))3394 return -1;3395 }3396 if (verify_index_match(ce, &st))3397 return error(_("%s: does not match index"), name);33983399 status = load_patch_target(state, &buf, ce, &st, name, mode);3400 if (status < 0)3401 return status;3402 else if (status)3403 return -1;3404 img = strbuf_detach(&buf, &len);3405 prepare_image(image, img, len, !patch->is_binary);3406 return 0;3407}34083409static int try_threeway(struct apply_state *state,3410 struct image *image,3411 struct patch *patch,3412 struct stat *st,3413 const struct cache_entry *ce)3414{3415 unsigned char pre_sha1[20], post_sha1[20], our_sha1[20];3416 struct strbuf buf = STRBUF_INIT;3417 size_t len;3418 int status;3419 char *img;3420 struct image tmp_image;34213422 /* No point falling back to 3-way merge in these cases */3423 if (patch->is_delete ||3424 S_ISGITLINK(patch->old_mode) || S_ISGITLINK(patch->new_mode))3425 return -1;34263427 /* Preimage the patch was prepared for */3428 if (patch->is_new)3429 write_sha1_file("", 0, blob_type, pre_sha1);3430 else if (get_sha1(patch->old_sha1_prefix, pre_sha1) ||3431 read_blob_object(&buf, pre_sha1, patch->old_mode))3432 return error("repository lacks the necessary blob to fall back on 3-way merge.");34333434 fprintf(stderr, "Falling back to three-way merge...\n");34353436 img = strbuf_detach(&buf, &len);3437 prepare_image(&tmp_image, img, len, 1);3438 /* Apply the patch to get the post image */3439 if (apply_fragments(state, &tmp_image, patch) < 0) {3440 clear_image(&tmp_image);3441 return -1;3442 }3443 /* post_sha1[] is theirs */3444 write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, post_sha1);3445 clear_image(&tmp_image);34463447 /* our_sha1[] is ours */3448 if (patch->is_new) {3449 if (load_current(state, &tmp_image, patch))3450 return error("cannot read the current contents of '%s'",3451 patch->new_name);3452 } else {3453 if (load_preimage(state, &tmp_image, patch, st, ce))3454 return error("cannot read the current contents of '%s'",3455 patch->old_name);3456 }3457 write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, our_sha1);3458 clear_image(&tmp_image);34593460 /* in-core three-way merge between post and our using pre as base */3461 status = three_way_merge(image, patch->new_name,3462 pre_sha1, our_sha1, post_sha1);3463 if (status < 0) {3464 fprintf(stderr, "Failed to fall back on three-way merge...\n");3465 return status;3466 }34673468 if (status) {3469 patch->conflicted_threeway = 1;3470 if (patch->is_new)3471 oidclr(&patch->threeway_stage[0]);3472 else3473 hashcpy(patch->threeway_stage[0].hash, pre_sha1);3474 hashcpy(patch->threeway_stage[1].hash, our_sha1);3475 hashcpy(patch->threeway_stage[2].hash, post_sha1);3476 fprintf(stderr, "Applied patch to '%s' with conflicts.\n", patch->new_name);3477 } else {3478 fprintf(stderr, "Applied patch to '%s' cleanly.\n", patch->new_name);3479 }3480 return 0;3481}34823483static int apply_data(struct apply_state *state, struct patch *patch,3484 struct stat *st, const struct cache_entry *ce)3485{3486 struct image image;34873488 if (load_preimage(state, &image, patch, st, ce) < 0)3489 return -1;34903491 if (patch->direct_to_threeway ||3492 apply_fragments(state, &image, patch) < 0) {3493 /* Note: with --reject, apply_fragments() returns 0 */3494 if (!threeway || try_threeway(state, &image, patch, st, ce) < 0)3495 return -1;3496 }3497 patch->result = image.buf;3498 patch->resultsize = image.len;3499 add_to_fn_table(patch);3500 free(image.line_allocated);35013502 if (0 < patch->is_delete && patch->resultsize)3503 return error(_("removal patch leaves file contents"));35043505 return 0;3506}35073508/*3509 * If "patch" that we are looking at modifies or deletes what we have,3510 * we would want it not to lose any local modification we have, either3511 * in the working tree or in the index.3512 *3513 * This also decides if a non-git patch is a creation patch or a3514 * modification to an existing empty file. We do not check the state3515 * of the current tree for a creation patch in this function; the caller3516 * check_patch() separately makes sure (and errors out otherwise) that3517 * the path the patch creates does not exist in the current tree.3518 */3519static int check_preimage(struct apply_state *state,3520 struct patch *patch,3521 struct cache_entry **ce,3522 struct stat *st)3523{3524 const char *old_name = patch->old_name;3525 struct patch *previous = NULL;3526 int stat_ret = 0, status;3527 unsigned st_mode = 0;35283529 if (!old_name)3530 return 0;35313532 assert(patch->is_new <= 0);3533 previous = previous_patch(patch, &status);35343535 if (status)3536 return error(_("path %s has been renamed/deleted"), old_name);3537 if (previous) {3538 st_mode = previous->new_mode;3539 } else if (!cached) {3540 stat_ret = lstat(old_name, st);3541 if (stat_ret && errno != ENOENT)3542 return error(_("%s: %s"), old_name, strerror(errno));3543 }35443545 if (state->check_index && !previous) {3546 int pos = cache_name_pos(old_name, strlen(old_name));3547 if (pos < 0) {3548 if (patch->is_new < 0)3549 goto is_new;3550 return error(_("%s: does not exist in index"), old_name);3551 }3552 *ce = active_cache[pos];3553 if (stat_ret < 0) {3554 if (checkout_target(&the_index, *ce, st))3555 return -1;3556 }3557 if (!cached && verify_index_match(*ce, st))3558 return error(_("%s: does not match index"), old_name);3559 if (cached)3560 st_mode = (*ce)->ce_mode;3561 } else if (stat_ret < 0) {3562 if (patch->is_new < 0)3563 goto is_new;3564 return error(_("%s: %s"), old_name, strerror(errno));3565 }35663567 if (!cached && !previous)3568 st_mode = ce_mode_from_stat(*ce, st->st_mode);35693570 if (patch->is_new < 0)3571 patch->is_new = 0;3572 if (!patch->old_mode)3573 patch->old_mode = st_mode;3574 if ((st_mode ^ patch->old_mode) & S_IFMT)3575 return error(_("%s: wrong type"), old_name);3576 if (st_mode != patch->old_mode)3577 warning(_("%s has type %o, expected %o"),3578 old_name, st_mode, patch->old_mode);3579 if (!patch->new_mode && !patch->is_delete)3580 patch->new_mode = st_mode;3581 return 0;35823583 is_new:3584 patch->is_new = 1;3585 patch->is_delete = 0;3586 free(patch->old_name);3587 patch->old_name = NULL;3588 return 0;3589}359035913592#define EXISTS_IN_INDEX 13593#define EXISTS_IN_WORKTREE 235943595static int check_to_create(struct apply_state *state,3596 const char *new_name,3597 int ok_if_exists)3598{3599 struct stat nst;36003601 if (state->check_index &&3602 cache_name_pos(new_name, strlen(new_name)) >= 0 &&3603 !ok_if_exists)3604 return EXISTS_IN_INDEX;3605 if (cached)3606 return 0;36073608 if (!lstat(new_name, &nst)) {3609 if (S_ISDIR(nst.st_mode) || ok_if_exists)3610 return 0;3611 /*3612 * A leading component of new_name might be a symlink3613 * that is going to be removed with this patch, but3614 * still pointing at somewhere that has the path.3615 * In such a case, path "new_name" does not exist as3616 * far as git is concerned.3617 */3618 if (has_symlink_leading_path(new_name, strlen(new_name)))3619 return 0;36203621 return EXISTS_IN_WORKTREE;3622 } else if ((errno != ENOENT) && (errno != ENOTDIR)) {3623 return error("%s: %s", new_name, strerror(errno));3624 }3625 return 0;3626}36273628/*3629 * We need to keep track of how symlinks in the preimage are3630 * manipulated by the patches. A patch to add a/b/c where a/b3631 * is a symlink should not be allowed to affect the directory3632 * the symlink points at, but if the same patch removes a/b,3633 * it is perfectly fine, as the patch removes a/b to make room3634 * to create a directory a/b so that a/b/c can be created.3635 */3636static struct string_list symlink_changes;3637#define SYMLINK_GOES_AWAY 013638#define SYMLINK_IN_RESULT 0236393640static uintptr_t register_symlink_changes(const char *path, uintptr_t what)3641{3642 struct string_list_item *ent;36433644 ent = string_list_lookup(&symlink_changes, path);3645 if (!ent) {3646 ent = string_list_insert(&symlink_changes, path);3647 ent->util = (void *)0;3648 }3649 ent->util = (void *)(what | ((uintptr_t)ent->util));3650 return (uintptr_t)ent->util;3651}36523653static uintptr_t check_symlink_changes(const char *path)3654{3655 struct string_list_item *ent;36563657 ent = string_list_lookup(&symlink_changes, path);3658 if (!ent)3659 return 0;3660 return (uintptr_t)ent->util;3661}36623663static void prepare_symlink_changes(struct patch *patch)3664{3665 for ( ; patch; patch = patch->next) {3666 if ((patch->old_name && S_ISLNK(patch->old_mode)) &&3667 (patch->is_rename || patch->is_delete))3668 /* the symlink at patch->old_name is removed */3669 register_symlink_changes(patch->old_name, SYMLINK_GOES_AWAY);36703671 if (patch->new_name && S_ISLNK(patch->new_mode))3672 /* the symlink at patch->new_name is created or remains */3673 register_symlink_changes(patch->new_name, SYMLINK_IN_RESULT);3674 }3675}36763677static int path_is_beyond_symlink_1(struct apply_state *state, struct strbuf *name)3678{3679 do {3680 unsigned int change;36813682 while (--name->len && name->buf[name->len] != '/')3683 ; /* scan backwards */3684 if (!name->len)3685 break;3686 name->buf[name->len] = '\0';3687 change = check_symlink_changes(name->buf);3688 if (change & SYMLINK_IN_RESULT)3689 return 1;3690 if (change & SYMLINK_GOES_AWAY)3691 /*3692 * This cannot be "return 0", because we may3693 * see a new one created at a higher level.3694 */3695 continue;36963697 /* otherwise, check the preimage */3698 if (state->check_index) {3699 struct cache_entry *ce;37003701 ce = cache_file_exists(name->buf, name->len, ignore_case);3702 if (ce && S_ISLNK(ce->ce_mode))3703 return 1;3704 } else {3705 struct stat st;3706 if (!lstat(name->buf, &st) && S_ISLNK(st.st_mode))3707 return 1;3708 }3709 } while (1);3710 return 0;3711}37123713static int path_is_beyond_symlink(struct apply_state *state, const char *name_)3714{3715 int ret;3716 struct strbuf name = STRBUF_INIT;37173718 assert(*name_ != '\0');3719 strbuf_addstr(&name, name_);3720 ret = path_is_beyond_symlink_1(state, &name);3721 strbuf_release(&name);37223723 return ret;3724}37253726static void die_on_unsafe_path(struct patch *patch)3727{3728 const char *old_name = NULL;3729 const char *new_name = NULL;3730 if (patch->is_delete)3731 old_name = patch->old_name;3732 else if (!patch->is_new && !patch->is_copy)3733 old_name = patch->old_name;3734 if (!patch->is_delete)3735 new_name = patch->new_name;37363737 if (old_name && !verify_path(old_name))3738 die(_("invalid path '%s'"), old_name);3739 if (new_name && !verify_path(new_name))3740 die(_("invalid path '%s'"), new_name);3741}37423743/*3744 * Check and apply the patch in-core; leave the result in patch->result3745 * for the caller to write it out to the final destination.3746 */3747static int check_patch(struct apply_state *state, struct patch *patch)3748{3749 struct stat st;3750 const char *old_name = patch->old_name;3751 const char *new_name = patch->new_name;3752 const char *name = old_name ? old_name : new_name;3753 struct cache_entry *ce = NULL;3754 struct patch *tpatch;3755 int ok_if_exists;3756 int status;37573758 patch->rejected = 1; /* we will drop this after we succeed */37593760 status = check_preimage(state, patch, &ce, &st);3761 if (status)3762 return status;3763 old_name = patch->old_name;37643765 /*3766 * A type-change diff is always split into a patch to delete3767 * old, immediately followed by a patch to create new (see3768 * diff.c::run_diff()); in such a case it is Ok that the entry3769 * to be deleted by the previous patch is still in the working3770 * tree and in the index.3771 *3772 * A patch to swap-rename between A and B would first rename A3773 * to B and then rename B to A. While applying the first one,3774 * the presence of B should not stop A from getting renamed to3775 * B; ask to_be_deleted() about the later rename. Removal of3776 * B and rename from A to B is handled the same way by asking3777 * was_deleted().3778 */3779 if ((tpatch = in_fn_table(new_name)) &&3780 (was_deleted(tpatch) || to_be_deleted(tpatch)))3781 ok_if_exists = 1;3782 else3783 ok_if_exists = 0;37843785 if (new_name &&3786 ((0 < patch->is_new) || patch->is_rename || patch->is_copy)) {3787 int err = check_to_create(state, new_name, ok_if_exists);37883789 if (err && threeway) {3790 patch->direct_to_threeway = 1;3791 } else switch (err) {3792 case 0:3793 break; /* happy */3794 case EXISTS_IN_INDEX:3795 return error(_("%s: already exists in index"), new_name);3796 break;3797 case EXISTS_IN_WORKTREE:3798 return error(_("%s: already exists in working directory"),3799 new_name);3800 default:3801 return err;3802 }38033804 if (!patch->new_mode) {3805 if (0 < patch->is_new)3806 patch->new_mode = S_IFREG | 0644;3807 else3808 patch->new_mode = patch->old_mode;3809 }3810 }38113812 if (new_name && old_name) {3813 int same = !strcmp(old_name, new_name);3814 if (!patch->new_mode)3815 patch->new_mode = patch->old_mode;3816 if ((patch->old_mode ^ patch->new_mode) & S_IFMT) {3817 if (same)3818 return error(_("new mode (%o) of %s does not "3819 "match old mode (%o)"),3820 patch->new_mode, new_name,3821 patch->old_mode);3822 else3823 return error(_("new mode (%o) of %s does not "3824 "match old mode (%o) of %s"),3825 patch->new_mode, new_name,3826 patch->old_mode, old_name);3827 }3828 }38293830 if (!unsafe_paths)3831 die_on_unsafe_path(patch);38323833 /*3834 * An attempt to read from or delete a path that is beyond a3835 * symbolic link will be prevented by load_patch_target() that3836 * is called at the beginning of apply_data() so we do not3837 * have to worry about a patch marked with "is_delete" bit3838 * here. We however need to make sure that the patch result3839 * is not deposited to a path that is beyond a symbolic link3840 * here.3841 */3842 if (!patch->is_delete && path_is_beyond_symlink(state, patch->new_name))3843 return error(_("affected file '%s' is beyond a symbolic link"),3844 patch->new_name);38453846 if (apply_data(state, patch, &st, ce) < 0)3847 return error(_("%s: patch does not apply"), name);3848 patch->rejected = 0;3849 return 0;3850}38513852static int check_patch_list(struct apply_state *state, struct patch *patch)3853{3854 int err = 0;38553856 prepare_symlink_changes(patch);3857 prepare_fn_table(patch);3858 while (patch) {3859 if (apply_verbosely)3860 say_patch_name(stderr,3861 _("Checking patch %s..."), patch);3862 err |= check_patch(state, patch);3863 patch = patch->next;3864 }3865 return err;3866}38673868/* This function tries to read the sha1 from the current index */3869static int get_current_sha1(const char *path, unsigned char *sha1)3870{3871 int pos;38723873 if (read_cache() < 0)3874 return -1;3875 pos = cache_name_pos(path, strlen(path));3876 if (pos < 0)3877 return -1;3878 hashcpy(sha1, active_cache[pos]->sha1);3879 return 0;3880}38813882static int preimage_sha1_in_gitlink_patch(struct patch *p, unsigned char sha1[20])3883{3884 /*3885 * A usable gitlink patch has only one fragment (hunk) that looks like:3886 * @@ -1 +1 @@3887 * -Subproject commit <old sha1>3888 * +Subproject commit <new sha1>3889 * or3890 * @@ -1 +0,0 @@3891 * -Subproject commit <old sha1>3892 * for a removal patch.3893 */3894 struct fragment *hunk = p->fragments;3895 static const char heading[] = "-Subproject commit ";3896 char *preimage;38973898 if (/* does the patch have only one hunk? */3899 hunk && !hunk->next &&3900 /* is its preimage one line? */3901 hunk->oldpos == 1 && hunk->oldlines == 1 &&3902 /* does preimage begin with the heading? */3903 (preimage = memchr(hunk->patch, '\n', hunk->size)) != NULL &&3904 starts_with(++preimage, heading) &&3905 /* does it record full SHA-1? */3906 !get_sha1_hex(preimage + sizeof(heading) - 1, sha1) &&3907 preimage[sizeof(heading) + 40 - 1] == '\n' &&3908 /* does the abbreviated name on the index line agree with it? */3909 starts_with(preimage + sizeof(heading) - 1, p->old_sha1_prefix))3910 return 0; /* it all looks fine */39113912 /* we may have full object name on the index line */3913 return get_sha1_hex(p->old_sha1_prefix, sha1);3914}39153916/* Build an index that contains the just the files needed for a 3way merge */3917static void build_fake_ancestor(struct patch *list, const char *filename)3918{3919 struct patch *patch;3920 struct index_state result = { NULL };3921 static struct lock_file lock;39223923 /* Once we start supporting the reverse patch, it may be3924 * worth showing the new sha1 prefix, but until then...3925 */3926 for (patch = list; patch; patch = patch->next) {3927 unsigned char sha1[20];3928 struct cache_entry *ce;3929 const char *name;39303931 name = patch->old_name ? patch->old_name : patch->new_name;3932 if (0 < patch->is_new)3933 continue;39343935 if (S_ISGITLINK(patch->old_mode)) {3936 if (!preimage_sha1_in_gitlink_patch(patch, sha1))3937 ; /* ok, the textual part looks sane */3938 else3939 die("sha1 information is lacking or useless for submodule %s",3940 name);3941 } else if (!get_sha1_blob(patch->old_sha1_prefix, sha1)) {3942 ; /* ok */3943 } else if (!patch->lines_added && !patch->lines_deleted) {3944 /* mode-only change: update the current */3945 if (get_current_sha1(patch->old_name, sha1))3946 die("mode change for %s, which is not "3947 "in current HEAD", name);3948 } else3949 die("sha1 information is lacking or useless "3950 "(%s).", name);39513952 ce = make_cache_entry(patch->old_mode, sha1, name, 0, 0);3953 if (!ce)3954 die(_("make_cache_entry failed for path '%s'"), name);3955 if (add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD))3956 die ("Could not add %s to temporary index", name);3957 }39583959 hold_lock_file_for_update(&lock, filename, LOCK_DIE_ON_ERROR);3960 if (write_locked_index(&result, &lock, COMMIT_LOCK))3961 die ("Could not write temporary index to %s", filename);39623963 discard_index(&result);3964}39653966static void stat_patch_list(struct patch *patch)3967{3968 int files, adds, dels;39693970 for (files = adds = dels = 0 ; patch ; patch = patch->next) {3971 files++;3972 adds += patch->lines_added;3973 dels += patch->lines_deleted;3974 show_stats(patch);3975 }39763977 print_stat_summary(stdout, files, adds, dels);3978}39793980static void numstat_patch_list(struct patch *patch)3981{3982 for ( ; patch; patch = patch->next) {3983 const char *name;3984 name = patch->new_name ? patch->new_name : patch->old_name;3985 if (patch->is_binary)3986 printf("-\t-\t");3987 else3988 printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);3989 write_name_quoted(name, stdout, line_termination);3990 }3991}39923993static void show_file_mode_name(const char *newdelete, unsigned int mode, const char *name)3994{3995 if (mode)3996 printf(" %s mode %06o %s\n", newdelete, mode, name);3997 else3998 printf(" %s %s\n", newdelete, name);3999}40004001static void show_mode_change(struct patch *p, int show_name)4002{4003 if (p->old_mode && p->new_mode && p->old_mode != p->new_mode) {4004 if (show_name)4005 printf(" mode change %06o => %06o %s\n",4006 p->old_mode, p->new_mode, p->new_name);4007 else4008 printf(" mode change %06o => %06o\n",4009 p->old_mode, p->new_mode);4010 }4011}40124013static void show_rename_copy(struct patch *p)4014{4015 const char *renamecopy = p->is_rename ? "rename" : "copy";4016 const char *old, *new;40174018 /* Find common prefix */4019 old = p->old_name;4020 new = p->new_name;4021 while (1) {4022 const char *slash_old, *slash_new;4023 slash_old = strchr(old, '/');4024 slash_new = strchr(new, '/');4025 if (!slash_old ||4026 !slash_new ||4027 slash_old - old != slash_new - new ||4028 memcmp(old, new, slash_new - new))4029 break;4030 old = slash_old + 1;4031 new = slash_new + 1;4032 }4033 /* p->old_name thru old is the common prefix, and old and new4034 * through the end of names are renames4035 */4036 if (old != p->old_name)4037 printf(" %s %.*s{%s => %s} (%d%%)\n", renamecopy,4038 (int)(old - p->old_name), p->old_name,4039 old, new, p->score);4040 else4041 printf(" %s %s => %s (%d%%)\n", renamecopy,4042 p->old_name, p->new_name, p->score);4043 show_mode_change(p, 0);4044}40454046static void summary_patch_list(struct patch *patch)4047{4048 struct patch *p;40494050 for (p = patch; p; p = p->next) {4051 if (p->is_new)4052 show_file_mode_name("create", p->new_mode, p->new_name);4053 else if (p->is_delete)4054 show_file_mode_name("delete", p->old_mode, p->old_name);4055 else {4056 if (p->is_rename || p->is_copy)4057 show_rename_copy(p);4058 else {4059 if (p->score) {4060 printf(" rewrite %s (%d%%)\n",4061 p->new_name, p->score);4062 show_mode_change(p, 0);4063 }4064 else4065 show_mode_change(p, 1);4066 }4067 }4068 }4069}40704071static void patch_stats(struct patch *patch)4072{4073 int lines = patch->lines_added + patch->lines_deleted;40744075 if (lines > max_change)4076 max_change = lines;4077 if (patch->old_name) {4078 int len = quote_c_style(patch->old_name, NULL, NULL, 0);4079 if (!len)4080 len = strlen(patch->old_name);4081 if (len > max_len)4082 max_len = len;4083 }4084 if (patch->new_name) {4085 int len = quote_c_style(patch->new_name, NULL, NULL, 0);4086 if (!len)4087 len = strlen(patch->new_name);4088 if (len > max_len)4089 max_len = len;4090 }4091}40924093static void remove_file(struct patch *patch, int rmdir_empty)4094{4095 if (update_index) {4096 if (remove_file_from_cache(patch->old_name) < 0)4097 die(_("unable to remove %s from index"), patch->old_name);4098 }4099 if (!cached) {4100 if (!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {4101 remove_path(patch->old_name);4102 }4103 }4104}41054106static void add_index_file(const char *path, unsigned mode, void *buf, unsigned long size)4107{4108 struct stat st;4109 struct cache_entry *ce;4110 int namelen = strlen(path);4111 unsigned ce_size = cache_entry_size(namelen);41124113 if (!update_index)4114 return;41154116 ce = xcalloc(1, ce_size);4117 memcpy(ce->name, path, namelen);4118 ce->ce_mode = create_ce_mode(mode);4119 ce->ce_flags = create_ce_flags(0);4120 ce->ce_namelen = namelen;4121 if (S_ISGITLINK(mode)) {4122 const char *s;41234124 if (!skip_prefix(buf, "Subproject commit ", &s) ||4125 get_sha1_hex(s, ce->sha1))4126 die(_("corrupt patch for submodule %s"), path);4127 } else {4128 if (!cached) {4129 if (lstat(path, &st) < 0)4130 die_errno(_("unable to stat newly created file '%s'"),4131 path);4132 fill_stat_cache_info(ce, &st);4133 }4134 if (write_sha1_file(buf, size, blob_type, ce->sha1) < 0)4135 die(_("unable to create backing store for newly created file %s"), path);4136 }4137 if (add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) < 0)4138 die(_("unable to add cache entry for %s"), path);4139}41404141static int try_create_file(const char *path, unsigned int mode, const char *buf, unsigned long size)4142{4143 int fd;4144 struct strbuf nbuf = STRBUF_INIT;41454146 if (S_ISGITLINK(mode)) {4147 struct stat st;4148 if (!lstat(path, &st) && S_ISDIR(st.st_mode))4149 return 0;4150 return mkdir(path, 0777);4151 }41524153 if (has_symlinks && S_ISLNK(mode))4154 /* Although buf:size is counted string, it also is NUL4155 * terminated.4156 */4157 return symlink(buf, path);41584159 fd = open(path, O_CREAT | O_EXCL | O_WRONLY, (mode & 0100) ? 0777 : 0666);4160 if (fd < 0)4161 return -1;41624163 if (convert_to_working_tree(path, buf, size, &nbuf)) {4164 size = nbuf.len;4165 buf = nbuf.buf;4166 }4167 write_or_die(fd, buf, size);4168 strbuf_release(&nbuf);41694170 if (close(fd) < 0)4171 die_errno(_("closing file '%s'"), path);4172 return 0;4173}41744175/*4176 * We optimistically assume that the directories exist,4177 * which is true 99% of the time anyway. If they don't,4178 * we create them and try again.4179 */4180static void create_one_file(char *path, unsigned mode, const char *buf, unsigned long size)4181{4182 if (cached)4183 return;4184 if (!try_create_file(path, mode, buf, size))4185 return;41864187 if (errno == ENOENT) {4188 if (safe_create_leading_directories(path))4189 return;4190 if (!try_create_file(path, mode, buf, size))4191 return;4192 }41934194 if (errno == EEXIST || errno == EACCES) {4195 /* We may be trying to create a file where a directory4196 * used to be.4197 */4198 struct stat st;4199 if (!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))4200 errno = EEXIST;4201 }42024203 if (errno == EEXIST) {4204 unsigned int nr = getpid();42054206 for (;;) {4207 char newpath[PATH_MAX];4208 mksnpath(newpath, sizeof(newpath), "%s~%u", path, nr);4209 if (!try_create_file(newpath, mode, buf, size)) {4210 if (!rename(newpath, path))4211 return;4212 unlink_or_warn(newpath);4213 break;4214 }4215 if (errno != EEXIST)4216 break;4217 ++nr;4218 }4219 }4220 die_errno(_("unable to write file '%s' mode %o"), path, mode);4221}42224223static void add_conflicted_stages_file(struct patch *patch)4224{4225 int stage, namelen;4226 unsigned ce_size, mode;4227 struct cache_entry *ce;42284229 if (!update_index)4230 return;4231 namelen = strlen(patch->new_name);4232 ce_size = cache_entry_size(namelen);4233 mode = patch->new_mode ? patch->new_mode : (S_IFREG | 0644);42344235 remove_file_from_cache(patch->new_name);4236 for (stage = 1; stage < 4; stage++) {4237 if (is_null_oid(&patch->threeway_stage[stage - 1]))4238 continue;4239 ce = xcalloc(1, ce_size);4240 memcpy(ce->name, patch->new_name, namelen);4241 ce->ce_mode = create_ce_mode(mode);4242 ce->ce_flags = create_ce_flags(stage);4243 ce->ce_namelen = namelen;4244 hashcpy(ce->sha1, patch->threeway_stage[stage - 1].hash);4245 if (add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) < 0)4246 die(_("unable to add cache entry for %s"), patch->new_name);4247 }4248}42494250static void create_file(struct patch *patch)4251{4252 char *path = patch->new_name;4253 unsigned mode = patch->new_mode;4254 unsigned long size = patch->resultsize;4255 char *buf = patch->result;42564257 if (!mode)4258 mode = S_IFREG | 0644;4259 create_one_file(path, mode, buf, size);42604261 if (patch->conflicted_threeway)4262 add_conflicted_stages_file(patch);4263 else4264 add_index_file(path, mode, buf, size);4265}42664267/* phase zero is to remove, phase one is to create */4268static void write_out_one_result(struct patch *patch, int phase)4269{4270 if (patch->is_delete > 0) {4271 if (phase == 0)4272 remove_file(patch, 1);4273 return;4274 }4275 if (patch->is_new > 0 || patch->is_copy) {4276 if (phase == 1)4277 create_file(patch);4278 return;4279 }4280 /*4281 * Rename or modification boils down to the same4282 * thing: remove the old, write the new4283 */4284 if (phase == 0)4285 remove_file(patch, patch->is_rename);4286 if (phase == 1)4287 create_file(patch);4288}42894290static int write_out_one_reject(struct patch *patch)4291{4292 FILE *rej;4293 char namebuf[PATH_MAX];4294 struct fragment *frag;4295 int cnt = 0;4296 struct strbuf sb = STRBUF_INIT;42974298 for (cnt = 0, frag = patch->fragments; frag; frag = frag->next) {4299 if (!frag->rejected)4300 continue;4301 cnt++;4302 }43034304 if (!cnt) {4305 if (apply_verbosely)4306 say_patch_name(stderr,4307 _("Applied patch %s cleanly."), patch);4308 return 0;4309 }43104311 /* This should not happen, because a removal patch that leaves4312 * contents are marked "rejected" at the patch level.4313 */4314 if (!patch->new_name)4315 die(_("internal error"));43164317 /* Say this even without --verbose */4318 strbuf_addf(&sb, Q_("Applying patch %%s with %d reject...",4319 "Applying patch %%s with %d rejects...",4320 cnt),4321 cnt);4322 say_patch_name(stderr, sb.buf, patch);4323 strbuf_release(&sb);43244325 cnt = strlen(patch->new_name);4326 if (ARRAY_SIZE(namebuf) <= cnt + 5) {4327 cnt = ARRAY_SIZE(namebuf) - 5;4328 warning(_("truncating .rej filename to %.*s.rej"),4329 cnt - 1, patch->new_name);4330 }4331 memcpy(namebuf, patch->new_name, cnt);4332 memcpy(namebuf + cnt, ".rej", 5);43334334 rej = fopen(namebuf, "w");4335 if (!rej)4336 return error(_("cannot open %s: %s"), namebuf, strerror(errno));43374338 /* Normal git tools never deal with .rej, so do not pretend4339 * this is a git patch by saying --git or giving extended4340 * headers. While at it, maybe please "kompare" that wants4341 * the trailing TAB and some garbage at the end of line ;-).4342 */4343 fprintf(rej, "diff a/%s b/%s\t(rejected hunks)\n",4344 patch->new_name, patch->new_name);4345 for (cnt = 1, frag = patch->fragments;4346 frag;4347 cnt++, frag = frag->next) {4348 if (!frag->rejected) {4349 fprintf_ln(stderr, _("Hunk #%d applied cleanly."), cnt);4350 continue;4351 }4352 fprintf_ln(stderr, _("Rejected hunk #%d."), cnt);4353 fprintf(rej, "%.*s", frag->size, frag->patch);4354 if (frag->patch[frag->size-1] != '\n')4355 fputc('\n', rej);4356 }4357 fclose(rej);4358 return -1;4359}43604361static int write_out_results(struct patch *list)4362{4363 int phase;4364 int errs = 0;4365 struct patch *l;4366 struct string_list cpath = STRING_LIST_INIT_DUP;43674368 for (phase = 0; phase < 2; phase++) {4369 l = list;4370 while (l) {4371 if (l->rejected)4372 errs = 1;4373 else {4374 write_out_one_result(l, phase);4375 if (phase == 1) {4376 if (write_out_one_reject(l))4377 errs = 1;4378 if (l->conflicted_threeway) {4379 string_list_append(&cpath, l->new_name);4380 errs = 1;4381 }4382 }4383 }4384 l = l->next;4385 }4386 }43874388 if (cpath.nr) {4389 struct string_list_item *item;43904391 string_list_sort(&cpath);4392 for_each_string_list_item(item, &cpath)4393 fprintf(stderr, "U %s\n", item->string);4394 string_list_clear(&cpath, 0);43954396 rerere(0);4397 }43984399 return errs;4400}44014402static struct lock_file lock_file;44034404#define INACCURATE_EOF (1<<0)4405#define RECOUNT (1<<1)44064407static int apply_patch(struct apply_state *state,4408 int fd,4409 const char *filename,4410 int options)4411{4412 size_t offset;4413 struct strbuf buf = STRBUF_INIT; /* owns the patch text */4414 struct patch *list = NULL, **listp = &list;4415 int skipped_patch = 0;44164417 patch_input_file = filename;4418 read_patch_file(&buf, fd);4419 offset = 0;4420 while (offset < buf.len) {4421 struct patch *patch;4422 int nr;44234424 patch = xcalloc(1, sizeof(*patch));4425 patch->inaccurate_eof = !!(options & INACCURATE_EOF);4426 patch->recount = !!(options & RECOUNT);4427 nr = parse_chunk(state, buf.buf + offset, buf.len - offset, patch);4428 if (nr < 0) {4429 free_patch(patch);4430 break;4431 }4432 if (state->apply_in_reverse)4433 reverse_patches(patch);4434 if (use_patch(state, patch)) {4435 patch_stats(patch);4436 *listp = patch;4437 listp = &patch->next;4438 }4439 else {4440 if (apply_verbosely)4441 say_patch_name(stderr, _("Skipped patch '%s'."), patch);4442 free_patch(patch);4443 skipped_patch++;4444 }4445 offset += nr;4446 }44474448 if (!list && !skipped_patch)4449 die(_("unrecognized input"));44504451 if (whitespace_error && (ws_error_action == die_on_ws_error))4452 apply = 0;44534454 update_index = state->check_index && apply;4455 if (update_index && newfd < 0)4456 newfd = hold_locked_index(&lock_file, 1);44574458 if (state->check_index) {4459 if (read_cache() < 0)4460 die(_("unable to read index file"));4461 }44624463 if ((state->check || apply) &&4464 check_patch_list(state, list) < 0 &&4465 !apply_with_reject)4466 exit(1);44674468 if (apply && write_out_results(list)) {4469 if (apply_with_reject)4470 exit(1);4471 /* with --3way, we still need to write the index out */4472 return 1;4473 }44744475 if (fake_ancestor)4476 build_fake_ancestor(list, fake_ancestor);44774478 if (diffstat)4479 stat_patch_list(list);44804481 if (numstat)4482 numstat_patch_list(list);44834484 if (summary)4485 summary_patch_list(list);44864487 free_patch_list(list);4488 strbuf_release(&buf);4489 string_list_clear(&fn_table, 0);4490 return 0;4491}44924493static void git_apply_config(void)4494{4495 git_config_get_string_const("apply.whitespace", &apply_default_whitespace);4496 git_config_get_string_const("apply.ignorewhitespace", &apply_default_ignorewhitespace);4497 git_config(git_default_config, NULL);4498}44994500static int option_parse_exclude(const struct option *opt,4501 const char *arg, int unset)4502{4503 add_name_limit(arg, 1);4504 return 0;4505}45064507static int option_parse_include(const struct option *opt,4508 const char *arg, int unset)4509{4510 add_name_limit(arg, 0);4511 has_include = 1;4512 return 0;4513}45144515static int option_parse_p(const struct option *opt,4516 const char *arg, int unset)4517{4518 state_p_value = atoi(arg);4519 p_value_known = 1;4520 return 0;4521}45224523static int option_parse_space_change(const struct option *opt,4524 const char *arg, int unset)4525{4526 if (unset)4527 ws_ignore_action = ignore_ws_none;4528 else4529 ws_ignore_action = ignore_ws_change;4530 return 0;4531}45324533static int option_parse_whitespace(const struct option *opt,4534 const char *arg, int unset)4535{4536 const char **whitespace_option = opt->value;45374538 *whitespace_option = arg;4539 parse_whitespace_option(arg);4540 return 0;4541}45424543static int option_parse_directory(const struct option *opt,4544 const char *arg, int unset)4545{4546 strbuf_reset(&root);4547 strbuf_addstr(&root, arg);4548 strbuf_complete(&root, '/');4549 return 0;4550}45514552static void init_apply_state(struct apply_state *state, const char *prefix)4553{4554 memset(state, 0, sizeof(*state));4555 state->prefix = prefix;4556 state->prefix_length = state->prefix ? strlen(state->prefix) : 0;45574558 git_apply_config();4559 if (apply_default_whitespace)4560 parse_whitespace_option(apply_default_whitespace);4561 if (apply_default_ignorewhitespace)4562 parse_ignorewhitespace_option(apply_default_ignorewhitespace);4563}45644565static void clear_apply_state(struct apply_state *state)4566{4567 /* empty for now */4568}45694570int cmd_apply(int argc, const char **argv, const char *prefix)4571{4572 int i;4573 int errs = 0;4574 int is_not_gitdir = !startup_info->have_repository;4575 int force_apply = 0;4576 int options = 0;4577 int read_stdin = 1;4578 struct apply_state state;45794580 const char *whitespace_option = NULL;45814582 struct option builtin_apply_options[] = {4583 { OPTION_CALLBACK, 0, "exclude", NULL, N_("path"),4584 N_("don't apply changes matching the given path"),4585 0, option_parse_exclude },4586 { OPTION_CALLBACK, 0, "include", NULL, N_("path"),4587 N_("apply changes matching the given path"),4588 0, option_parse_include },4589 { OPTION_CALLBACK, 'p', NULL, NULL, N_("num"),4590 N_("remove <num> leading slashes from traditional diff paths"),4591 0, option_parse_p },4592 OPT_BOOL(0, "no-add", &no_add,4593 N_("ignore additions made by the patch")),4594 OPT_BOOL(0, "stat", &diffstat,4595 N_("instead of applying the patch, output diffstat for the input")),4596 OPT_NOOP_NOARG(0, "allow-binary-replacement"),4597 OPT_NOOP_NOARG(0, "binary"),4598 OPT_BOOL(0, "numstat", &numstat,4599 N_("show number of added and deleted lines in decimal notation")),4600 OPT_BOOL(0, "summary", &summary,4601 N_("instead of applying the patch, output a summary for the input")),4602 OPT_BOOL(0, "check", &state.check,4603 N_("instead of applying the patch, see if the patch is applicable")),4604 OPT_BOOL(0, "index", &state.check_index,4605 N_("make sure the patch is applicable to the current index")),4606 OPT_BOOL(0, "cached", &cached,4607 N_("apply a patch without touching the working tree")),4608 OPT_BOOL(0, "unsafe-paths", &unsafe_paths,4609 N_("accept a patch that touches outside the working area")),4610 OPT_BOOL(0, "apply", &force_apply,4611 N_("also apply the patch (use with --stat/--summary/--check)")),4612 OPT_BOOL('3', "3way", &threeway,4613 N_( "attempt three-way merge if a patch does not apply")),4614 OPT_FILENAME(0, "build-fake-ancestor", &fake_ancestor,4615 N_("build a temporary index based on embedded index information")),4616 /* Think twice before adding "--nul" synonym to this */4617 OPT_SET_INT('z', NULL, &line_termination,4618 N_("paths are separated with NUL character"), '\0'),4619 OPT_INTEGER('C', NULL, &p_context,4620 N_("ensure at least <n> lines of context match")),4621 { OPTION_CALLBACK, 0, "whitespace", &whitespace_option, N_("action"),4622 N_("detect new or modified lines that have whitespace errors"),4623 0, option_parse_whitespace },4624 { OPTION_CALLBACK, 0, "ignore-space-change", NULL, NULL,4625 N_("ignore changes in whitespace when finding context"),4626 PARSE_OPT_NOARG, option_parse_space_change },4627 { OPTION_CALLBACK, 0, "ignore-whitespace", NULL, NULL,4628 N_("ignore changes in whitespace when finding context"),4629 PARSE_OPT_NOARG, option_parse_space_change },4630 OPT_BOOL('R', "reverse", &state.apply_in_reverse,4631 N_("apply the patch in reverse")),4632 OPT_BOOL(0, "unidiff-zero", &state.unidiff_zero,4633 N_("don't expect at least one line of context")),4634 OPT_BOOL(0, "reject", &apply_with_reject,4635 N_("leave the rejected hunks in corresponding *.rej files")),4636 OPT_BOOL(0, "allow-overlap", &allow_overlap,4637 N_("allow overlapping hunks")),4638 OPT__VERBOSE(&apply_verbosely, N_("be verbose")),4639 OPT_BIT(0, "inaccurate-eof", &options,4640 N_("tolerate incorrectly detected missing new-line at the end of file"),4641 INACCURATE_EOF),4642 OPT_BIT(0, "recount", &options,4643 N_("do not trust the line counts in the hunk headers"),4644 RECOUNT),4645 { OPTION_CALLBACK, 0, "directory", NULL, N_("root"),4646 N_("prepend <root> to all filenames"),4647 0, option_parse_directory },4648 OPT_END()4649 };46504651 init_apply_state(&state, prefix);46524653 argc = parse_options(argc, argv, state.prefix, builtin_apply_options,4654 apply_usage, 0);46554656 if (apply_with_reject && threeway)4657 die("--reject and --3way cannot be used together.");4658 if (cached && threeway)4659 die("--cached and --3way cannot be used together.");4660 if (threeway) {4661 if (is_not_gitdir)4662 die(_("--3way outside a repository"));4663 state.check_index = 1;4664 }4665 if (apply_with_reject)4666 apply = apply_verbosely = 1;4667 if (!force_apply && (diffstat || numstat || summary || state.check || fake_ancestor))4668 apply = 0;4669 if (state.check_index && is_not_gitdir)4670 die(_("--index outside a repository"));4671 if (cached) {4672 if (is_not_gitdir)4673 die(_("--cached outside a repository"));4674 state.check_index = 1;4675 }4676 if (state.check_index)4677 unsafe_paths = 0;46784679 for (i = 0; i < argc; i++) {4680 const char *arg = argv[i];4681 int fd;46824683 if (!strcmp(arg, "-")) {4684 errs |= apply_patch(&state, 0, "<stdin>", options);4685 read_stdin = 0;4686 continue;4687 } else if (0 < state.prefix_length)4688 arg = prefix_filename(state.prefix,4689 state.prefix_length,4690 arg);46914692 fd = open(arg, O_RDONLY);4693 if (fd < 0)4694 die_errno(_("can't open patch '%s'"), arg);4695 read_stdin = 0;4696 set_default_whitespace_mode(whitespace_option);4697 errs |= apply_patch(&state, fd, arg, options);4698 close(fd);4699 }4700 set_default_whitespace_mode(whitespace_option);4701 if (read_stdin)4702 errs |= apply_patch(&state, 0, "<stdin>", options);4703 if (whitespace_error) {4704 if (squelch_whitespace_errors &&4705 squelch_whitespace_errors < whitespace_error) {4706 int squelched =4707 whitespace_error - squelch_whitespace_errors;4708 warning(Q_("squelched %d whitespace error",4709 "squelched %d whitespace errors",4710 squelched),4711 squelched);4712 }4713 if (ws_error_action == die_on_ws_error)4714 die(Q_("%d line adds whitespace errors.",4715 "%d lines add whitespace errors.",4716 whitespace_error),4717 whitespace_error);4718 if (applied_after_fixing_ws && apply)4719 warning("%d line%s applied after"4720 " fixing whitespace errors.",4721 applied_after_fixing_ws,4722 applied_after_fixing_ws == 1 ? "" : "s");4723 else if (whitespace_error)4724 warning(Q_("%d line adds whitespace errors.",4725 "%d lines add whitespace errors.",4726 whitespace_error),4727 whitespace_error);4728 }47294730 if (update_index) {4731 if (write_locked_index(&the_index, &lock_file, COMMIT_LOCK))4732 die(_("Unable to write new index file"));4733 }47344735 clear_apply_state(&state);47364737 return !!errs;4738}