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 24/* 25 * --check turns on checking that the working tree matches the 26 * files that are being modified, but doesn't apply the patch 27 * --stat does just a diffstat, and doesn't actually apply 28 * --numstat does numeric diffstat, and doesn't actually apply 29 * --index-info shows the old and new index info for paths if available. 30 * --index updates the cache as well. 31 * --cached updates only the cache without ever touching the working tree. 32 */ 33static const char *prefix; 34static int prefix_length = -1; 35static int newfd = -1; 36 37static int unidiff_zero; 38static int p_value = 1; 39static int p_value_known; 40static int check_index; 41static int update_index; 42static int cached; 43static int diffstat; 44static int numstat; 45static int summary; 46static int check; 47static int apply = 1; 48static int apply_in_reverse; 49static int apply_with_reject; 50static int apply_verbosely; 51static int allow_overlap; 52static int no_add; 53static int threeway; 54static int unsafe_paths; 55static const char *fake_ancestor; 56static int line_termination = '\n'; 57static unsigned int p_context = UINT_MAX; 58static const char * const apply_usage[] = { 59 N_("git apply [<options>] [<patch>...]"), 60 NULL 61}; 62 63static enum ws_error_action { 64 nowarn_ws_error, 65 warn_on_ws_error, 66 die_on_ws_error, 67 correct_ws_error 68} ws_error_action = warn_on_ws_error; 69static int whitespace_error; 70static int squelch_whitespace_errors = 5; 71static int applied_after_fixing_ws; 72 73static enum ws_ignore { 74 ignore_ws_none, 75 ignore_ws_change 76} ws_ignore_action = ignore_ws_none; 77 78 79static const char *patch_input_file; 80static struct strbuf root = STRBUF_INIT; 81static int read_stdin = 1; 82static int options; 83 84static void parse_whitespace_option(const char *option) 85{ 86 if (!option) { 87 ws_error_action = warn_on_ws_error; 88 return; 89 } 90 if (!strcmp(option, "warn")) { 91 ws_error_action = warn_on_ws_error; 92 return; 93 } 94 if (!strcmp(option, "nowarn")) { 95 ws_error_action = nowarn_ws_error; 96 return; 97 } 98 if (!strcmp(option, "error")) { 99 ws_error_action = die_on_ws_error; 100 return; 101 } 102 if (!strcmp(option, "error-all")) { 103 ws_error_action = die_on_ws_error; 104 squelch_whitespace_errors = 0; 105 return; 106 } 107 if (!strcmp(option, "strip") || !strcmp(option, "fix")) { 108 ws_error_action = correct_ws_error; 109 return; 110 } 111 die(_("unrecognized whitespace option '%s'"), option); 112} 113 114static void parse_ignorewhitespace_option(const char *option) 115{ 116 if (!option || !strcmp(option, "no") || 117 !strcmp(option, "false") || !strcmp(option, "never") || 118 !strcmp(option, "none")) { 119 ws_ignore_action = ignore_ws_none; 120 return; 121 } 122 if (!strcmp(option, "change")) { 123 ws_ignore_action = ignore_ws_change; 124 return; 125 } 126 die(_("unrecognized whitespace ignore option '%s'"), option); 127} 128 129static void set_default_whitespace_mode(const char *whitespace_option) 130{ 131 if (!whitespace_option && !apply_default_whitespace) 132 ws_error_action = (apply ? warn_on_ws_error : nowarn_ws_error); 133} 134 135/* 136 * For "diff-stat" like behaviour, we keep track of the biggest change 137 * we've seen, and the longest filename. That allows us to do simple 138 * scaling. 139 */ 140static int max_change, max_len; 141 142/* 143 * Various "current state", notably line numbers and what 144 * file (and how) we're patching right now.. The "is_xxxx" 145 * things are flags, where -1 means "don't know yet". 146 */ 147static int linenr = 1; 148 149/* 150 * This represents one "hunk" from a patch, starting with 151 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The 152 * patch text is pointed at by patch, and its byte length 153 * is stored in size. leading and trailing are the number 154 * of context lines. 155 */ 156struct fragment { 157 unsigned long leading, trailing; 158 unsigned long oldpos, oldlines; 159 unsigned long newpos, newlines; 160 /* 161 * 'patch' is usually borrowed from buf in apply_patch(), 162 * but some codepaths store an allocated buffer. 163 */ 164 const char *patch; 165 unsigned free_patch:1, 166 rejected:1; 167 int size; 168 int linenr; 169 struct fragment *next; 170}; 171 172/* 173 * When dealing with a binary patch, we reuse "leading" field 174 * to store the type of the binary hunk, either deflated "delta" 175 * or deflated "literal". 176 */ 177#define binary_patch_method leading 178#define BINARY_DELTA_DEFLATED 1 179#define BINARY_LITERAL_DEFLATED 2 180 181/* 182 * This represents a "patch" to a file, both metainfo changes 183 * such as creation/deletion, filemode and content changes represented 184 * as a series of fragments. 185 */ 186struct patch { 187 char *new_name, *old_name, *def_name; 188 unsigned int old_mode, new_mode; 189 int is_new, is_delete; /* -1 = unknown, 0 = false, 1 = true */ 190 int rejected; 191 unsigned ws_rule; 192 int lines_added, lines_deleted; 193 int score; 194 unsigned int is_toplevel_relative:1; 195 unsigned int inaccurate_eof:1; 196 unsigned int is_binary:1; 197 unsigned int is_copy:1; 198 unsigned int is_rename:1; 199 unsigned int recount:1; 200 unsigned int conflicted_threeway:1; 201 unsigned int direct_to_threeway:1; 202 struct fragment *fragments; 203 char *result; 204 size_t resultsize; 205 char old_sha1_prefix[41]; 206 char new_sha1_prefix[41]; 207 struct patch *next; 208 209 /* three-way fallback result */ 210 struct object_id threeway_stage[3]; 211}; 212 213static void free_fragment_list(struct fragment *list) 214{ 215 while (list) { 216 struct fragment *next = list->next; 217 if (list->free_patch) 218 free((char *)list->patch); 219 free(list); 220 list = next; 221 } 222} 223 224static void free_patch(struct patch *patch) 225{ 226 free_fragment_list(patch->fragments); 227 free(patch->def_name); 228 free(patch->old_name); 229 free(patch->new_name); 230 free(patch->result); 231 free(patch); 232} 233 234static void free_patch_list(struct patch *list) 235{ 236 while (list) { 237 struct patch *next = list->next; 238 free_patch(list); 239 list = next; 240 } 241} 242 243/* 244 * A line in a file, len-bytes long (includes the terminating LF, 245 * except for an incomplete line at the end if the file ends with 246 * one), and its contents hashes to 'hash'. 247 */ 248struct line { 249 size_t len; 250 unsigned hash : 24; 251 unsigned flag : 8; 252#define LINE_COMMON 1 253#define LINE_PATCHED 2 254}; 255 256/* 257 * This represents a "file", which is an array of "lines". 258 */ 259struct image { 260 char *buf; 261 size_t len; 262 size_t nr; 263 size_t alloc; 264 struct line *line_allocated; 265 struct line *line; 266}; 267 268/* 269 * Records filenames that have been touched, in order to handle 270 * the case where more than one patches touch the same file. 271 */ 272 273static struct string_list fn_table; 274 275static uint32_t hash_line(const char *cp, size_t len) 276{ 277 size_t i; 278 uint32_t h; 279 for (i = 0, h = 0; i < len; i++) { 280 if (!isspace(cp[i])) { 281 h = h * 3 + (cp[i] & 0xff); 282 } 283 } 284 return h; 285} 286 287/* 288 * Compare lines s1 of length n1 and s2 of length n2, ignoring 289 * whitespace difference. Returns 1 if they match, 0 otherwise 290 */ 291static int fuzzy_matchlines(const char *s1, size_t n1, 292 const char *s2, size_t n2) 293{ 294 const char *last1 = s1 + n1 - 1; 295 const char *last2 = s2 + n2 - 1; 296 int result = 0; 297 298 /* ignore line endings */ 299 while ((*last1 == '\r') || (*last1 == '\n')) 300 last1--; 301 while ((*last2 == '\r') || (*last2 == '\n')) 302 last2--; 303 304 /* skip leading whitespaces, if both begin with whitespace */ 305 if (s1 <= last1 && s2 <= last2 && isspace(*s1) && isspace(*s2)) { 306 while (isspace(*s1) && (s1 <= last1)) 307 s1++; 308 while (isspace(*s2) && (s2 <= last2)) 309 s2++; 310 } 311 /* early return if both lines are empty */ 312 if ((s1 > last1) && (s2 > last2)) 313 return 1; 314 while (!result) { 315 result = *s1++ - *s2++; 316 /* 317 * Skip whitespace inside. We check for whitespace on 318 * both buffers because we don't want "a b" to match 319 * "ab" 320 */ 321 if (isspace(*s1) && isspace(*s2)) { 322 while (isspace(*s1) && s1 <= last1) 323 s1++; 324 while (isspace(*s2) && s2 <= last2) 325 s2++; 326 } 327 /* 328 * If we reached the end on one side only, 329 * lines don't match 330 */ 331 if ( 332 ((s2 > last2) && (s1 <= last1)) || 333 ((s1 > last1) && (s2 <= last2))) 334 return 0; 335 if ((s1 > last1) && (s2 > last2)) 336 break; 337 } 338 339 return !result; 340} 341 342static void add_line_info(struct image *img, const char *bol, size_t len, unsigned flag) 343{ 344 ALLOC_GROW(img->line_allocated, img->nr + 1, img->alloc); 345 img->line_allocated[img->nr].len = len; 346 img->line_allocated[img->nr].hash = hash_line(bol, len); 347 img->line_allocated[img->nr].flag = flag; 348 img->nr++; 349} 350 351/* 352 * "buf" has the file contents to be patched (read from various sources). 353 * attach it to "image" and add line-based index to it. 354 * "image" now owns the "buf". 355 */ 356static void prepare_image(struct image *image, char *buf, size_t len, 357 int prepare_linetable) 358{ 359 const char *cp, *ep; 360 361 memset(image, 0, sizeof(*image)); 362 image->buf = buf; 363 image->len = len; 364 365 if (!prepare_linetable) 366 return; 367 368 ep = image->buf + image->len; 369 cp = image->buf; 370 while (cp < ep) { 371 const char *next; 372 for (next = cp; next < ep && *next != '\n'; next++) 373 ; 374 if (next < ep) 375 next++; 376 add_line_info(image, cp, next - cp, 0); 377 cp = next; 378 } 379 image->line = image->line_allocated; 380} 381 382static void clear_image(struct image *image) 383{ 384 free(image->buf); 385 free(image->line_allocated); 386 memset(image, 0, sizeof(*image)); 387} 388 389/* fmt must contain _one_ %s and no other substitution */ 390static void say_patch_name(FILE *output, const char *fmt, struct patch *patch) 391{ 392 struct strbuf sb = STRBUF_INIT; 393 394 if (patch->old_name && patch->new_name && 395 strcmp(patch->old_name, patch->new_name)) { 396 quote_c_style(patch->old_name, &sb, NULL, 0); 397 strbuf_addstr(&sb, " => "); 398 quote_c_style(patch->new_name, &sb, NULL, 0); 399 } else { 400 const char *n = patch->new_name; 401 if (!n) 402 n = patch->old_name; 403 quote_c_style(n, &sb, NULL, 0); 404 } 405 fprintf(output, fmt, sb.buf); 406 fputc('\n', output); 407 strbuf_release(&sb); 408} 409 410#define SLOP (16) 411 412static void read_patch_file(struct strbuf *sb, int fd) 413{ 414 if (strbuf_read(sb, fd, 0) < 0) 415 die_errno("git apply: failed to read"); 416 417 /* 418 * Make sure that we have some slop in the buffer 419 * so that we can do speculative "memcmp" etc, and 420 * see to it that it is NUL-filled. 421 */ 422 strbuf_grow(sb, SLOP); 423 memset(sb->buf + sb->len, 0, SLOP); 424} 425 426static unsigned long linelen(const char *buffer, unsigned long size) 427{ 428 unsigned long len = 0; 429 while (size--) { 430 len++; 431 if (*buffer++ == '\n') 432 break; 433 } 434 return len; 435} 436 437static int is_dev_null(const char *str) 438{ 439 return skip_prefix(str, "/dev/null", &str) && isspace(*str); 440} 441 442#define TERM_SPACE 1 443#define TERM_TAB 2 444 445static int name_terminate(const char *name, int namelen, int c, int terminate) 446{ 447 if (c == ' ' && !(terminate & TERM_SPACE)) 448 return 0; 449 if (c == '\t' && !(terminate & TERM_TAB)) 450 return 0; 451 452 return 1; 453} 454 455/* remove double slashes to make --index work with such filenames */ 456static char *squash_slash(char *name) 457{ 458 int i = 0, j = 0; 459 460 if (!name) 461 return NULL; 462 463 while (name[i]) { 464 if ((name[j++] = name[i++]) == '/') 465 while (name[i] == '/') 466 i++; 467 } 468 name[j] = '\0'; 469 return name; 470} 471 472static char *find_name_gnu(const char *line, const char *def, int p_value) 473{ 474 struct strbuf name = STRBUF_INIT; 475 char *cp; 476 477 /* 478 * Proposed "new-style" GNU patch/diff format; see 479 * http://marc.info/?l=git&m=112927316408690&w=2 480 */ 481 if (unquote_c_style(&name, line, NULL)) { 482 strbuf_release(&name); 483 return NULL; 484 } 485 486 for (cp = name.buf; p_value; p_value--) { 487 cp = strchr(cp, '/'); 488 if (!cp) { 489 strbuf_release(&name); 490 return NULL; 491 } 492 cp++; 493 } 494 495 strbuf_remove(&name, 0, cp - name.buf); 496 if (root.len) 497 strbuf_insert(&name, 0, root.buf, root.len); 498 return squash_slash(strbuf_detach(&name, NULL)); 499} 500 501static size_t sane_tz_len(const char *line, size_t len) 502{ 503 const char *tz, *p; 504 505 if (len < strlen(" +0500") || line[len-strlen(" +0500")] != ' ') 506 return 0; 507 tz = line + len - strlen(" +0500"); 508 509 if (tz[1] != '+' && tz[1] != '-') 510 return 0; 511 512 for (p = tz + 2; p != line + len; p++) 513 if (!isdigit(*p)) 514 return 0; 515 516 return line + len - tz; 517} 518 519static size_t tz_with_colon_len(const char *line, size_t len) 520{ 521 const char *tz, *p; 522 523 if (len < strlen(" +08:00") || line[len - strlen(":00")] != ':') 524 return 0; 525 tz = line + len - strlen(" +08:00"); 526 527 if (tz[0] != ' ' || (tz[1] != '+' && tz[1] != '-')) 528 return 0; 529 p = tz + 2; 530 if (!isdigit(*p++) || !isdigit(*p++) || *p++ != ':' || 531 !isdigit(*p++) || !isdigit(*p++)) 532 return 0; 533 534 return line + len - tz; 535} 536 537static size_t date_len(const char *line, size_t len) 538{ 539 const char *date, *p; 540 541 if (len < strlen("72-02-05") || line[len-strlen("-05")] != '-') 542 return 0; 543 p = date = line + len - strlen("72-02-05"); 544 545 if (!isdigit(*p++) || !isdigit(*p++) || *p++ != '-' || 546 !isdigit(*p++) || !isdigit(*p++) || *p++ != '-' || 547 !isdigit(*p++) || !isdigit(*p++)) /* Not a date. */ 548 return 0; 549 550 if (date - line >= strlen("19") && 551 isdigit(date[-1]) && isdigit(date[-2])) /* 4-digit year */ 552 date -= strlen("19"); 553 554 return line + len - date; 555} 556 557static size_t short_time_len(const char *line, size_t len) 558{ 559 const char *time, *p; 560 561 if (len < strlen(" 07:01:32") || line[len-strlen(":32")] != ':') 562 return 0; 563 p = time = line + len - strlen(" 07:01:32"); 564 565 /* Permit 1-digit hours? */ 566 if (*p++ != ' ' || 567 !isdigit(*p++) || !isdigit(*p++) || *p++ != ':' || 568 !isdigit(*p++) || !isdigit(*p++) || *p++ != ':' || 569 !isdigit(*p++) || !isdigit(*p++)) /* Not a time. */ 570 return 0; 571 572 return line + len - time; 573} 574 575static size_t fractional_time_len(const char *line, size_t len) 576{ 577 const char *p; 578 size_t n; 579 580 /* Expected format: 19:41:17.620000023 */ 581 if (!len || !isdigit(line[len - 1])) 582 return 0; 583 p = line + len - 1; 584 585 /* Fractional seconds. */ 586 while (p > line && isdigit(*p)) 587 p--; 588 if (*p != '.') 589 return 0; 590 591 /* Hours, minutes, and whole seconds. */ 592 n = short_time_len(line, p - line); 593 if (!n) 594 return 0; 595 596 return line + len - p + n; 597} 598 599static size_t trailing_spaces_len(const char *line, size_t len) 600{ 601 const char *p; 602 603 /* Expected format: ' ' x (1 or more) */ 604 if (!len || line[len - 1] != ' ') 605 return 0; 606 607 p = line + len; 608 while (p != line) { 609 p--; 610 if (*p != ' ') 611 return line + len - (p + 1); 612 } 613 614 /* All spaces! */ 615 return len; 616} 617 618static size_t diff_timestamp_len(const char *line, size_t len) 619{ 620 const char *end = line + len; 621 size_t n; 622 623 /* 624 * Posix: 2010-07-05 19:41:17 625 * GNU: 2010-07-05 19:41:17.620000023 -0500 626 */ 627 628 if (!isdigit(end[-1])) 629 return 0; 630 631 n = sane_tz_len(line, end - line); 632 if (!n) 633 n = tz_with_colon_len(line, end - line); 634 end -= n; 635 636 n = short_time_len(line, end - line); 637 if (!n) 638 n = fractional_time_len(line, end - line); 639 end -= n; 640 641 n = date_len(line, end - line); 642 if (!n) /* No date. Too bad. */ 643 return 0; 644 end -= n; 645 646 if (end == line) /* No space before date. */ 647 return 0; 648 if (end[-1] == '\t') { /* Success! */ 649 end--; 650 return line + len - end; 651 } 652 if (end[-1] != ' ') /* No space before date. */ 653 return 0; 654 655 /* Whitespace damage. */ 656 end -= trailing_spaces_len(line, end - line); 657 return line + len - end; 658} 659 660static char *find_name_common(const char *line, const char *def, 661 int p_value, const char *end, int terminate) 662{ 663 int len; 664 const char *start = NULL; 665 666 if (p_value == 0) 667 start = line; 668 while (line != end) { 669 char c = *line; 670 671 if (!end && isspace(c)) { 672 if (c == '\n') 673 break; 674 if (name_terminate(start, line-start, c, terminate)) 675 break; 676 } 677 line++; 678 if (c == '/' && !--p_value) 679 start = line; 680 } 681 if (!start) 682 return squash_slash(xstrdup_or_null(def)); 683 len = line - start; 684 if (!len) 685 return squash_slash(xstrdup_or_null(def)); 686 687 /* 688 * Generally we prefer the shorter name, especially 689 * if the other one is just a variation of that with 690 * something else tacked on to the end (ie "file.orig" 691 * or "file~"). 692 */ 693 if (def) { 694 int deflen = strlen(def); 695 if (deflen < len && !strncmp(start, def, deflen)) 696 return squash_slash(xstrdup(def)); 697 } 698 699 if (root.len) { 700 char *ret = xstrfmt("%s%.*s", root.buf, len, start); 701 return squash_slash(ret); 702 } 703 704 return squash_slash(xmemdupz(start, len)); 705} 706 707static char *find_name(const char *line, char *def, int p_value, int terminate) 708{ 709 if (*line == '"') { 710 char *name = find_name_gnu(line, def, p_value); 711 if (name) 712 return name; 713 } 714 715 return find_name_common(line, def, p_value, NULL, terminate); 716} 717 718static char *find_name_traditional(const char *line, char *def, int p_value) 719{ 720 size_t len; 721 size_t date_len; 722 723 if (*line == '"') { 724 char *name = find_name_gnu(line, def, p_value); 725 if (name) 726 return name; 727 } 728 729 len = strchrnul(line, '\n') - line; 730 date_len = diff_timestamp_len(line, len); 731 if (!date_len) 732 return find_name_common(line, def, p_value, NULL, TERM_TAB); 733 len -= date_len; 734 735 return find_name_common(line, def, p_value, line + len, 0); 736} 737 738static int count_slashes(const char *cp) 739{ 740 int cnt = 0; 741 char ch; 742 743 while ((ch = *cp++)) 744 if (ch == '/') 745 cnt++; 746 return cnt; 747} 748 749/* 750 * Given the string after "--- " or "+++ ", guess the appropriate 751 * p_value for the given patch. 752 */ 753static int guess_p_value(const char *nameline) 754{ 755 char *name, *cp; 756 int val = -1; 757 758 if (is_dev_null(nameline)) 759 return -1; 760 name = find_name_traditional(nameline, NULL, 0); 761 if (!name) 762 return -1; 763 cp = strchr(name, '/'); 764 if (!cp) 765 val = 0; 766 else if (prefix) { 767 /* 768 * Does it begin with "a/$our-prefix" and such? Then this is 769 * very likely to apply to our directory. 770 */ 771 if (!strncmp(name, prefix, prefix_length)) 772 val = count_slashes(prefix); 773 else { 774 cp++; 775 if (!strncmp(cp, prefix, prefix_length)) 776 val = count_slashes(prefix) + 1; 777 } 778 } 779 free(name); 780 return val; 781} 782 783/* 784 * Does the ---/+++ line have the POSIX timestamp after the last HT? 785 * GNU diff puts epoch there to signal a creation/deletion event. Is 786 * this such a timestamp? 787 */ 788static int has_epoch_timestamp(const char *nameline) 789{ 790 /* 791 * We are only interested in epoch timestamp; any non-zero 792 * fraction cannot be one, hence "(\.0+)?" in the regexp below. 793 * For the same reason, the date must be either 1969-12-31 or 794 * 1970-01-01, and the seconds part must be "00". 795 */ 796 const char stamp_regexp[] = 797 "^(1969-12-31|1970-01-01)" 798 " " 799 "[0-2][0-9]:[0-5][0-9]:00(\\.0+)?" 800 " " 801 "([-+][0-2][0-9]:?[0-5][0-9])\n"; 802 const char *timestamp = NULL, *cp, *colon; 803 static regex_t *stamp; 804 regmatch_t m[10]; 805 int zoneoffset; 806 int hourminute; 807 int status; 808 809 for (cp = nameline; *cp != '\n'; cp++) { 810 if (*cp == '\t') 811 timestamp = cp + 1; 812 } 813 if (!timestamp) 814 return 0; 815 if (!stamp) { 816 stamp = xmalloc(sizeof(*stamp)); 817 if (regcomp(stamp, stamp_regexp, REG_EXTENDED)) { 818 warning(_("Cannot prepare timestamp regexp %s"), 819 stamp_regexp); 820 return 0; 821 } 822 } 823 824 status = regexec(stamp, timestamp, ARRAY_SIZE(m), m, 0); 825 if (status) { 826 if (status != REG_NOMATCH) 827 warning(_("regexec returned %d for input: %s"), 828 status, timestamp); 829 return 0; 830 } 831 832 zoneoffset = strtol(timestamp + m[3].rm_so + 1, (char **) &colon, 10); 833 if (*colon == ':') 834 zoneoffset = zoneoffset * 60 + strtol(colon + 1, NULL, 10); 835 else 836 zoneoffset = (zoneoffset / 100) * 60 + (zoneoffset % 100); 837 if (timestamp[m[3].rm_so] == '-') 838 zoneoffset = -zoneoffset; 839 840 /* 841 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31 842 * (west of GMT) or 1970-01-01 (east of GMT) 843 */ 844 if ((zoneoffset < 0 && memcmp(timestamp, "1969-12-31", 10)) || 845 (0 <= zoneoffset && memcmp(timestamp, "1970-01-01", 10))) 846 return 0; 847 848 hourminute = (strtol(timestamp + 11, NULL, 10) * 60 + 849 strtol(timestamp + 14, NULL, 10) - 850 zoneoffset); 851 852 return ((zoneoffset < 0 && hourminute == 1440) || 853 (0 <= zoneoffset && !hourminute)); 854} 855 856/* 857 * Get the name etc info from the ---/+++ lines of a traditional patch header 858 * 859 * FIXME! The end-of-filename heuristics are kind of screwy. For existing 860 * files, we can happily check the index for a match, but for creating a 861 * new file we should try to match whatever "patch" does. I have no idea. 862 */ 863static void parse_traditional_patch(const char *first, const char *second, struct patch *patch) 864{ 865 char *name; 866 867 first += 4; /* skip "--- " */ 868 second += 4; /* skip "+++ " */ 869 if (!p_value_known) { 870 int p, q; 871 p = guess_p_value(first); 872 q = guess_p_value(second); 873 if (p < 0) p = q; 874 if (0 <= p && p == q) { 875 p_value = p; 876 p_value_known = 1; 877 } 878 } 879 if (is_dev_null(first)) { 880 patch->is_new = 1; 881 patch->is_delete = 0; 882 name = find_name_traditional(second, NULL, p_value); 883 patch->new_name = name; 884 } else if (is_dev_null(second)) { 885 patch->is_new = 0; 886 patch->is_delete = 1; 887 name = find_name_traditional(first, NULL, p_value); 888 patch->old_name = name; 889 } else { 890 char *first_name; 891 first_name = find_name_traditional(first, NULL, p_value); 892 name = find_name_traditional(second, first_name, p_value); 893 free(first_name); 894 if (has_epoch_timestamp(first)) { 895 patch->is_new = 1; 896 patch->is_delete = 0; 897 patch->new_name = name; 898 } else if (has_epoch_timestamp(second)) { 899 patch->is_new = 0; 900 patch->is_delete = 1; 901 patch->old_name = name; 902 } else { 903 patch->old_name = name; 904 patch->new_name = xstrdup_or_null(name); 905 } 906 } 907 if (!name) 908 die(_("unable to find filename in patch at line %d"), linenr); 909} 910 911static int gitdiff_hdrend(const char *line, struct patch *patch) 912{ 913 return -1; 914} 915 916/* 917 * We're anal about diff header consistency, to make 918 * sure that we don't end up having strange ambiguous 919 * patches floating around. 920 * 921 * As a result, gitdiff_{old|new}name() will check 922 * their names against any previous information, just 923 * to make sure.. 924 */ 925#define DIFF_OLD_NAME 0 926#define DIFF_NEW_NAME 1 927 928static char *gitdiff_verify_name(const char *line, int isnull, char *orig_name, int side) 929{ 930 if (!orig_name && !isnull) 931 return find_name(line, NULL, p_value, TERM_TAB); 932 933 if (orig_name) { 934 int len = strlen(orig_name); 935 char *another; 936 if (isnull) 937 die(_("git apply: bad git-diff - expected /dev/null, got %s on line %d"), 938 orig_name, linenr); 939 another = find_name(line, NULL, p_value, TERM_TAB); 940 if (!another || memcmp(another, orig_name, len + 1)) 941 die((side == DIFF_NEW_NAME) ? 942 _("git apply: bad git-diff - inconsistent new filename on line %d") : 943 _("git apply: bad git-diff - inconsistent old filename on line %d"), linenr); 944 free(another); 945 return orig_name; 946 } else { 947 /* expect "/dev/null" */ 948 if (memcmp("/dev/null", line, 9) || line[9] != '\n') 949 die(_("git apply: bad git-diff - expected /dev/null on line %d"), linenr); 950 return NULL; 951 } 952} 953 954static int gitdiff_oldname(const char *line, struct patch *patch) 955{ 956 char *orig = patch->old_name; 957 patch->old_name = gitdiff_verify_name(line, patch->is_new, patch->old_name, 958 DIFF_OLD_NAME); 959 if (orig != patch->old_name) 960 free(orig); 961 return 0; 962} 963 964static int gitdiff_newname(const char *line, struct patch *patch) 965{ 966 char *orig = patch->new_name; 967 patch->new_name = gitdiff_verify_name(line, patch->is_delete, patch->new_name, 968 DIFF_NEW_NAME); 969 if (orig != patch->new_name) 970 free(orig); 971 return 0; 972} 973 974static int gitdiff_oldmode(const char *line, struct patch *patch) 975{ 976 patch->old_mode = strtoul(line, NULL, 8); 977 return 0; 978} 979 980static int gitdiff_newmode(const char *line, struct patch *patch) 981{ 982 patch->new_mode = strtoul(line, NULL, 8); 983 return 0; 984} 985 986static int gitdiff_delete(const char *line, struct patch *patch) 987{ 988 patch->is_delete = 1; 989 free(patch->old_name); 990 patch->old_name = xstrdup_or_null(patch->def_name); 991 return gitdiff_oldmode(line, patch); 992} 993 994static int gitdiff_newfile(const char *line, struct patch *patch) 995{ 996 patch->is_new = 1; 997 free(patch->new_name); 998 patch->new_name = xstrdup_or_null(patch->def_name); 999 return gitdiff_newmode(line, patch);1000}10011002static int gitdiff_copysrc(const char *line, struct patch *patch)1003{1004 patch->is_copy = 1;1005 free(patch->old_name);1006 patch->old_name = find_name(line, NULL, p_value ? p_value - 1 : 0, 0);1007 return 0;1008}10091010static int gitdiff_copydst(const char *line, struct patch *patch)1011{1012 patch->is_copy = 1;1013 free(patch->new_name);1014 patch->new_name = find_name(line, NULL, p_value ? p_value - 1 : 0, 0);1015 return 0;1016}10171018static int gitdiff_renamesrc(const char *line, struct patch *patch)1019{1020 patch->is_rename = 1;1021 free(patch->old_name);1022 patch->old_name = find_name(line, NULL, p_value ? p_value - 1 : 0, 0);1023 return 0;1024}10251026static int gitdiff_renamedst(const char *line, struct patch *patch)1027{1028 patch->is_rename = 1;1029 free(patch->new_name);1030 patch->new_name = find_name(line, NULL, p_value ? p_value - 1 : 0, 0);1031 return 0;1032}10331034static int gitdiff_similarity(const char *line, struct patch *patch)1035{1036 unsigned long val = strtoul(line, NULL, 10);1037 if (val <= 100)1038 patch->score = val;1039 return 0;1040}10411042static int gitdiff_dissimilarity(const char *line, struct patch *patch)1043{1044 unsigned long val = strtoul(line, NULL, 10);1045 if (val <= 100)1046 patch->score = val;1047 return 0;1048}10491050static int gitdiff_index(const char *line, struct patch *patch)1051{1052 /*1053 * index line is N hexadecimal, "..", N hexadecimal,1054 * and optional space with octal mode.1055 */1056 const char *ptr, *eol;1057 int len;10581059 ptr = strchr(line, '.');1060 if (!ptr || ptr[1] != '.' || 40 < ptr - line)1061 return 0;1062 len = ptr - line;1063 memcpy(patch->old_sha1_prefix, line, len);1064 patch->old_sha1_prefix[len] = 0;10651066 line = ptr + 2;1067 ptr = strchr(line, ' ');1068 eol = strchrnul(line, '\n');10691070 if (!ptr || eol < ptr)1071 ptr = eol;1072 len = ptr - line;10731074 if (40 < len)1075 return 0;1076 memcpy(patch->new_sha1_prefix, line, len);1077 patch->new_sha1_prefix[len] = 0;1078 if (*ptr == ' ')1079 patch->old_mode = strtoul(ptr+1, NULL, 8);1080 return 0;1081}10821083/*1084 * This is normal for a diff that doesn't change anything: we'll fall through1085 * into the next diff. Tell the parser to break out.1086 */1087static int gitdiff_unrecognized(const char *line, struct patch *patch)1088{1089 return -1;1090}10911092/*1093 * Skip p_value leading components from "line"; as we do not accept1094 * absolute paths, return NULL in that case.1095 */1096static const char *skip_tree_prefix(const char *line, int llen)1097{1098 int nslash;1099 int i;11001101 if (!p_value)1102 return (llen && line[0] == '/') ? NULL : line;11031104 nslash = p_value;1105 for (i = 0; i < llen; i++) {1106 int ch = line[i];1107 if (ch == '/' && --nslash <= 0)1108 return (i == 0) ? NULL : &line[i + 1];1109 }1110 return NULL;1111}11121113/*1114 * This is to extract the same name that appears on "diff --git"1115 * line. We do not find and return anything if it is a rename1116 * patch, and it is OK because we will find the name elsewhere.1117 * We need to reliably find name only when it is mode-change only,1118 * creation or deletion of an empty file. In any of these cases,1119 * both sides are the same name under a/ and b/ respectively.1120 */1121static char *git_header_name(const char *line, int llen)1122{1123 const char *name;1124 const char *second = NULL;1125 size_t len, line_len;11261127 line += strlen("diff --git ");1128 llen -= strlen("diff --git ");11291130 if (*line == '"') {1131 const char *cp;1132 struct strbuf first = STRBUF_INIT;1133 struct strbuf sp = STRBUF_INIT;11341135 if (unquote_c_style(&first, line, &second))1136 goto free_and_fail1;11371138 /* strip the a/b prefix including trailing slash */1139 cp = skip_tree_prefix(first.buf, first.len);1140 if (!cp)1141 goto free_and_fail1;1142 strbuf_remove(&first, 0, cp - first.buf);11431144 /*1145 * second points at one past closing dq of name.1146 * find the second name.1147 */1148 while ((second < line + llen) && isspace(*second))1149 second++;11501151 if (line + llen <= second)1152 goto free_and_fail1;1153 if (*second == '"') {1154 if (unquote_c_style(&sp, second, NULL))1155 goto free_and_fail1;1156 cp = skip_tree_prefix(sp.buf, sp.len);1157 if (!cp)1158 goto free_and_fail1;1159 /* They must match, otherwise ignore */1160 if (strcmp(cp, first.buf))1161 goto free_and_fail1;1162 strbuf_release(&sp);1163 return strbuf_detach(&first, NULL);1164 }11651166 /* unquoted second */1167 cp = skip_tree_prefix(second, line + llen - second);1168 if (!cp)1169 goto free_and_fail1;1170 if (line + llen - cp != first.len ||1171 memcmp(first.buf, cp, first.len))1172 goto free_and_fail1;1173 return strbuf_detach(&first, NULL);11741175 free_and_fail1:1176 strbuf_release(&first);1177 strbuf_release(&sp);1178 return NULL;1179 }11801181 /* unquoted first name */1182 name = skip_tree_prefix(line, llen);1183 if (!name)1184 return NULL;11851186 /*1187 * since the first name is unquoted, a dq if exists must be1188 * the beginning of the second name.1189 */1190 for (second = name; second < line + llen; second++) {1191 if (*second == '"') {1192 struct strbuf sp = STRBUF_INIT;1193 const char *np;11941195 if (unquote_c_style(&sp, second, NULL))1196 goto free_and_fail2;11971198 np = skip_tree_prefix(sp.buf, sp.len);1199 if (!np)1200 goto free_and_fail2;12011202 len = sp.buf + sp.len - np;1203 if (len < second - name &&1204 !strncmp(np, name, len) &&1205 isspace(name[len])) {1206 /* Good */1207 strbuf_remove(&sp, 0, np - sp.buf);1208 return strbuf_detach(&sp, NULL);1209 }12101211 free_and_fail2:1212 strbuf_release(&sp);1213 return NULL;1214 }1215 }12161217 /*1218 * Accept a name only if it shows up twice, exactly the same1219 * form.1220 */1221 second = strchr(name, '\n');1222 if (!second)1223 return NULL;1224 line_len = second - name;1225 for (len = 0 ; ; len++) {1226 switch (name[len]) {1227 default:1228 continue;1229 case '\n':1230 return NULL;1231 case '\t': case ' ':1232 /*1233 * Is this the separator between the preimage1234 * and the postimage pathname? Again, we are1235 * only interested in the case where there is1236 * no rename, as this is only to set def_name1237 * and a rename patch has the names elsewhere1238 * in an unambiguous form.1239 */1240 if (!name[len + 1])1241 return NULL; /* no postimage name */1242 second = skip_tree_prefix(name + len + 1,1243 line_len - (len + 1));1244 if (!second)1245 return NULL;1246 /*1247 * Does len bytes starting at "name" and "second"1248 * (that are separated by one HT or SP we just1249 * found) exactly match?1250 */1251 if (second[len] == '\n' && !strncmp(name, second, len))1252 return xmemdupz(name, len);1253 }1254 }1255}12561257/* Verify that we recognize the lines following a git header */1258static int parse_git_header(const char *line, int len, unsigned int size, struct patch *patch)1259{1260 unsigned long offset;12611262 /* A git diff has explicit new/delete information, so we don't guess */1263 patch->is_new = 0;1264 patch->is_delete = 0;12651266 /*1267 * Some things may not have the old name in the1268 * rest of the headers anywhere (pure mode changes,1269 * or removing or adding empty files), so we get1270 * the default name from the header.1271 */1272 patch->def_name = git_header_name(line, len);1273 if (patch->def_name && root.len) {1274 char *s = xstrfmt("%s%s", root.buf, patch->def_name);1275 free(patch->def_name);1276 patch->def_name = s;1277 }12781279 line += len;1280 size -= len;1281 linenr++;1282 for (offset = len ; size > 0 ; offset += len, size -= len, line += len, linenr++) {1283 static const struct opentry {1284 const char *str;1285 int (*fn)(const char *, struct patch *);1286 } optable[] = {1287 { "@@ -", gitdiff_hdrend },1288 { "--- ", gitdiff_oldname },1289 { "+++ ", gitdiff_newname },1290 { "old mode ", gitdiff_oldmode },1291 { "new mode ", gitdiff_newmode },1292 { "deleted file mode ", gitdiff_delete },1293 { "new file mode ", gitdiff_newfile },1294 { "copy from ", gitdiff_copysrc },1295 { "copy to ", gitdiff_copydst },1296 { "rename old ", gitdiff_renamesrc },1297 { "rename new ", gitdiff_renamedst },1298 { "rename from ", gitdiff_renamesrc },1299 { "rename to ", gitdiff_renamedst },1300 { "similarity index ", gitdiff_similarity },1301 { "dissimilarity index ", gitdiff_dissimilarity },1302 { "index ", gitdiff_index },1303 { "", gitdiff_unrecognized },1304 };1305 int i;13061307 len = linelen(line, size);1308 if (!len || line[len-1] != '\n')1309 break;1310 for (i = 0; i < ARRAY_SIZE(optable); i++) {1311 const struct opentry *p = optable + i;1312 int oplen = strlen(p->str);1313 if (len < oplen || memcmp(p->str, line, oplen))1314 continue;1315 if (p->fn(line + oplen, patch) < 0)1316 return offset;1317 break;1318 }1319 }13201321 return offset;1322}13231324static int parse_num(const char *line, unsigned long *p)1325{1326 char *ptr;13271328 if (!isdigit(*line))1329 return 0;1330 *p = strtoul(line, &ptr, 10);1331 return ptr - line;1332}13331334static int parse_range(const char *line, int len, int offset, const char *expect,1335 unsigned long *p1, unsigned long *p2)1336{1337 int digits, ex;13381339 if (offset < 0 || offset >= len)1340 return -1;1341 line += offset;1342 len -= offset;13431344 digits = parse_num(line, p1);1345 if (!digits)1346 return -1;13471348 offset += digits;1349 line += digits;1350 len -= digits;13511352 *p2 = 1;1353 if (*line == ',') {1354 digits = parse_num(line+1, p2);1355 if (!digits)1356 return -1;13571358 offset += digits+1;1359 line += digits+1;1360 len -= digits+1;1361 }13621363 ex = strlen(expect);1364 if (ex > len)1365 return -1;1366 if (memcmp(line, expect, ex))1367 return -1;13681369 return offset + ex;1370}13711372static void recount_diff(const char *line, int size, struct fragment *fragment)1373{1374 int oldlines = 0, newlines = 0, ret = 0;13751376 if (size < 1) {1377 warning("recount: ignore empty hunk");1378 return;1379 }13801381 for (;;) {1382 int len = linelen(line, size);1383 size -= len;1384 line += len;13851386 if (size < 1)1387 break;13881389 switch (*line) {1390 case ' ': case '\n':1391 newlines++;1392 /* fall through */1393 case '-':1394 oldlines++;1395 continue;1396 case '+':1397 newlines++;1398 continue;1399 case '\\':1400 continue;1401 case '@':1402 ret = size < 3 || !starts_with(line, "@@ ");1403 break;1404 case 'd':1405 ret = size < 5 || !starts_with(line, "diff ");1406 break;1407 default:1408 ret = -1;1409 break;1410 }1411 if (ret) {1412 warning(_("recount: unexpected line: %.*s"),1413 (int)linelen(line, size), line);1414 return;1415 }1416 break;1417 }1418 fragment->oldlines = oldlines;1419 fragment->newlines = newlines;1420}14211422/*1423 * Parse a unified diff fragment header of the1424 * form "@@ -a,b +c,d @@"1425 */1426static int parse_fragment_header(const char *line, int len, struct fragment *fragment)1427{1428 int offset;14291430 if (!len || line[len-1] != '\n')1431 return -1;14321433 /* Figure out the number of lines in a fragment */1434 offset = parse_range(line, len, 4, " +", &fragment->oldpos, &fragment->oldlines);1435 offset = parse_range(line, len, offset, " @@", &fragment->newpos, &fragment->newlines);14361437 return offset;1438}14391440static int find_header(const char *line, unsigned long size, int *hdrsize, struct patch *patch)1441{1442 unsigned long offset, len;14431444 patch->is_toplevel_relative = 0;1445 patch->is_rename = patch->is_copy = 0;1446 patch->is_new = patch->is_delete = -1;1447 patch->old_mode = patch->new_mode = 0;1448 patch->old_name = patch->new_name = NULL;1449 for (offset = 0; size > 0; offset += len, size -= len, line += len, linenr++) {1450 unsigned long nextlen;14511452 len = linelen(line, size);1453 if (!len)1454 break;14551456 /* Testing this early allows us to take a few shortcuts.. */1457 if (len < 6)1458 continue;14591460 /*1461 * Make sure we don't find any unconnected patch fragments.1462 * That's a sign that we didn't find a header, and that a1463 * patch has become corrupted/broken up.1464 */1465 if (!memcmp("@@ -", line, 4)) {1466 struct fragment dummy;1467 if (parse_fragment_header(line, len, &dummy) < 0)1468 continue;1469 die(_("patch fragment without header at line %d: %.*s"),1470 linenr, (int)len-1, line);1471 }14721473 if (size < len + 6)1474 break;14751476 /*1477 * Git patch? It might not have a real patch, just a rename1478 * or mode change, so we handle that specially1479 */1480 if (!memcmp("diff --git ", line, 11)) {1481 int git_hdr_len = parse_git_header(line, len, size, patch);1482 if (git_hdr_len <= len)1483 continue;1484 if (!patch->old_name && !patch->new_name) {1485 if (!patch->def_name)1486 die(Q_("git diff header lacks filename information when removing "1487 "%d leading pathname component (line %d)",1488 "git diff header lacks filename information when removing "1489 "%d leading pathname components (line %d)",1490 p_value),1491 p_value, linenr);1492 patch->old_name = xstrdup(patch->def_name);1493 patch->new_name = xstrdup(patch->def_name);1494 }1495 if (!patch->is_delete && !patch->new_name)1496 die("git diff header lacks filename information "1497 "(line %d)", linenr);1498 patch->is_toplevel_relative = 1;1499 *hdrsize = git_hdr_len;1500 return offset;1501 }15021503 /* --- followed by +++ ? */1504 if (memcmp("--- ", line, 4) || memcmp("+++ ", line + len, 4))1505 continue;15061507 /*1508 * We only accept unified patches, so we want it to1509 * at least have "@@ -a,b +c,d @@\n", which is 14 chars1510 * minimum ("@@ -0,0 +1 @@\n" is the shortest).1511 */1512 nextlen = linelen(line + len, size - len);1513 if (size < nextlen + 14 || memcmp("@@ -", line + len + nextlen, 4))1514 continue;15151516 /* Ok, we'll consider it a patch */1517 parse_traditional_patch(line, line+len, patch);1518 *hdrsize = len + nextlen;1519 linenr += 2;1520 return offset;1521 }1522 return -1;1523}15241525static void record_ws_error(unsigned result, const char *line, int len, int linenr)1526{1527 char *err;15281529 if (!result)1530 return;15311532 whitespace_error++;1533 if (squelch_whitespace_errors &&1534 squelch_whitespace_errors < whitespace_error)1535 return;15361537 err = whitespace_error_string(result);1538 fprintf(stderr, "%s:%d: %s.\n%.*s\n",1539 patch_input_file, linenr, err, len, line);1540 free(err);1541}15421543static void check_whitespace(const char *line, int len, unsigned ws_rule)1544{1545 unsigned result = ws_check(line + 1, len - 1, ws_rule);15461547 record_ws_error(result, line + 1, len - 2, linenr);1548}15491550/*1551 * Parse a unified diff. Note that this really needs to parse each1552 * fragment separately, since the only way to know the difference1553 * between a "---" that is part of a patch, and a "---" that starts1554 * the next patch is to look at the line counts..1555 */1556static int parse_fragment(const char *line, unsigned long size,1557 struct patch *patch, struct fragment *fragment)1558{1559 int added, deleted;1560 int len = linelen(line, size), offset;1561 unsigned long oldlines, newlines;1562 unsigned long leading, trailing;15631564 offset = parse_fragment_header(line, len, fragment);1565 if (offset < 0)1566 return -1;1567 if (offset > 0 && patch->recount)1568 recount_diff(line + offset, size - offset, fragment);1569 oldlines = fragment->oldlines;1570 newlines = fragment->newlines;1571 leading = 0;1572 trailing = 0;15731574 /* Parse the thing.. */1575 line += len;1576 size -= len;1577 linenr++;1578 added = deleted = 0;1579 for (offset = len;1580 0 < size;1581 offset += len, size -= len, line += len, linenr++) {1582 if (!oldlines && !newlines)1583 break;1584 len = linelen(line, size);1585 if (!len || line[len-1] != '\n')1586 return -1;1587 switch (*line) {1588 default:1589 return -1;1590 case '\n': /* newer GNU diff, an empty context line */1591 case ' ':1592 oldlines--;1593 newlines--;1594 if (!deleted && !added)1595 leading++;1596 trailing++;1597 if (!apply_in_reverse &&1598 ws_error_action == correct_ws_error)1599 check_whitespace(line, len, patch->ws_rule);1600 break;1601 case '-':1602 if (apply_in_reverse &&1603 ws_error_action != nowarn_ws_error)1604 check_whitespace(line, len, patch->ws_rule);1605 deleted++;1606 oldlines--;1607 trailing = 0;1608 break;1609 case '+':1610 if (!apply_in_reverse &&1611 ws_error_action != nowarn_ws_error)1612 check_whitespace(line, len, patch->ws_rule);1613 added++;1614 newlines--;1615 trailing = 0;1616 break;16171618 /*1619 * We allow "\ No newline at end of file". Depending1620 * on locale settings when the patch was produced we1621 * don't know what this line looks like. The only1622 * thing we do know is that it begins with "\ ".1623 * Checking for 12 is just for sanity check -- any1624 * l10n of "\ No newline..." is at least that long.1625 */1626 case '\\':1627 if (len < 12 || memcmp(line, "\\ ", 2))1628 return -1;1629 break;1630 }1631 }1632 if (oldlines || newlines)1633 return -1;1634 if (!deleted && !added)1635 return -1;16361637 fragment->leading = leading;1638 fragment->trailing = trailing;16391640 /*1641 * If a fragment ends with an incomplete line, we failed to include1642 * it in the above loop because we hit oldlines == newlines == 01643 * before seeing it.1644 */1645 if (12 < size && !memcmp(line, "\\ ", 2))1646 offset += linelen(line, size);16471648 patch->lines_added += added;1649 patch->lines_deleted += deleted;16501651 if (0 < patch->is_new && oldlines)1652 return error(_("new file depends on old contents"));1653 if (0 < patch->is_delete && newlines)1654 return error(_("deleted file still has contents"));1655 return offset;1656}16571658/*1659 * We have seen "diff --git a/... b/..." header (or a traditional patch1660 * header). Read hunks that belong to this patch into fragments and hang1661 * them to the given patch structure.1662 *1663 * The (fragment->patch, fragment->size) pair points into the memory given1664 * by the caller, not a copy, when we return.1665 */1666static int parse_single_patch(const char *line, unsigned long size, struct patch *patch)1667{1668 unsigned long offset = 0;1669 unsigned long oldlines = 0, newlines = 0, context = 0;1670 struct fragment **fragp = &patch->fragments;16711672 while (size > 4 && !memcmp(line, "@@ -", 4)) {1673 struct fragment *fragment;1674 int len;16751676 fragment = xcalloc(1, sizeof(*fragment));1677 fragment->linenr = linenr;1678 len = parse_fragment(line, size, patch, fragment);1679 if (len <= 0)1680 die(_("corrupt patch at line %d"), linenr);1681 fragment->patch = line;1682 fragment->size = len;1683 oldlines += fragment->oldlines;1684 newlines += fragment->newlines;1685 context += fragment->leading + fragment->trailing;16861687 *fragp = fragment;1688 fragp = &fragment->next;16891690 offset += len;1691 line += len;1692 size -= len;1693 }16941695 /*1696 * If something was removed (i.e. we have old-lines) it cannot1697 * be creation, and if something was added it cannot be1698 * deletion. However, the reverse is not true; --unified=01699 * patches that only add are not necessarily creation even1700 * though they do not have any old lines, and ones that only1701 * delete are not necessarily deletion.1702 *1703 * Unfortunately, a real creation/deletion patch do _not_ have1704 * any context line by definition, so we cannot safely tell it1705 * apart with --unified=0 insanity. At least if the patch has1706 * more than one hunk it is not creation or deletion.1707 */1708 if (patch->is_new < 0 &&1709 (oldlines || (patch->fragments && patch->fragments->next)))1710 patch->is_new = 0;1711 if (patch->is_delete < 0 &&1712 (newlines || (patch->fragments && patch->fragments->next)))1713 patch->is_delete = 0;17141715 if (0 < patch->is_new && oldlines)1716 die(_("new file %s depends on old contents"), patch->new_name);1717 if (0 < patch->is_delete && newlines)1718 die(_("deleted file %s still has contents"), patch->old_name);1719 if (!patch->is_delete && !newlines && context)1720 fprintf_ln(stderr,1721 _("** warning: "1722 "file %s becomes empty but is not deleted"),1723 patch->new_name);17241725 return offset;1726}17271728static inline int metadata_changes(struct patch *patch)1729{1730 return patch->is_rename > 0 ||1731 patch->is_copy > 0 ||1732 patch->is_new > 0 ||1733 patch->is_delete ||1734 (patch->old_mode && patch->new_mode &&1735 patch->old_mode != patch->new_mode);1736}17371738static char *inflate_it(const void *data, unsigned long size,1739 unsigned long inflated_size)1740{1741 git_zstream stream;1742 void *out;1743 int st;17441745 memset(&stream, 0, sizeof(stream));17461747 stream.next_in = (unsigned char *)data;1748 stream.avail_in = size;1749 stream.next_out = out = xmalloc(inflated_size);1750 stream.avail_out = inflated_size;1751 git_inflate_init(&stream);1752 st = git_inflate(&stream, Z_FINISH);1753 git_inflate_end(&stream);1754 if ((st != Z_STREAM_END) || stream.total_out != inflated_size) {1755 free(out);1756 return NULL;1757 }1758 return out;1759}17601761/*1762 * Read a binary hunk and return a new fragment; fragment->patch1763 * points at an allocated memory that the caller must free, so1764 * it is marked as "->free_patch = 1".1765 */1766static struct fragment *parse_binary_hunk(char **buf_p,1767 unsigned long *sz_p,1768 int *status_p,1769 int *used_p)1770{1771 /*1772 * Expect a line that begins with binary patch method ("literal"1773 * or "delta"), followed by the length of data before deflating.1774 * a sequence of 'length-byte' followed by base-85 encoded data1775 * should follow, terminated by a newline.1776 *1777 * Each 5-byte sequence of base-85 encodes up to 4 bytes,1778 * and we would limit the patch line to 66 characters,1779 * so one line can fit up to 13 groups that would decode1780 * to 52 bytes max. The length byte 'A'-'Z' corresponds1781 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.1782 */1783 int llen, used;1784 unsigned long size = *sz_p;1785 char *buffer = *buf_p;1786 int patch_method;1787 unsigned long origlen;1788 char *data = NULL;1789 int hunk_size = 0;1790 struct fragment *frag;17911792 llen = linelen(buffer, size);1793 used = llen;17941795 *status_p = 0;17961797 if (starts_with(buffer, "delta ")) {1798 patch_method = BINARY_DELTA_DEFLATED;1799 origlen = strtoul(buffer + 6, NULL, 10);1800 }1801 else if (starts_with(buffer, "literal ")) {1802 patch_method = BINARY_LITERAL_DEFLATED;1803 origlen = strtoul(buffer + 8, NULL, 10);1804 }1805 else1806 return NULL;18071808 linenr++;1809 buffer += llen;1810 while (1) {1811 int byte_length, max_byte_length, newsize;1812 llen = linelen(buffer, size);1813 used += llen;1814 linenr++;1815 if (llen == 1) {1816 /* consume the blank line */1817 buffer++;1818 size--;1819 break;1820 }1821 /*1822 * Minimum line is "A00000\n" which is 7-byte long,1823 * and the line length must be multiple of 5 plus 2.1824 */1825 if ((llen < 7) || (llen-2) % 5)1826 goto corrupt;1827 max_byte_length = (llen - 2) / 5 * 4;1828 byte_length = *buffer;1829 if ('A' <= byte_length && byte_length <= 'Z')1830 byte_length = byte_length - 'A' + 1;1831 else if ('a' <= byte_length && byte_length <= 'z')1832 byte_length = byte_length - 'a' + 27;1833 else1834 goto corrupt;1835 /* if the input length was not multiple of 4, we would1836 * have filler at the end but the filler should never1837 * exceed 3 bytes1838 */1839 if (max_byte_length < byte_length ||1840 byte_length <= max_byte_length - 4)1841 goto corrupt;1842 newsize = hunk_size + byte_length;1843 data = xrealloc(data, newsize);1844 if (decode_85(data + hunk_size, buffer + 1, byte_length))1845 goto corrupt;1846 hunk_size = newsize;1847 buffer += llen;1848 size -= llen;1849 }18501851 frag = xcalloc(1, sizeof(*frag));1852 frag->patch = inflate_it(data, hunk_size, origlen);1853 frag->free_patch = 1;1854 if (!frag->patch)1855 goto corrupt;1856 free(data);1857 frag->size = origlen;1858 *buf_p = buffer;1859 *sz_p = size;1860 *used_p = used;1861 frag->binary_patch_method = patch_method;1862 return frag;18631864 corrupt:1865 free(data);1866 *status_p = -1;1867 error(_("corrupt binary patch at line %d: %.*s"),1868 linenr-1, llen-1, buffer);1869 return NULL;1870}18711872static int parse_binary(char *buffer, unsigned long size, struct patch *patch)1873{1874 /*1875 * We have read "GIT binary patch\n"; what follows is a line1876 * that says the patch method (currently, either "literal" or1877 * "delta") and the length of data before deflating; a1878 * sequence of 'length-byte' followed by base-85 encoded data1879 * follows.1880 *1881 * When a binary patch is reversible, there is another binary1882 * hunk in the same format, starting with patch method (either1883 * "literal" or "delta") with the length of data, and a sequence1884 * of length-byte + base-85 encoded data, terminated with another1885 * empty line. This data, when applied to the postimage, produces1886 * the preimage.1887 */1888 struct fragment *forward;1889 struct fragment *reverse;1890 int status;1891 int used, used_1;18921893 forward = parse_binary_hunk(&buffer, &size, &status, &used);1894 if (!forward && !status)1895 /* there has to be one hunk (forward hunk) */1896 return error(_("unrecognized binary patch at line %d"), linenr-1);1897 if (status)1898 /* otherwise we already gave an error message */1899 return status;19001901 reverse = parse_binary_hunk(&buffer, &size, &status, &used_1);1902 if (reverse)1903 used += used_1;1904 else if (status) {1905 /*1906 * Not having reverse hunk is not an error, but having1907 * a corrupt reverse hunk is.1908 */1909 free((void*) forward->patch);1910 free(forward);1911 return status;1912 }1913 forward->next = reverse;1914 patch->fragments = forward;1915 patch->is_binary = 1;1916 return used;1917}19181919static void prefix_one(char **name)1920{1921 char *old_name = *name;1922 if (!old_name)1923 return;1924 *name = xstrdup(prefix_filename(prefix, prefix_length, *name));1925 free(old_name);1926}19271928static void prefix_patch(struct patch *p)1929{1930 if (!prefix || p->is_toplevel_relative)1931 return;1932 prefix_one(&p->new_name);1933 prefix_one(&p->old_name);1934}19351936/*1937 * include/exclude1938 */19391940static struct string_list limit_by_name;1941static int has_include;1942static void add_name_limit(const char *name, int exclude)1943{1944 struct string_list_item *it;19451946 it = string_list_append(&limit_by_name, name);1947 it->util = exclude ? NULL : (void *) 1;1948}19491950static int use_patch(struct patch *p)1951{1952 const char *pathname = p->new_name ? p->new_name : p->old_name;1953 int i;19541955 /* Paths outside are not touched regardless of "--include" */1956 if (0 < prefix_length) {1957 int pathlen = strlen(pathname);1958 if (pathlen <= prefix_length ||1959 memcmp(prefix, pathname, prefix_length))1960 return 0;1961 }19621963 /* See if it matches any of exclude/include rule */1964 for (i = 0; i < limit_by_name.nr; i++) {1965 struct string_list_item *it = &limit_by_name.items[i];1966 if (!wildmatch(it->string, pathname, 0, NULL))1967 return (it->util != NULL);1968 }19691970 /*1971 * If we had any include, a path that does not match any rule is1972 * not used. Otherwise, we saw bunch of exclude rules (or none)1973 * and such a path is used.1974 */1975 return !has_include;1976}197719781979/*1980 * Read the patch text in "buffer" that extends for "size" bytes; stop1981 * reading after seeing a single patch (i.e. changes to a single file).1982 * Create fragments (i.e. patch hunks) and hang them to the given patch.1983 * Return the number of bytes consumed, so that the caller can call us1984 * again for the next patch.1985 */1986static int parse_chunk(char *buffer, unsigned long size, struct patch *patch)1987{1988 int hdrsize, patchsize;1989 int offset = find_header(buffer, size, &hdrsize, patch);19901991 if (offset < 0)1992 return offset;19931994 prefix_patch(patch);19951996 if (!use_patch(patch))1997 patch->ws_rule = 0;1998 else1999 patch->ws_rule = whitespace_rule(patch->new_name2000 ? patch->new_name2001 : patch->old_name);20022003 patchsize = parse_single_patch(buffer + offset + hdrsize,2004 size - offset - hdrsize, patch);20052006 if (!patchsize) {2007 static const char git_binary[] = "GIT binary patch\n";2008 int hd = hdrsize + offset;2009 unsigned long llen = linelen(buffer + hd, size - hd);20102011 if (llen == sizeof(git_binary) - 1 &&2012 !memcmp(git_binary, buffer + hd, llen)) {2013 int used;2014 linenr++;2015 used = parse_binary(buffer + hd + llen,2016 size - hd - llen, patch);2017 if (used)2018 patchsize = used + llen;2019 else2020 patchsize = 0;2021 }2022 else if (!memcmp(" differ\n", buffer + hd + llen - 8, 8)) {2023 static const char *binhdr[] = {2024 "Binary files ",2025 "Files ",2026 NULL,2027 };2028 int i;2029 for (i = 0; binhdr[i]; i++) {2030 int len = strlen(binhdr[i]);2031 if (len < size - hd &&2032 !memcmp(binhdr[i], buffer + hd, len)) {2033 linenr++;2034 patch->is_binary = 1;2035 patchsize = llen;2036 break;2037 }2038 }2039 }20402041 /* Empty patch cannot be applied if it is a text patch2042 * without metadata change. A binary patch appears2043 * empty to us here.2044 */2045 if ((apply || check) &&2046 (!patch->is_binary && !metadata_changes(patch)))2047 die(_("patch with only garbage at line %d"), linenr);2048 }20492050 return offset + hdrsize + patchsize;2051}20522053#define swap(a,b) myswap((a),(b),sizeof(a))20542055#define myswap(a, b, size) do { \2056 unsigned char mytmp[size]; \2057 memcpy(mytmp, &a, size); \2058 memcpy(&a, &b, size); \2059 memcpy(&b, mytmp, size); \2060} while (0)20612062static void reverse_patches(struct patch *p)2063{2064 for (; p; p = p->next) {2065 struct fragment *frag = p->fragments;20662067 swap(p->new_name, p->old_name);2068 swap(p->new_mode, p->old_mode);2069 swap(p->is_new, p->is_delete);2070 swap(p->lines_added, p->lines_deleted);2071 swap(p->old_sha1_prefix, p->new_sha1_prefix);20722073 for (; frag; frag = frag->next) {2074 swap(frag->newpos, frag->oldpos);2075 swap(frag->newlines, frag->oldlines);2076 }2077 }2078}20792080static const char pluses[] =2081"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";2082static const char minuses[]=2083"----------------------------------------------------------------------";20842085static void show_stats(struct patch *patch)2086{2087 struct strbuf qname = STRBUF_INIT;2088 char *cp = patch->new_name ? patch->new_name : patch->old_name;2089 int max, add, del;20902091 quote_c_style(cp, &qname, NULL, 0);20922093 /*2094 * "scale" the filename2095 */2096 max = max_len;2097 if (max > 50)2098 max = 50;20992100 if (qname.len > max) {2101 cp = strchr(qname.buf + qname.len + 3 - max, '/');2102 if (!cp)2103 cp = qname.buf + qname.len + 3 - max;2104 strbuf_splice(&qname, 0, cp - qname.buf, "...", 3);2105 }21062107 if (patch->is_binary) {2108 printf(" %-*s | Bin\n", max, qname.buf);2109 strbuf_release(&qname);2110 return;2111 }21122113 printf(" %-*s |", max, qname.buf);2114 strbuf_release(&qname);21152116 /*2117 * scale the add/delete2118 */2119 max = max + max_change > 70 ? 70 - max : max_change;2120 add = patch->lines_added;2121 del = patch->lines_deleted;21222123 if (max_change > 0) {2124 int total = ((add + del) * max + max_change / 2) / max_change;2125 add = (add * max + max_change / 2) / max_change;2126 del = total - add;2127 }2128 printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,2129 add, pluses, del, minuses);2130}21312132static int read_old_data(struct stat *st, const char *path, struct strbuf *buf)2133{2134 switch (st->st_mode & S_IFMT) {2135 case S_IFLNK:2136 if (strbuf_readlink(buf, path, st->st_size) < 0)2137 return error(_("unable to read symlink %s"), path);2138 return 0;2139 case S_IFREG:2140 if (strbuf_read_file(buf, path, st->st_size) != st->st_size)2141 return error(_("unable to open or read %s"), path);2142 convert_to_git(path, buf->buf, buf->len, buf, 0);2143 return 0;2144 default:2145 return -1;2146 }2147}21482149/*2150 * Update the preimage, and the common lines in postimage,2151 * from buffer buf of length len. If postlen is 0 the postimage2152 * is updated in place, otherwise it's updated on a new buffer2153 * of length postlen2154 */21552156static void update_pre_post_images(struct image *preimage,2157 struct image *postimage,2158 char *buf,2159 size_t len, size_t postlen)2160{2161 int i, ctx, reduced;2162 char *new, *old, *fixed;2163 struct image fixed_preimage;21642165 /*2166 * Update the preimage with whitespace fixes. Note that we2167 * are not losing preimage->buf -- apply_one_fragment() will2168 * free "oldlines".2169 */2170 prepare_image(&fixed_preimage, buf, len, 1);2171 assert(postlen2172 ? fixed_preimage.nr == preimage->nr2173 : fixed_preimage.nr <= preimage->nr);2174 for (i = 0; i < fixed_preimage.nr; i++)2175 fixed_preimage.line[i].flag = preimage->line[i].flag;2176 free(preimage->line_allocated);2177 *preimage = fixed_preimage;21782179 /*2180 * Adjust the common context lines in postimage. This can be2181 * done in-place when we are shrinking it with whitespace2182 * fixing, but needs a new buffer when ignoring whitespace or2183 * expanding leading tabs to spaces.2184 *2185 * We trust the caller to tell us if the update can be done2186 * in place (postlen==0) or not.2187 */2188 old = postimage->buf;2189 if (postlen)2190 new = postimage->buf = xmalloc(postlen);2191 else2192 new = old;2193 fixed = preimage->buf;21942195 for (i = reduced = ctx = 0; i < postimage->nr; i++) {2196 size_t len = postimage->line[i].len;2197 if (!(postimage->line[i].flag & LINE_COMMON)) {2198 /* an added line -- no counterparts in preimage */2199 memmove(new, old, len);2200 old += len;2201 new += len;2202 continue;2203 }22042205 /* a common context -- skip it in the original postimage */2206 old += len;22072208 /* and find the corresponding one in the fixed preimage */2209 while (ctx < preimage->nr &&2210 !(preimage->line[ctx].flag & LINE_COMMON)) {2211 fixed += preimage->line[ctx].len;2212 ctx++;2213 }22142215 /*2216 * preimage is expected to run out, if the caller2217 * fixed addition of trailing blank lines.2218 */2219 if (preimage->nr <= ctx) {2220 reduced++;2221 continue;2222 }22232224 /* and copy it in, while fixing the line length */2225 len = preimage->line[ctx].len;2226 memcpy(new, fixed, len);2227 new += len;2228 fixed += len;2229 postimage->line[i].len = len;2230 ctx++;2231 }22322233 if (postlen2234 ? postlen < new - postimage->buf2235 : postimage->len < new - postimage->buf)2236 die("BUG: caller miscounted postlen: asked %d, orig = %d, used = %d",2237 (int)postlen, (int) postimage->len, (int)(new - postimage->buf));22382239 /* Fix the length of the whole thing */2240 postimage->len = new - postimage->buf;2241 postimage->nr -= reduced;2242}22432244static int match_fragment(struct image *img,2245 struct image *preimage,2246 struct image *postimage,2247 unsigned long try,2248 int try_lno,2249 unsigned ws_rule,2250 int match_beginning, int match_end)2251{2252 int i;2253 char *fixed_buf, *buf, *orig, *target;2254 struct strbuf fixed;2255 size_t fixed_len, postlen;2256 int preimage_limit;22572258 if (preimage->nr + try_lno <= img->nr) {2259 /*2260 * The hunk falls within the boundaries of img.2261 */2262 preimage_limit = preimage->nr;2263 if (match_end && (preimage->nr + try_lno != img->nr))2264 return 0;2265 } else if (ws_error_action == correct_ws_error &&2266 (ws_rule & WS_BLANK_AT_EOF)) {2267 /*2268 * This hunk extends beyond the end of img, and we are2269 * removing blank lines at the end of the file. This2270 * many lines from the beginning of the preimage must2271 * match with img, and the remainder of the preimage2272 * must be blank.2273 */2274 preimage_limit = img->nr - try_lno;2275 } else {2276 /*2277 * The hunk extends beyond the end of the img and2278 * we are not removing blanks at the end, so we2279 * should reject the hunk at this position.2280 */2281 return 0;2282 }22832284 if (match_beginning && try_lno)2285 return 0;22862287 /* Quick hash check */2288 for (i = 0; i < preimage_limit; i++)2289 if ((img->line[try_lno + i].flag & LINE_PATCHED) ||2290 (preimage->line[i].hash != img->line[try_lno + i].hash))2291 return 0;22922293 if (preimage_limit == preimage->nr) {2294 /*2295 * Do we have an exact match? If we were told to match2296 * at the end, size must be exactly at try+fragsize,2297 * otherwise try+fragsize must be still within the preimage,2298 * and either case, the old piece should match the preimage2299 * exactly.2300 */2301 if ((match_end2302 ? (try + preimage->len == img->len)2303 : (try + preimage->len <= img->len)) &&2304 !memcmp(img->buf + try, preimage->buf, preimage->len))2305 return 1;2306 } else {2307 /*2308 * The preimage extends beyond the end of img, so2309 * there cannot be an exact match.2310 *2311 * There must be one non-blank context line that match2312 * a line before the end of img.2313 */2314 char *buf_end;23152316 buf = preimage->buf;2317 buf_end = buf;2318 for (i = 0; i < preimage_limit; i++)2319 buf_end += preimage->line[i].len;23202321 for ( ; buf < buf_end; buf++)2322 if (!isspace(*buf))2323 break;2324 if (buf == buf_end)2325 return 0;2326 }23272328 /*2329 * No exact match. If we are ignoring whitespace, run a line-by-line2330 * fuzzy matching. We collect all the line length information because2331 * we need it to adjust whitespace if we match.2332 */2333 if (ws_ignore_action == ignore_ws_change) {2334 size_t imgoff = 0;2335 size_t preoff = 0;2336 size_t postlen = postimage->len;2337 size_t extra_chars;2338 char *preimage_eof;2339 char *preimage_end;2340 for (i = 0; i < preimage_limit; i++) {2341 size_t prelen = preimage->line[i].len;2342 size_t imglen = img->line[try_lno+i].len;23432344 if (!fuzzy_matchlines(img->buf + try + imgoff, imglen,2345 preimage->buf + preoff, prelen))2346 return 0;2347 if (preimage->line[i].flag & LINE_COMMON)2348 postlen += imglen - prelen;2349 imgoff += imglen;2350 preoff += prelen;2351 }23522353 /*2354 * Ok, the preimage matches with whitespace fuzz.2355 *2356 * imgoff now holds the true length of the target that2357 * matches the preimage before the end of the file.2358 *2359 * Count the number of characters in the preimage that fall2360 * beyond the end of the file and make sure that all of them2361 * are whitespace characters. (This can only happen if2362 * we are removing blank lines at the end of the file.)2363 */2364 buf = preimage_eof = preimage->buf + preoff;2365 for ( ; i < preimage->nr; i++)2366 preoff += preimage->line[i].len;2367 preimage_end = preimage->buf + preoff;2368 for ( ; buf < preimage_end; buf++)2369 if (!isspace(*buf))2370 return 0;23712372 /*2373 * Update the preimage and the common postimage context2374 * lines to use the same whitespace as the target.2375 * If whitespace is missing in the target (i.e.2376 * if the preimage extends beyond the end of the file),2377 * use the whitespace from the preimage.2378 */2379 extra_chars = preimage_end - preimage_eof;2380 strbuf_init(&fixed, imgoff + extra_chars);2381 strbuf_add(&fixed, img->buf + try, imgoff);2382 strbuf_add(&fixed, preimage_eof, extra_chars);2383 fixed_buf = strbuf_detach(&fixed, &fixed_len);2384 update_pre_post_images(preimage, postimage,2385 fixed_buf, fixed_len, postlen);2386 return 1;2387 }23882389 if (ws_error_action != correct_ws_error)2390 return 0;23912392 /*2393 * The hunk does not apply byte-by-byte, but the hash says2394 * it might with whitespace fuzz. We weren't asked to2395 * ignore whitespace, we were asked to correct whitespace2396 * errors, so let's try matching after whitespace correction.2397 *2398 * While checking the preimage against the target, whitespace2399 * errors in both fixed, we count how large the corresponding2400 * postimage needs to be. The postimage prepared by2401 * apply_one_fragment() has whitespace errors fixed on added2402 * lines already, but the common lines were propagated as-is,2403 * which may become longer when their whitespace errors are2404 * fixed.2405 */24062407 /* First count added lines in postimage */2408 postlen = 0;2409 for (i = 0; i < postimage->nr; i++) {2410 if (!(postimage->line[i].flag & LINE_COMMON))2411 postlen += postimage->line[i].len;2412 }24132414 /*2415 * The preimage may extend beyond the end of the file,2416 * but in this loop we will only handle the part of the2417 * preimage that falls within the file.2418 */2419 strbuf_init(&fixed, preimage->len + 1);2420 orig = preimage->buf;2421 target = img->buf + try;2422 for (i = 0; i < preimage_limit; i++) {2423 size_t oldlen = preimage->line[i].len;2424 size_t tgtlen = img->line[try_lno + i].len;2425 size_t fixstart = fixed.len;2426 struct strbuf tgtfix;2427 int match;24282429 /* Try fixing the line in the preimage */2430 ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);24312432 /* Try fixing the line in the target */2433 strbuf_init(&tgtfix, tgtlen);2434 ws_fix_copy(&tgtfix, target, tgtlen, ws_rule, NULL);24352436 /*2437 * If they match, either the preimage was based on2438 * a version before our tree fixed whitespace breakage,2439 * or we are lacking a whitespace-fix patch the tree2440 * the preimage was based on already had (i.e. target2441 * has whitespace breakage, the preimage doesn't).2442 * In either case, we are fixing the whitespace breakages2443 * so we might as well take the fix together with their2444 * real change.2445 */2446 match = (tgtfix.len == fixed.len - fixstart &&2447 !memcmp(tgtfix.buf, fixed.buf + fixstart,2448 fixed.len - fixstart));24492450 /* Add the length if this is common with the postimage */2451 if (preimage->line[i].flag & LINE_COMMON)2452 postlen += tgtfix.len;24532454 strbuf_release(&tgtfix);2455 if (!match)2456 goto unmatch_exit;24572458 orig += oldlen;2459 target += tgtlen;2460 }246124622463 /*2464 * Now handle the lines in the preimage that falls beyond the2465 * end of the file (if any). They will only match if they are2466 * empty or only contain whitespace (if WS_BLANK_AT_EOL is2467 * false).2468 */2469 for ( ; i < preimage->nr; i++) {2470 size_t fixstart = fixed.len; /* start of the fixed preimage */2471 size_t oldlen = preimage->line[i].len;2472 int j;24732474 /* Try fixing the line in the preimage */2475 ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);24762477 for (j = fixstart; j < fixed.len; j++)2478 if (!isspace(fixed.buf[j]))2479 goto unmatch_exit;24802481 orig += oldlen;2482 }24832484 /*2485 * Yes, the preimage is based on an older version that still2486 * has whitespace breakages unfixed, and fixing them makes the2487 * hunk match. Update the context lines in the postimage.2488 */2489 fixed_buf = strbuf_detach(&fixed, &fixed_len);2490 if (postlen < postimage->len)2491 postlen = 0;2492 update_pre_post_images(preimage, postimage,2493 fixed_buf, fixed_len, postlen);2494 return 1;24952496 unmatch_exit:2497 strbuf_release(&fixed);2498 return 0;2499}25002501static int find_pos(struct image *img,2502 struct image *preimage,2503 struct image *postimage,2504 int line,2505 unsigned ws_rule,2506 int match_beginning, int match_end)2507{2508 int i;2509 unsigned long backwards, forwards, try;2510 int backwards_lno, forwards_lno, try_lno;25112512 /*2513 * If match_beginning or match_end is specified, there is no2514 * point starting from a wrong line that will never match and2515 * wander around and wait for a match at the specified end.2516 */2517 if (match_beginning)2518 line = 0;2519 else if (match_end)2520 line = img->nr - preimage->nr;25212522 /*2523 * Because the comparison is unsigned, the following test2524 * will also take care of a negative line number that can2525 * result when match_end and preimage is larger than the target.2526 */2527 if ((size_t) line > img->nr)2528 line = img->nr;25292530 try = 0;2531 for (i = 0; i < line; i++)2532 try += img->line[i].len;25332534 /*2535 * There's probably some smart way to do this, but I'll leave2536 * that to the smart and beautiful people. I'm simple and stupid.2537 */2538 backwards = try;2539 backwards_lno = line;2540 forwards = try;2541 forwards_lno = line;2542 try_lno = line;25432544 for (i = 0; ; i++) {2545 if (match_fragment(img, preimage, postimage,2546 try, try_lno, ws_rule,2547 match_beginning, match_end))2548 return try_lno;25492550 again:2551 if (backwards_lno == 0 && forwards_lno == img->nr)2552 break;25532554 if (i & 1) {2555 if (backwards_lno == 0) {2556 i++;2557 goto again;2558 }2559 backwards_lno--;2560 backwards -= img->line[backwards_lno].len;2561 try = backwards;2562 try_lno = backwards_lno;2563 } else {2564 if (forwards_lno == img->nr) {2565 i++;2566 goto again;2567 }2568 forwards += img->line[forwards_lno].len;2569 forwards_lno++;2570 try = forwards;2571 try_lno = forwards_lno;2572 }25732574 }2575 return -1;2576}25772578static void remove_first_line(struct image *img)2579{2580 img->buf += img->line[0].len;2581 img->len -= img->line[0].len;2582 img->line++;2583 img->nr--;2584}25852586static void remove_last_line(struct image *img)2587{2588 img->len -= img->line[--img->nr].len;2589}25902591/*2592 * The change from "preimage" and "postimage" has been found to2593 * apply at applied_pos (counts in line numbers) in "img".2594 * Update "img" to remove "preimage" and replace it with "postimage".2595 */2596static void update_image(struct image *img,2597 int applied_pos,2598 struct image *preimage,2599 struct image *postimage)2600{2601 /*2602 * remove the copy of preimage at offset in img2603 * and replace it with postimage2604 */2605 int i, nr;2606 size_t remove_count, insert_count, applied_at = 0;2607 char *result;2608 int preimage_limit;26092610 /*2611 * If we are removing blank lines at the end of img,2612 * the preimage may extend beyond the end.2613 * If that is the case, we must be careful only to2614 * remove the part of the preimage that falls within2615 * the boundaries of img. Initialize preimage_limit2616 * to the number of lines in the preimage that falls2617 * within the boundaries.2618 */2619 preimage_limit = preimage->nr;2620 if (preimage_limit > img->nr - applied_pos)2621 preimage_limit = img->nr - applied_pos;26222623 for (i = 0; i < applied_pos; i++)2624 applied_at += img->line[i].len;26252626 remove_count = 0;2627 for (i = 0; i < preimage_limit; i++)2628 remove_count += img->line[applied_pos + i].len;2629 insert_count = postimage->len;26302631 /* Adjust the contents */2632 result = xmalloc(st_add3(st_sub(img->len, remove_count), insert_count, 1));2633 memcpy(result, img->buf, applied_at);2634 memcpy(result + applied_at, postimage->buf, postimage->len);2635 memcpy(result + applied_at + postimage->len,2636 img->buf + (applied_at + remove_count),2637 img->len - (applied_at + remove_count));2638 free(img->buf);2639 img->buf = result;2640 img->len += insert_count - remove_count;2641 result[img->len] = '\0';26422643 /* Adjust the line table */2644 nr = img->nr + postimage->nr - preimage_limit;2645 if (preimage_limit < postimage->nr) {2646 /*2647 * NOTE: this knows that we never call remove_first_line()2648 * on anything other than pre/post image.2649 */2650 REALLOC_ARRAY(img->line, nr);2651 img->line_allocated = img->line;2652 }2653 if (preimage_limit != postimage->nr)2654 memmove(img->line + applied_pos + postimage->nr,2655 img->line + applied_pos + preimage_limit,2656 (img->nr - (applied_pos + preimage_limit)) *2657 sizeof(*img->line));2658 memcpy(img->line + applied_pos,2659 postimage->line,2660 postimage->nr * sizeof(*img->line));2661 if (!allow_overlap)2662 for (i = 0; i < postimage->nr; i++)2663 img->line[applied_pos + i].flag |= LINE_PATCHED;2664 img->nr = nr;2665}26662667/*2668 * Use the patch-hunk text in "frag" to prepare two images (preimage and2669 * postimage) for the hunk. Find lines that match "preimage" in "img" and2670 * replace the part of "img" with "postimage" text.2671 */2672static int apply_one_fragment(struct image *img, struct fragment *frag,2673 int inaccurate_eof, unsigned ws_rule,2674 int nth_fragment)2675{2676 int match_beginning, match_end;2677 const char *patch = frag->patch;2678 int size = frag->size;2679 char *old, *oldlines;2680 struct strbuf newlines;2681 int new_blank_lines_at_end = 0;2682 int found_new_blank_lines_at_end = 0;2683 int hunk_linenr = frag->linenr;2684 unsigned long leading, trailing;2685 int pos, applied_pos;2686 struct image preimage;2687 struct image postimage;26882689 memset(&preimage, 0, sizeof(preimage));2690 memset(&postimage, 0, sizeof(postimage));2691 oldlines = xmalloc(size);2692 strbuf_init(&newlines, size);26932694 old = oldlines;2695 while (size > 0) {2696 char first;2697 int len = linelen(patch, size);2698 int plen;2699 int added_blank_line = 0;2700 int is_blank_context = 0;2701 size_t start;27022703 if (!len)2704 break;27052706 /*2707 * "plen" is how much of the line we should use for2708 * the actual patch data. Normally we just remove the2709 * first character on the line, but if the line is2710 * followed by "\ No newline", then we also remove the2711 * last one (which is the newline, of course).2712 */2713 plen = len - 1;2714 if (len < size && patch[len] == '\\')2715 plen--;2716 first = *patch;2717 if (apply_in_reverse) {2718 if (first == '-')2719 first = '+';2720 else if (first == '+')2721 first = '-';2722 }27232724 switch (first) {2725 case '\n':2726 /* Newer GNU diff, empty context line */2727 if (plen < 0)2728 /* ... followed by '\No newline'; nothing */2729 break;2730 *old++ = '\n';2731 strbuf_addch(&newlines, '\n');2732 add_line_info(&preimage, "\n", 1, LINE_COMMON);2733 add_line_info(&postimage, "\n", 1, LINE_COMMON);2734 is_blank_context = 1;2735 break;2736 case ' ':2737 if (plen && (ws_rule & WS_BLANK_AT_EOF) &&2738 ws_blank_line(patch + 1, plen, ws_rule))2739 is_blank_context = 1;2740 case '-':2741 memcpy(old, patch + 1, plen);2742 add_line_info(&preimage, old, plen,2743 (first == ' ' ? LINE_COMMON : 0));2744 old += plen;2745 if (first == '-')2746 break;2747 /* Fall-through for ' ' */2748 case '+':2749 /* --no-add does not add new lines */2750 if (first == '+' && no_add)2751 break;27522753 start = newlines.len;2754 if (first != '+' ||2755 !whitespace_error ||2756 ws_error_action != correct_ws_error) {2757 strbuf_add(&newlines, patch + 1, plen);2758 }2759 else {2760 ws_fix_copy(&newlines, patch + 1, plen, ws_rule, &applied_after_fixing_ws);2761 }2762 add_line_info(&postimage, newlines.buf + start, newlines.len - start,2763 (first == '+' ? 0 : LINE_COMMON));2764 if (first == '+' &&2765 (ws_rule & WS_BLANK_AT_EOF) &&2766 ws_blank_line(patch + 1, plen, ws_rule))2767 added_blank_line = 1;2768 break;2769 case '@': case '\\':2770 /* Ignore it, we already handled it */2771 break;2772 default:2773 if (apply_verbosely)2774 error(_("invalid start of line: '%c'"), first);2775 applied_pos = -1;2776 goto out;2777 }2778 if (added_blank_line) {2779 if (!new_blank_lines_at_end)2780 found_new_blank_lines_at_end = hunk_linenr;2781 new_blank_lines_at_end++;2782 }2783 else if (is_blank_context)2784 ;2785 else2786 new_blank_lines_at_end = 0;2787 patch += len;2788 size -= len;2789 hunk_linenr++;2790 }2791 if (inaccurate_eof &&2792 old > oldlines && old[-1] == '\n' &&2793 newlines.len > 0 && newlines.buf[newlines.len - 1] == '\n') {2794 old--;2795 strbuf_setlen(&newlines, newlines.len - 1);2796 }27972798 leading = frag->leading;2799 trailing = frag->trailing;28002801 /*2802 * A hunk to change lines at the beginning would begin with2803 * @@ -1,L +N,M @@2804 * but we need to be careful. -U0 that inserts before the second2805 * line also has this pattern.2806 *2807 * And a hunk to add to an empty file would begin with2808 * @@ -0,0 +N,M @@2809 *2810 * In other words, a hunk that is (frag->oldpos <= 1) with or2811 * without leading context must match at the beginning.2812 */2813 match_beginning = (!frag->oldpos ||2814 (frag->oldpos == 1 && !unidiff_zero));28152816 /*2817 * A hunk without trailing lines must match at the end.2818 * However, we simply cannot tell if a hunk must match end2819 * from the lack of trailing lines if the patch was generated2820 * with unidiff without any context.2821 */2822 match_end = !unidiff_zero && !trailing;28232824 pos = frag->newpos ? (frag->newpos - 1) : 0;2825 preimage.buf = oldlines;2826 preimage.len = old - oldlines;2827 postimage.buf = newlines.buf;2828 postimage.len = newlines.len;2829 preimage.line = preimage.line_allocated;2830 postimage.line = postimage.line_allocated;28312832 for (;;) {28332834 applied_pos = find_pos(img, &preimage, &postimage, pos,2835 ws_rule, match_beginning, match_end);28362837 if (applied_pos >= 0)2838 break;28392840 /* Am I at my context limits? */2841 if ((leading <= p_context) && (trailing <= p_context))2842 break;2843 if (match_beginning || match_end) {2844 match_beginning = match_end = 0;2845 continue;2846 }28472848 /*2849 * Reduce the number of context lines; reduce both2850 * leading and trailing if they are equal otherwise2851 * just reduce the larger context.2852 */2853 if (leading >= trailing) {2854 remove_first_line(&preimage);2855 remove_first_line(&postimage);2856 pos--;2857 leading--;2858 }2859 if (trailing > leading) {2860 remove_last_line(&preimage);2861 remove_last_line(&postimage);2862 trailing--;2863 }2864 }28652866 if (applied_pos >= 0) {2867 if (new_blank_lines_at_end &&2868 preimage.nr + applied_pos >= img->nr &&2869 (ws_rule & WS_BLANK_AT_EOF) &&2870 ws_error_action != nowarn_ws_error) {2871 record_ws_error(WS_BLANK_AT_EOF, "+", 1,2872 found_new_blank_lines_at_end);2873 if (ws_error_action == correct_ws_error) {2874 while (new_blank_lines_at_end--)2875 remove_last_line(&postimage);2876 }2877 /*2878 * We would want to prevent write_out_results()2879 * from taking place in apply_patch() that follows2880 * the callchain led us here, which is:2881 * apply_patch->check_patch_list->check_patch->2882 * apply_data->apply_fragments->apply_one_fragment2883 */2884 if (ws_error_action == die_on_ws_error)2885 apply = 0;2886 }28872888 if (apply_verbosely && applied_pos != pos) {2889 int offset = applied_pos - pos;2890 if (apply_in_reverse)2891 offset = 0 - offset;2892 fprintf_ln(stderr,2893 Q_("Hunk #%d succeeded at %d (offset %d line).",2894 "Hunk #%d succeeded at %d (offset %d lines).",2895 offset),2896 nth_fragment, applied_pos + 1, offset);2897 }28982899 /*2900 * Warn if it was necessary to reduce the number2901 * of context lines.2902 */2903 if ((leading != frag->leading) ||2904 (trailing != frag->trailing))2905 fprintf_ln(stderr, _("Context reduced to (%ld/%ld)"2906 " to apply fragment at %d"),2907 leading, trailing, applied_pos+1);2908 update_image(img, applied_pos, &preimage, &postimage);2909 } else {2910 if (apply_verbosely)2911 error(_("while searching for:\n%.*s"),2912 (int)(old - oldlines), oldlines);2913 }29142915out:2916 free(oldlines);2917 strbuf_release(&newlines);2918 free(preimage.line_allocated);2919 free(postimage.line_allocated);29202921 return (applied_pos < 0);2922}29232924static int apply_binary_fragment(struct image *img, struct patch *patch)2925{2926 struct fragment *fragment = patch->fragments;2927 unsigned long len;2928 void *dst;29292930 if (!fragment)2931 return error(_("missing binary patch data for '%s'"),2932 patch->new_name ?2933 patch->new_name :2934 patch->old_name);29352936 /* Binary patch is irreversible without the optional second hunk */2937 if (apply_in_reverse) {2938 if (!fragment->next)2939 return error("cannot reverse-apply a binary patch "2940 "without the reverse hunk to '%s'",2941 patch->new_name2942 ? patch->new_name : patch->old_name);2943 fragment = fragment->next;2944 }2945 switch (fragment->binary_patch_method) {2946 case BINARY_DELTA_DEFLATED:2947 dst = patch_delta(img->buf, img->len, fragment->patch,2948 fragment->size, &len);2949 if (!dst)2950 return -1;2951 clear_image(img);2952 img->buf = dst;2953 img->len = len;2954 return 0;2955 case BINARY_LITERAL_DEFLATED:2956 clear_image(img);2957 img->len = fragment->size;2958 img->buf = xmemdupz(fragment->patch, img->len);2959 return 0;2960 }2961 return -1;2962}29632964/*2965 * Replace "img" with the result of applying the binary patch.2966 * The binary patch data itself in patch->fragment is still kept2967 * but the preimage prepared by the caller in "img" is freed here2968 * or in the helper function apply_binary_fragment() this calls.2969 */2970static int apply_binary(struct image *img, struct patch *patch)2971{2972 const char *name = patch->old_name ? patch->old_name : patch->new_name;2973 unsigned char sha1[20];29742975 /*2976 * For safety, we require patch index line to contain2977 * full 40-byte textual SHA1 for old and new, at least for now.2978 */2979 if (strlen(patch->old_sha1_prefix) != 40 ||2980 strlen(patch->new_sha1_prefix) != 40 ||2981 get_sha1_hex(patch->old_sha1_prefix, sha1) ||2982 get_sha1_hex(patch->new_sha1_prefix, sha1))2983 return error("cannot apply binary patch to '%s' "2984 "without full index line", name);29852986 if (patch->old_name) {2987 /*2988 * See if the old one matches what the patch2989 * applies to.2990 */2991 hash_sha1_file(img->buf, img->len, blob_type, sha1);2992 if (strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))2993 return error("the patch applies to '%s' (%s), "2994 "which does not match the "2995 "current contents.",2996 name, sha1_to_hex(sha1));2997 }2998 else {2999 /* Otherwise, the old one must be empty. */3000 if (img->len)3001 return error("the patch applies to an empty "3002 "'%s' but it is not empty", name);3003 }30043005 get_sha1_hex(patch->new_sha1_prefix, sha1);3006 if (is_null_sha1(sha1)) {3007 clear_image(img);3008 return 0; /* deletion patch */3009 }30103011 if (has_sha1_file(sha1)) {3012 /* We already have the postimage */3013 enum object_type type;3014 unsigned long size;3015 char *result;30163017 result = read_sha1_file(sha1, &type, &size);3018 if (!result)3019 return error("the necessary postimage %s for "3020 "'%s' cannot be read",3021 patch->new_sha1_prefix, name);3022 clear_image(img);3023 img->buf = result;3024 img->len = size;3025 } else {3026 /*3027 * We have verified buf matches the preimage;3028 * apply the patch data to it, which is stored3029 * in the patch->fragments->{patch,size}.3030 */3031 if (apply_binary_fragment(img, patch))3032 return error(_("binary patch does not apply to '%s'"),3033 name);30343035 /* verify that the result matches */3036 hash_sha1_file(img->buf, img->len, blob_type, sha1);3037 if (strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))3038 return error(_("binary patch to '%s' creates incorrect result (expecting %s, got %s)"),3039 name, patch->new_sha1_prefix, sha1_to_hex(sha1));3040 }30413042 return 0;3043}30443045static int apply_fragments(struct image *img, struct patch *patch)3046{3047 struct fragment *frag = patch->fragments;3048 const char *name = patch->old_name ? patch->old_name : patch->new_name;3049 unsigned ws_rule = patch->ws_rule;3050 unsigned inaccurate_eof = patch->inaccurate_eof;3051 int nth = 0;30523053 if (patch->is_binary)3054 return apply_binary(img, patch);30553056 while (frag) {3057 nth++;3058 if (apply_one_fragment(img, frag, inaccurate_eof, ws_rule, nth)) {3059 error(_("patch failed: %s:%ld"), name, frag->oldpos);3060 if (!apply_with_reject)3061 return -1;3062 frag->rejected = 1;3063 }3064 frag = frag->next;3065 }3066 return 0;3067}30683069static int read_blob_object(struct strbuf *buf, const unsigned char *sha1, unsigned mode)3070{3071 if (S_ISGITLINK(mode)) {3072 strbuf_grow(buf, 100);3073 strbuf_addf(buf, "Subproject commit %s\n", sha1_to_hex(sha1));3074 } else {3075 enum object_type type;3076 unsigned long sz;3077 char *result;30783079 result = read_sha1_file(sha1, &type, &sz);3080 if (!result)3081 return -1;3082 /* XXX read_sha1_file NUL-terminates */3083 strbuf_attach(buf, result, sz, sz + 1);3084 }3085 return 0;3086}30873088static int read_file_or_gitlink(const struct cache_entry *ce, struct strbuf *buf)3089{3090 if (!ce)3091 return 0;3092 return read_blob_object(buf, ce->sha1, ce->ce_mode);3093}30943095static struct patch *in_fn_table(const char *name)3096{3097 struct string_list_item *item;30983099 if (name == NULL)3100 return NULL;31013102 item = string_list_lookup(&fn_table, name);3103 if (item != NULL)3104 return (struct patch *)item->util;31053106 return NULL;3107}31083109/*3110 * item->util in the filename table records the status of the path.3111 * Usually it points at a patch (whose result records the contents3112 * of it after applying it), but it could be PATH_WAS_DELETED for a3113 * path that a previously applied patch has already removed, or3114 * PATH_TO_BE_DELETED for a path that a later patch would remove.3115 *3116 * The latter is needed to deal with a case where two paths A and B3117 * are swapped by first renaming A to B and then renaming B to A;3118 * moving A to B should not be prevented due to presence of B as we3119 * will remove it in a later patch.3120 */3121#define PATH_TO_BE_DELETED ((struct patch *) -2)3122#define PATH_WAS_DELETED ((struct patch *) -1)31233124static int to_be_deleted(struct patch *patch)3125{3126 return patch == PATH_TO_BE_DELETED;3127}31283129static int was_deleted(struct patch *patch)3130{3131 return patch == PATH_WAS_DELETED;3132}31333134static void add_to_fn_table(struct patch *patch)3135{3136 struct string_list_item *item;31373138 /*3139 * Always add new_name unless patch is a deletion3140 * This should cover the cases for normal diffs,3141 * file creations and copies3142 */3143 if (patch->new_name != NULL) {3144 item = string_list_insert(&fn_table, patch->new_name);3145 item->util = patch;3146 }31473148 /*3149 * store a failure on rename/deletion cases because3150 * later chunks shouldn't patch old names3151 */3152 if ((patch->new_name == NULL) || (patch->is_rename)) {3153 item = string_list_insert(&fn_table, patch->old_name);3154 item->util = PATH_WAS_DELETED;3155 }3156}31573158static void prepare_fn_table(struct patch *patch)3159{3160 /*3161 * store information about incoming file deletion3162 */3163 while (patch) {3164 if ((patch->new_name == NULL) || (patch->is_rename)) {3165 struct string_list_item *item;3166 item = string_list_insert(&fn_table, patch->old_name);3167 item->util = PATH_TO_BE_DELETED;3168 }3169 patch = patch->next;3170 }3171}31723173static int checkout_target(struct index_state *istate,3174 struct cache_entry *ce, struct stat *st)3175{3176 struct checkout costate;31773178 memset(&costate, 0, sizeof(costate));3179 costate.base_dir = "";3180 costate.refresh_cache = 1;3181 costate.istate = istate;3182 if (checkout_entry(ce, &costate, NULL) || lstat(ce->name, st))3183 return error(_("cannot checkout %s"), ce->name);3184 return 0;3185}31863187static struct patch *previous_patch(struct patch *patch, int *gone)3188{3189 struct patch *previous;31903191 *gone = 0;3192 if (patch->is_copy || patch->is_rename)3193 return NULL; /* "git" patches do not depend on the order */31943195 previous = in_fn_table(patch->old_name);3196 if (!previous)3197 return NULL;31983199 if (to_be_deleted(previous))3200 return NULL; /* the deletion hasn't happened yet */32013202 if (was_deleted(previous))3203 *gone = 1;32043205 return previous;3206}32073208static int verify_index_match(const struct cache_entry *ce, struct stat *st)3209{3210 if (S_ISGITLINK(ce->ce_mode)) {3211 if (!S_ISDIR(st->st_mode))3212 return -1;3213 return 0;3214 }3215 return ce_match_stat(ce, st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE);3216}32173218#define SUBMODULE_PATCH_WITHOUT_INDEX 132193220static int load_patch_target(struct strbuf *buf,3221 const struct cache_entry *ce,3222 struct stat *st,3223 const char *name,3224 unsigned expected_mode)3225{3226 if (cached || check_index) {3227 if (read_file_or_gitlink(ce, buf))3228 return error(_("read of %s failed"), name);3229 } else if (name) {3230 if (S_ISGITLINK(expected_mode)) {3231 if (ce)3232 return read_file_or_gitlink(ce, buf);3233 else3234 return SUBMODULE_PATCH_WITHOUT_INDEX;3235 } else if (has_symlink_leading_path(name, strlen(name))) {3236 return error(_("reading from '%s' beyond a symbolic link"), name);3237 } else {3238 if (read_old_data(st, name, buf))3239 return error(_("read of %s failed"), name);3240 }3241 }3242 return 0;3243}32443245/*3246 * We are about to apply "patch"; populate the "image" with the3247 * current version we have, from the working tree or from the index,3248 * depending on the situation e.g. --cached/--index. If we are3249 * applying a non-git patch that incrementally updates the tree,3250 * we read from the result of a previous diff.3251 */3252static int load_preimage(struct image *image,3253 struct patch *patch, struct stat *st,3254 const struct cache_entry *ce)3255{3256 struct strbuf buf = STRBUF_INIT;3257 size_t len;3258 char *img;3259 struct patch *previous;3260 int status;32613262 previous = previous_patch(patch, &status);3263 if (status)3264 return error(_("path %s has been renamed/deleted"),3265 patch->old_name);3266 if (previous) {3267 /* We have a patched copy in memory; use that. */3268 strbuf_add(&buf, previous->result, previous->resultsize);3269 } else {3270 status = load_patch_target(&buf, ce, st,3271 patch->old_name, patch->old_mode);3272 if (status < 0)3273 return status;3274 else if (status == SUBMODULE_PATCH_WITHOUT_INDEX) {3275 /*3276 * There is no way to apply subproject3277 * patch without looking at the index.3278 * NEEDSWORK: shouldn't this be flagged3279 * as an error???3280 */3281 free_fragment_list(patch->fragments);3282 patch->fragments = NULL;3283 } else if (status) {3284 return error(_("read of %s failed"), patch->old_name);3285 }3286 }32873288 img = strbuf_detach(&buf, &len);3289 prepare_image(image, img, len, !patch->is_binary);3290 return 0;3291}32923293static int three_way_merge(struct image *image,3294 char *path,3295 const unsigned char *base,3296 const unsigned char *ours,3297 const unsigned char *theirs)3298{3299 mmfile_t base_file, our_file, their_file;3300 mmbuffer_t result = { NULL };3301 int status;33023303 read_mmblob(&base_file, base);3304 read_mmblob(&our_file, ours);3305 read_mmblob(&their_file, theirs);3306 status = ll_merge(&result, path,3307 &base_file, "base",3308 &our_file, "ours",3309 &their_file, "theirs", NULL);3310 free(base_file.ptr);3311 free(our_file.ptr);3312 free(their_file.ptr);3313 if (status < 0 || !result.ptr) {3314 free(result.ptr);3315 return -1;3316 }3317 clear_image(image);3318 image->buf = result.ptr;3319 image->len = result.size;33203321 return status;3322}33233324/*3325 * When directly falling back to add/add three-way merge, we read from3326 * the current contents of the new_name. In no cases other than that3327 * this function will be called.3328 */3329static int load_current(struct image *image, struct patch *patch)3330{3331 struct strbuf buf = STRBUF_INIT;3332 int status, pos;3333 size_t len;3334 char *img;3335 struct stat st;3336 struct cache_entry *ce;3337 char *name = patch->new_name;3338 unsigned mode = patch->new_mode;33393340 if (!patch->is_new)3341 die("BUG: patch to %s is not a creation", patch->old_name);33423343 pos = cache_name_pos(name, strlen(name));3344 if (pos < 0)3345 return error(_("%s: does not exist in index"), name);3346 ce = active_cache[pos];3347 if (lstat(name, &st)) {3348 if (errno != ENOENT)3349 return error(_("%s: %s"), name, strerror(errno));3350 if (checkout_target(&the_index, ce, &st))3351 return -1;3352 }3353 if (verify_index_match(ce, &st))3354 return error(_("%s: does not match index"), name);33553356 status = load_patch_target(&buf, ce, &st, name, mode);3357 if (status < 0)3358 return status;3359 else if (status)3360 return -1;3361 img = strbuf_detach(&buf, &len);3362 prepare_image(image, img, len, !patch->is_binary);3363 return 0;3364}33653366static int try_threeway(struct image *image, struct patch *patch,3367 struct stat *st, const struct cache_entry *ce)3368{3369 unsigned char pre_sha1[20], post_sha1[20], our_sha1[20];3370 struct strbuf buf = STRBUF_INIT;3371 size_t len;3372 int status;3373 char *img;3374 struct image tmp_image;33753376 /* No point falling back to 3-way merge in these cases */3377 if (patch->is_delete ||3378 S_ISGITLINK(patch->old_mode) || S_ISGITLINK(patch->new_mode))3379 return -1;33803381 /* Preimage the patch was prepared for */3382 if (patch->is_new)3383 write_sha1_file("", 0, blob_type, pre_sha1);3384 else if (get_sha1(patch->old_sha1_prefix, pre_sha1) ||3385 read_blob_object(&buf, pre_sha1, patch->old_mode))3386 return error("repository lacks the necessary blob to fall back on 3-way merge.");33873388 fprintf(stderr, "Falling back to three-way merge...\n");33893390 img = strbuf_detach(&buf, &len);3391 prepare_image(&tmp_image, img, len, 1);3392 /* Apply the patch to get the post image */3393 if (apply_fragments(&tmp_image, patch) < 0) {3394 clear_image(&tmp_image);3395 return -1;3396 }3397 /* post_sha1[] is theirs */3398 write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, post_sha1);3399 clear_image(&tmp_image);34003401 /* our_sha1[] is ours */3402 if (patch->is_new) {3403 if (load_current(&tmp_image, patch))3404 return error("cannot read the current contents of '%s'",3405 patch->new_name);3406 } else {3407 if (load_preimage(&tmp_image, patch, st, ce))3408 return error("cannot read the current contents of '%s'",3409 patch->old_name);3410 }3411 write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, our_sha1);3412 clear_image(&tmp_image);34133414 /* in-core three-way merge between post and our using pre as base */3415 status = three_way_merge(image, patch->new_name,3416 pre_sha1, our_sha1, post_sha1);3417 if (status < 0) {3418 fprintf(stderr, "Failed to fall back on three-way merge...\n");3419 return status;3420 }34213422 if (status) {3423 patch->conflicted_threeway = 1;3424 if (patch->is_new)3425 oidclr(&patch->threeway_stage[0]);3426 else3427 hashcpy(patch->threeway_stage[0].hash, pre_sha1);3428 hashcpy(patch->threeway_stage[1].hash, our_sha1);3429 hashcpy(patch->threeway_stage[2].hash, post_sha1);3430 fprintf(stderr, "Applied patch to '%s' with conflicts.\n", patch->new_name);3431 } else {3432 fprintf(stderr, "Applied patch to '%s' cleanly.\n", patch->new_name);3433 }3434 return 0;3435}34363437static int apply_data(struct patch *patch, struct stat *st, const struct cache_entry *ce)3438{3439 struct image image;34403441 if (load_preimage(&image, patch, st, ce) < 0)3442 return -1;34433444 if (patch->direct_to_threeway ||3445 apply_fragments(&image, patch) < 0) {3446 /* Note: with --reject, apply_fragments() returns 0 */3447 if (!threeway || try_threeway(&image, patch, st, ce) < 0)3448 return -1;3449 }3450 patch->result = image.buf;3451 patch->resultsize = image.len;3452 add_to_fn_table(patch);3453 free(image.line_allocated);34543455 if (0 < patch->is_delete && patch->resultsize)3456 return error(_("removal patch leaves file contents"));34573458 return 0;3459}34603461/*3462 * If "patch" that we are looking at modifies or deletes what we have,3463 * we would want it not to lose any local modification we have, either3464 * in the working tree or in the index.3465 *3466 * This also decides if a non-git patch is a creation patch or a3467 * modification to an existing empty file. We do not check the state3468 * of the current tree for a creation patch in this function; the caller3469 * check_patch() separately makes sure (and errors out otherwise) that3470 * the path the patch creates does not exist in the current tree.3471 */3472static int check_preimage(struct patch *patch, struct cache_entry **ce, struct stat *st)3473{3474 const char *old_name = patch->old_name;3475 struct patch *previous = NULL;3476 int stat_ret = 0, status;3477 unsigned st_mode = 0;34783479 if (!old_name)3480 return 0;34813482 assert(patch->is_new <= 0);3483 previous = previous_patch(patch, &status);34843485 if (status)3486 return error(_("path %s has been renamed/deleted"), old_name);3487 if (previous) {3488 st_mode = previous->new_mode;3489 } else if (!cached) {3490 stat_ret = lstat(old_name, st);3491 if (stat_ret && errno != ENOENT)3492 return error(_("%s: %s"), old_name, strerror(errno));3493 }34943495 if (check_index && !previous) {3496 int pos = cache_name_pos(old_name, strlen(old_name));3497 if (pos < 0) {3498 if (patch->is_new < 0)3499 goto is_new;3500 return error(_("%s: does not exist in index"), old_name);3501 }3502 *ce = active_cache[pos];3503 if (stat_ret < 0) {3504 if (checkout_target(&the_index, *ce, st))3505 return -1;3506 }3507 if (!cached && verify_index_match(*ce, st))3508 return error(_("%s: does not match index"), old_name);3509 if (cached)3510 st_mode = (*ce)->ce_mode;3511 } else if (stat_ret < 0) {3512 if (patch->is_new < 0)3513 goto is_new;3514 return error(_("%s: %s"), old_name, strerror(errno));3515 }35163517 if (!cached && !previous)3518 st_mode = ce_mode_from_stat(*ce, st->st_mode);35193520 if (patch->is_new < 0)3521 patch->is_new = 0;3522 if (!patch->old_mode)3523 patch->old_mode = st_mode;3524 if ((st_mode ^ patch->old_mode) & S_IFMT)3525 return error(_("%s: wrong type"), old_name);3526 if (st_mode != patch->old_mode)3527 warning(_("%s has type %o, expected %o"),3528 old_name, st_mode, patch->old_mode);3529 if (!patch->new_mode && !patch->is_delete)3530 patch->new_mode = st_mode;3531 return 0;35323533 is_new:3534 patch->is_new = 1;3535 patch->is_delete = 0;3536 free(patch->old_name);3537 patch->old_name = NULL;3538 return 0;3539}354035413542#define EXISTS_IN_INDEX 13543#define EXISTS_IN_WORKTREE 235443545static int check_to_create(const char *new_name, int ok_if_exists)3546{3547 struct stat nst;35483549 if (check_index &&3550 cache_name_pos(new_name, strlen(new_name)) >= 0 &&3551 !ok_if_exists)3552 return EXISTS_IN_INDEX;3553 if (cached)3554 return 0;35553556 if (!lstat(new_name, &nst)) {3557 if (S_ISDIR(nst.st_mode) || ok_if_exists)3558 return 0;3559 /*3560 * A leading component of new_name might be a symlink3561 * that is going to be removed with this patch, but3562 * still pointing at somewhere that has the path.3563 * In such a case, path "new_name" does not exist as3564 * far as git is concerned.3565 */3566 if (has_symlink_leading_path(new_name, strlen(new_name)))3567 return 0;35683569 return EXISTS_IN_WORKTREE;3570 } else if ((errno != ENOENT) && (errno != ENOTDIR)) {3571 return error("%s: %s", new_name, strerror(errno));3572 }3573 return 0;3574}35753576/*3577 * We need to keep track of how symlinks in the preimage are3578 * manipulated by the patches. A patch to add a/b/c where a/b3579 * is a symlink should not be allowed to affect the directory3580 * the symlink points at, but if the same patch removes a/b,3581 * it is perfectly fine, as the patch removes a/b to make room3582 * to create a directory a/b so that a/b/c can be created.3583 */3584static struct string_list symlink_changes;3585#define SYMLINK_GOES_AWAY 013586#define SYMLINK_IN_RESULT 0235873588static uintptr_t register_symlink_changes(const char *path, uintptr_t what)3589{3590 struct string_list_item *ent;35913592 ent = string_list_lookup(&symlink_changes, path);3593 if (!ent) {3594 ent = string_list_insert(&symlink_changes, path);3595 ent->util = (void *)0;3596 }3597 ent->util = (void *)(what | ((uintptr_t)ent->util));3598 return (uintptr_t)ent->util;3599}36003601static uintptr_t check_symlink_changes(const char *path)3602{3603 struct string_list_item *ent;36043605 ent = string_list_lookup(&symlink_changes, path);3606 if (!ent)3607 return 0;3608 return (uintptr_t)ent->util;3609}36103611static void prepare_symlink_changes(struct patch *patch)3612{3613 for ( ; patch; patch = patch->next) {3614 if ((patch->old_name && S_ISLNK(patch->old_mode)) &&3615 (patch->is_rename || patch->is_delete))3616 /* the symlink at patch->old_name is removed */3617 register_symlink_changes(patch->old_name, SYMLINK_GOES_AWAY);36183619 if (patch->new_name && S_ISLNK(patch->new_mode))3620 /* the symlink at patch->new_name is created or remains */3621 register_symlink_changes(patch->new_name, SYMLINK_IN_RESULT);3622 }3623}36243625static int path_is_beyond_symlink_1(struct strbuf *name)3626{3627 do {3628 unsigned int change;36293630 while (--name->len && name->buf[name->len] != '/')3631 ; /* scan backwards */3632 if (!name->len)3633 break;3634 name->buf[name->len] = '\0';3635 change = check_symlink_changes(name->buf);3636 if (change & SYMLINK_IN_RESULT)3637 return 1;3638 if (change & SYMLINK_GOES_AWAY)3639 /*3640 * This cannot be "return 0", because we may3641 * see a new one created at a higher level.3642 */3643 continue;36443645 /* otherwise, check the preimage */3646 if (check_index) {3647 struct cache_entry *ce;36483649 ce = cache_file_exists(name->buf, name->len, ignore_case);3650 if (ce && S_ISLNK(ce->ce_mode))3651 return 1;3652 } else {3653 struct stat st;3654 if (!lstat(name->buf, &st) && S_ISLNK(st.st_mode))3655 return 1;3656 }3657 } while (1);3658 return 0;3659}36603661static int path_is_beyond_symlink(const char *name_)3662{3663 int ret;3664 struct strbuf name = STRBUF_INIT;36653666 assert(*name_ != '\0');3667 strbuf_addstr(&name, name_);3668 ret = path_is_beyond_symlink_1(&name);3669 strbuf_release(&name);36703671 return ret;3672}36733674static void die_on_unsafe_path(struct patch *patch)3675{3676 const char *old_name = NULL;3677 const char *new_name = NULL;3678 if (patch->is_delete)3679 old_name = patch->old_name;3680 else if (!patch->is_new && !patch->is_copy)3681 old_name = patch->old_name;3682 if (!patch->is_delete)3683 new_name = patch->new_name;36843685 if (old_name && !verify_path(old_name))3686 die(_("invalid path '%s'"), old_name);3687 if (new_name && !verify_path(new_name))3688 die(_("invalid path '%s'"), new_name);3689}36903691/*3692 * Check and apply the patch in-core; leave the result in patch->result3693 * for the caller to write it out to the final destination.3694 */3695static int check_patch(struct patch *patch)3696{3697 struct stat st;3698 const char *old_name = patch->old_name;3699 const char *new_name = patch->new_name;3700 const char *name = old_name ? old_name : new_name;3701 struct cache_entry *ce = NULL;3702 struct patch *tpatch;3703 int ok_if_exists;3704 int status;37053706 patch->rejected = 1; /* we will drop this after we succeed */37073708 status = check_preimage(patch, &ce, &st);3709 if (status)3710 return status;3711 old_name = patch->old_name;37123713 /*3714 * A type-change diff is always split into a patch to delete3715 * old, immediately followed by a patch to create new (see3716 * diff.c::run_diff()); in such a case it is Ok that the entry3717 * to be deleted by the previous patch is still in the working3718 * tree and in the index.3719 *3720 * A patch to swap-rename between A and B would first rename A3721 * to B and then rename B to A. While applying the first one,3722 * the presence of B should not stop A from getting renamed to3723 * B; ask to_be_deleted() about the later rename. Removal of3724 * B and rename from A to B is handled the same way by asking3725 * was_deleted().3726 */3727 if ((tpatch = in_fn_table(new_name)) &&3728 (was_deleted(tpatch) || to_be_deleted(tpatch)))3729 ok_if_exists = 1;3730 else3731 ok_if_exists = 0;37323733 if (new_name &&3734 ((0 < patch->is_new) || patch->is_rename || patch->is_copy)) {3735 int err = check_to_create(new_name, ok_if_exists);37363737 if (err && threeway) {3738 patch->direct_to_threeway = 1;3739 } else switch (err) {3740 case 0:3741 break; /* happy */3742 case EXISTS_IN_INDEX:3743 return error(_("%s: already exists in index"), new_name);3744 break;3745 case EXISTS_IN_WORKTREE:3746 return error(_("%s: already exists in working directory"),3747 new_name);3748 default:3749 return err;3750 }37513752 if (!patch->new_mode) {3753 if (0 < patch->is_new)3754 patch->new_mode = S_IFREG | 0644;3755 else3756 patch->new_mode = patch->old_mode;3757 }3758 }37593760 if (new_name && old_name) {3761 int same = !strcmp(old_name, new_name);3762 if (!patch->new_mode)3763 patch->new_mode = patch->old_mode;3764 if ((patch->old_mode ^ patch->new_mode) & S_IFMT) {3765 if (same)3766 return error(_("new mode (%o) of %s does not "3767 "match old mode (%o)"),3768 patch->new_mode, new_name,3769 patch->old_mode);3770 else3771 return error(_("new mode (%o) of %s does not "3772 "match old mode (%o) of %s"),3773 patch->new_mode, new_name,3774 patch->old_mode, old_name);3775 }3776 }37773778 if (!unsafe_paths)3779 die_on_unsafe_path(patch);37803781 /*3782 * An attempt to read from or delete a path that is beyond a3783 * symbolic link will be prevented by load_patch_target() that3784 * is called at the beginning of apply_data() so we do not3785 * have to worry about a patch marked with "is_delete" bit3786 * here. We however need to make sure that the patch result3787 * is not deposited to a path that is beyond a symbolic link3788 * here.3789 */3790 if (!patch->is_delete && path_is_beyond_symlink(patch->new_name))3791 return error(_("affected file '%s' is beyond a symbolic link"),3792 patch->new_name);37933794 if (apply_data(patch, &st, ce) < 0)3795 return error(_("%s: patch does not apply"), name);3796 patch->rejected = 0;3797 return 0;3798}37993800static int check_patch_list(struct patch *patch)3801{3802 int err = 0;38033804 prepare_symlink_changes(patch);3805 prepare_fn_table(patch);3806 while (patch) {3807 if (apply_verbosely)3808 say_patch_name(stderr,3809 _("Checking patch %s..."), patch);3810 err |= check_patch(patch);3811 patch = patch->next;3812 }3813 return err;3814}38153816/* This function tries to read the sha1 from the current index */3817static int get_current_sha1(const char *path, unsigned char *sha1)3818{3819 int pos;38203821 if (read_cache() < 0)3822 return -1;3823 pos = cache_name_pos(path, strlen(path));3824 if (pos < 0)3825 return -1;3826 hashcpy(sha1, active_cache[pos]->sha1);3827 return 0;3828}38293830static int preimage_sha1_in_gitlink_patch(struct patch *p, unsigned char sha1[20])3831{3832 /*3833 * A usable gitlink patch has only one fragment (hunk) that looks like:3834 * @@ -1 +1 @@3835 * -Subproject commit <old sha1>3836 * +Subproject commit <new sha1>3837 * or3838 * @@ -1 +0,0 @@3839 * -Subproject commit <old sha1>3840 * for a removal patch.3841 */3842 struct fragment *hunk = p->fragments;3843 static const char heading[] = "-Subproject commit ";3844 char *preimage;38453846 if (/* does the patch have only one hunk? */3847 hunk && !hunk->next &&3848 /* is its preimage one line? */3849 hunk->oldpos == 1 && hunk->oldlines == 1 &&3850 /* does preimage begin with the heading? */3851 (preimage = memchr(hunk->patch, '\n', hunk->size)) != NULL &&3852 starts_with(++preimage, heading) &&3853 /* does it record full SHA-1? */3854 !get_sha1_hex(preimage + sizeof(heading) - 1, sha1) &&3855 preimage[sizeof(heading) + 40 - 1] == '\n' &&3856 /* does the abbreviated name on the index line agree with it? */3857 starts_with(preimage + sizeof(heading) - 1, p->old_sha1_prefix))3858 return 0; /* it all looks fine */38593860 /* we may have full object name on the index line */3861 return get_sha1_hex(p->old_sha1_prefix, sha1);3862}38633864/* Build an index that contains the just the files needed for a 3way merge */3865static void build_fake_ancestor(struct patch *list, const char *filename)3866{3867 struct patch *patch;3868 struct index_state result = { NULL };3869 static struct lock_file lock;38703871 /* Once we start supporting the reverse patch, it may be3872 * worth showing the new sha1 prefix, but until then...3873 */3874 for (patch = list; patch; patch = patch->next) {3875 unsigned char sha1[20];3876 struct cache_entry *ce;3877 const char *name;38783879 name = patch->old_name ? patch->old_name : patch->new_name;3880 if (0 < patch->is_new)3881 continue;38823883 if (S_ISGITLINK(patch->old_mode)) {3884 if (!preimage_sha1_in_gitlink_patch(patch, sha1))3885 ; /* ok, the textual part looks sane */3886 else3887 die("sha1 information is lacking or useless for submodule %s",3888 name);3889 } else if (!get_sha1_blob(patch->old_sha1_prefix, sha1)) {3890 ; /* ok */3891 } else if (!patch->lines_added && !patch->lines_deleted) {3892 /* mode-only change: update the current */3893 if (get_current_sha1(patch->old_name, sha1))3894 die("mode change for %s, which is not "3895 "in current HEAD", name);3896 } else3897 die("sha1 information is lacking or useless "3898 "(%s).", name);38993900 ce = make_cache_entry(patch->old_mode, sha1, name, 0, 0);3901 if (!ce)3902 die(_("make_cache_entry failed for path '%s'"), name);3903 if (add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD))3904 die ("Could not add %s to temporary index", name);3905 }39063907 hold_lock_file_for_update(&lock, filename, LOCK_DIE_ON_ERROR);3908 if (write_locked_index(&result, &lock, COMMIT_LOCK))3909 die ("Could not write temporary index to %s", filename);39103911 discard_index(&result);3912}39133914static void stat_patch_list(struct patch *patch)3915{3916 int files, adds, dels;39173918 for (files = adds = dels = 0 ; patch ; patch = patch->next) {3919 files++;3920 adds += patch->lines_added;3921 dels += patch->lines_deleted;3922 show_stats(patch);3923 }39243925 print_stat_summary(stdout, files, adds, dels);3926}39273928static void numstat_patch_list(struct patch *patch)3929{3930 for ( ; patch; patch = patch->next) {3931 const char *name;3932 name = patch->new_name ? patch->new_name : patch->old_name;3933 if (patch->is_binary)3934 printf("-\t-\t");3935 else3936 printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);3937 write_name_quoted(name, stdout, line_termination);3938 }3939}39403941static void show_file_mode_name(const char *newdelete, unsigned int mode, const char *name)3942{3943 if (mode)3944 printf(" %s mode %06o %s\n", newdelete, mode, name);3945 else3946 printf(" %s %s\n", newdelete, name);3947}39483949static void show_mode_change(struct patch *p, int show_name)3950{3951 if (p->old_mode && p->new_mode && p->old_mode != p->new_mode) {3952 if (show_name)3953 printf(" mode change %06o => %06o %s\n",3954 p->old_mode, p->new_mode, p->new_name);3955 else3956 printf(" mode change %06o => %06o\n",3957 p->old_mode, p->new_mode);3958 }3959}39603961static void show_rename_copy(struct patch *p)3962{3963 const char *renamecopy = p->is_rename ? "rename" : "copy";3964 const char *old, *new;39653966 /* Find common prefix */3967 old = p->old_name;3968 new = p->new_name;3969 while (1) {3970 const char *slash_old, *slash_new;3971 slash_old = strchr(old, '/');3972 slash_new = strchr(new, '/');3973 if (!slash_old ||3974 !slash_new ||3975 slash_old - old != slash_new - new ||3976 memcmp(old, new, slash_new - new))3977 break;3978 old = slash_old + 1;3979 new = slash_new + 1;3980 }3981 /* p->old_name thru old is the common prefix, and old and new3982 * through the end of names are renames3983 */3984 if (old != p->old_name)3985 printf(" %s %.*s{%s => %s} (%d%%)\n", renamecopy,3986 (int)(old - p->old_name), p->old_name,3987 old, new, p->score);3988 else3989 printf(" %s %s => %s (%d%%)\n", renamecopy,3990 p->old_name, p->new_name, p->score);3991 show_mode_change(p, 0);3992}39933994static void summary_patch_list(struct patch *patch)3995{3996 struct patch *p;39973998 for (p = patch; p; p = p->next) {3999 if (p->is_new)4000 show_file_mode_name("create", p->new_mode, p->new_name);4001 else if (p->is_delete)4002 show_file_mode_name("delete", p->old_mode, p->old_name);4003 else {4004 if (p->is_rename || p->is_copy)4005 show_rename_copy(p);4006 else {4007 if (p->score) {4008 printf(" rewrite %s (%d%%)\n",4009 p->new_name, p->score);4010 show_mode_change(p, 0);4011 }4012 else4013 show_mode_change(p, 1);4014 }4015 }4016 }4017}40184019static void patch_stats(struct patch *patch)4020{4021 int lines = patch->lines_added + patch->lines_deleted;40224023 if (lines > max_change)4024 max_change = lines;4025 if (patch->old_name) {4026 int len = quote_c_style(patch->old_name, NULL, NULL, 0);4027 if (!len)4028 len = strlen(patch->old_name);4029 if (len > max_len)4030 max_len = len;4031 }4032 if (patch->new_name) {4033 int len = quote_c_style(patch->new_name, NULL, NULL, 0);4034 if (!len)4035 len = strlen(patch->new_name);4036 if (len > max_len)4037 max_len = len;4038 }4039}40404041static void remove_file(struct patch *patch, int rmdir_empty)4042{4043 if (update_index) {4044 if (remove_file_from_cache(patch->old_name) < 0)4045 die(_("unable to remove %s from index"), patch->old_name);4046 }4047 if (!cached) {4048 if (!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {4049 remove_path(patch->old_name);4050 }4051 }4052}40534054static void add_index_file(const char *path, unsigned mode, void *buf, unsigned long size)4055{4056 struct stat st;4057 struct cache_entry *ce;4058 int namelen = strlen(path);4059 unsigned ce_size = cache_entry_size(namelen);40604061 if (!update_index)4062 return;40634064 ce = xcalloc(1, ce_size);4065 memcpy(ce->name, path, namelen);4066 ce->ce_mode = create_ce_mode(mode);4067 ce->ce_flags = create_ce_flags(0);4068 ce->ce_namelen = namelen;4069 if (S_ISGITLINK(mode)) {4070 const char *s;40714072 if (!skip_prefix(buf, "Subproject commit ", &s) ||4073 get_sha1_hex(s, ce->sha1))4074 die(_("corrupt patch for submodule %s"), path);4075 } else {4076 if (!cached) {4077 if (lstat(path, &st) < 0)4078 die_errno(_("unable to stat newly created file '%s'"),4079 path);4080 fill_stat_cache_info(ce, &st);4081 }4082 if (write_sha1_file(buf, size, blob_type, ce->sha1) < 0)4083 die(_("unable to create backing store for newly created file %s"), path);4084 }4085 if (add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) < 0)4086 die(_("unable to add cache entry for %s"), path);4087}40884089static int try_create_file(const char *path, unsigned int mode, const char *buf, unsigned long size)4090{4091 int fd;4092 struct strbuf nbuf = STRBUF_INIT;40934094 if (S_ISGITLINK(mode)) {4095 struct stat st;4096 if (!lstat(path, &st) && S_ISDIR(st.st_mode))4097 return 0;4098 return mkdir(path, 0777);4099 }41004101 if (has_symlinks && S_ISLNK(mode))4102 /* Although buf:size is counted string, it also is NUL4103 * terminated.4104 */4105 return symlink(buf, path);41064107 fd = open(path, O_CREAT | O_EXCL | O_WRONLY, (mode & 0100) ? 0777 : 0666);4108 if (fd < 0)4109 return -1;41104111 if (convert_to_working_tree(path, buf, size, &nbuf)) {4112 size = nbuf.len;4113 buf = nbuf.buf;4114 }4115 write_or_die(fd, buf, size);4116 strbuf_release(&nbuf);41174118 if (close(fd) < 0)4119 die_errno(_("closing file '%s'"), path);4120 return 0;4121}41224123/*4124 * We optimistically assume that the directories exist,4125 * which is true 99% of the time anyway. If they don't,4126 * we create them and try again.4127 */4128static void create_one_file(char *path, unsigned mode, const char *buf, unsigned long size)4129{4130 if (cached)4131 return;4132 if (!try_create_file(path, mode, buf, size))4133 return;41344135 if (errno == ENOENT) {4136 if (safe_create_leading_directories(path))4137 return;4138 if (!try_create_file(path, mode, buf, size))4139 return;4140 }41414142 if (errno == EEXIST || errno == EACCES) {4143 /* We may be trying to create a file where a directory4144 * used to be.4145 */4146 struct stat st;4147 if (!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))4148 errno = EEXIST;4149 }41504151 if (errno == EEXIST) {4152 unsigned int nr = getpid();41534154 for (;;) {4155 char newpath[PATH_MAX];4156 mksnpath(newpath, sizeof(newpath), "%s~%u", path, nr);4157 if (!try_create_file(newpath, mode, buf, size)) {4158 if (!rename(newpath, path))4159 return;4160 unlink_or_warn(newpath);4161 break;4162 }4163 if (errno != EEXIST)4164 break;4165 ++nr;4166 }4167 }4168 die_errno(_("unable to write file '%s' mode %o"), path, mode);4169}41704171static void add_conflicted_stages_file(struct patch *patch)4172{4173 int stage, namelen;4174 unsigned ce_size, mode;4175 struct cache_entry *ce;41764177 if (!update_index)4178 return;4179 namelen = strlen(patch->new_name);4180 ce_size = cache_entry_size(namelen);4181 mode = patch->new_mode ? patch->new_mode : (S_IFREG | 0644);41824183 remove_file_from_cache(patch->new_name);4184 for (stage = 1; stage < 4; stage++) {4185 if (is_null_oid(&patch->threeway_stage[stage - 1]))4186 continue;4187 ce = xcalloc(1, ce_size);4188 memcpy(ce->name, patch->new_name, namelen);4189 ce->ce_mode = create_ce_mode(mode);4190 ce->ce_flags = create_ce_flags(stage);4191 ce->ce_namelen = namelen;4192 hashcpy(ce->sha1, patch->threeway_stage[stage - 1].hash);4193 if (add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) < 0)4194 die(_("unable to add cache entry for %s"), patch->new_name);4195 }4196}41974198static void create_file(struct patch *patch)4199{4200 char *path = patch->new_name;4201 unsigned mode = patch->new_mode;4202 unsigned long size = patch->resultsize;4203 char *buf = patch->result;42044205 if (!mode)4206 mode = S_IFREG | 0644;4207 create_one_file(path, mode, buf, size);42084209 if (patch->conflicted_threeway)4210 add_conflicted_stages_file(patch);4211 else4212 add_index_file(path, mode, buf, size);4213}42144215/* phase zero is to remove, phase one is to create */4216static void write_out_one_result(struct patch *patch, int phase)4217{4218 if (patch->is_delete > 0) {4219 if (phase == 0)4220 remove_file(patch, 1);4221 return;4222 }4223 if (patch->is_new > 0 || patch->is_copy) {4224 if (phase == 1)4225 create_file(patch);4226 return;4227 }4228 /*4229 * Rename or modification boils down to the same4230 * thing: remove the old, write the new4231 */4232 if (phase == 0)4233 remove_file(patch, patch->is_rename);4234 if (phase == 1)4235 create_file(patch);4236}42374238static int write_out_one_reject(struct patch *patch)4239{4240 FILE *rej;4241 char namebuf[PATH_MAX];4242 struct fragment *frag;4243 int cnt = 0;4244 struct strbuf sb = STRBUF_INIT;42454246 for (cnt = 0, frag = patch->fragments; frag; frag = frag->next) {4247 if (!frag->rejected)4248 continue;4249 cnt++;4250 }42514252 if (!cnt) {4253 if (apply_verbosely)4254 say_patch_name(stderr,4255 _("Applied patch %s cleanly."), patch);4256 return 0;4257 }42584259 /* This should not happen, because a removal patch that leaves4260 * contents are marked "rejected" at the patch level.4261 */4262 if (!patch->new_name)4263 die(_("internal error"));42644265 /* Say this even without --verbose */4266 strbuf_addf(&sb, Q_("Applying patch %%s with %d reject...",4267 "Applying patch %%s with %d rejects...",4268 cnt),4269 cnt);4270 say_patch_name(stderr, sb.buf, patch);4271 strbuf_release(&sb);42724273 cnt = strlen(patch->new_name);4274 if (ARRAY_SIZE(namebuf) <= cnt + 5) {4275 cnt = ARRAY_SIZE(namebuf) - 5;4276 warning(_("truncating .rej filename to %.*s.rej"),4277 cnt - 1, patch->new_name);4278 }4279 memcpy(namebuf, patch->new_name, cnt);4280 memcpy(namebuf + cnt, ".rej", 5);42814282 rej = fopen(namebuf, "w");4283 if (!rej)4284 return error(_("cannot open %s: %s"), namebuf, strerror(errno));42854286 /* Normal git tools never deal with .rej, so do not pretend4287 * this is a git patch by saying --git or giving extended4288 * headers. While at it, maybe please "kompare" that wants4289 * the trailing TAB and some garbage at the end of line ;-).4290 */4291 fprintf(rej, "diff a/%s b/%s\t(rejected hunks)\n",4292 patch->new_name, patch->new_name);4293 for (cnt = 1, frag = patch->fragments;4294 frag;4295 cnt++, frag = frag->next) {4296 if (!frag->rejected) {4297 fprintf_ln(stderr, _("Hunk #%d applied cleanly."), cnt);4298 continue;4299 }4300 fprintf_ln(stderr, _("Rejected hunk #%d."), cnt);4301 fprintf(rej, "%.*s", frag->size, frag->patch);4302 if (frag->patch[frag->size-1] != '\n')4303 fputc('\n', rej);4304 }4305 fclose(rej);4306 return -1;4307}43084309static int write_out_results(struct patch *list)4310{4311 int phase;4312 int errs = 0;4313 struct patch *l;4314 struct string_list cpath = STRING_LIST_INIT_DUP;43154316 for (phase = 0; phase < 2; phase++) {4317 l = list;4318 while (l) {4319 if (l->rejected)4320 errs = 1;4321 else {4322 write_out_one_result(l, phase);4323 if (phase == 1) {4324 if (write_out_one_reject(l))4325 errs = 1;4326 if (l->conflicted_threeway) {4327 string_list_append(&cpath, l->new_name);4328 errs = 1;4329 }4330 }4331 }4332 l = l->next;4333 }4334 }43354336 if (cpath.nr) {4337 struct string_list_item *item;43384339 string_list_sort(&cpath);4340 for_each_string_list_item(item, &cpath)4341 fprintf(stderr, "U %s\n", item->string);4342 string_list_clear(&cpath, 0);43434344 rerere(0);4345 }43464347 return errs;4348}43494350static struct lock_file lock_file;43514352#define INACCURATE_EOF (1<<0)4353#define RECOUNT (1<<1)43544355static int apply_patch(int fd, const char *filename, int options)4356{4357 size_t offset;4358 struct strbuf buf = STRBUF_INIT; /* owns the patch text */4359 struct patch *list = NULL, **listp = &list;4360 int skipped_patch = 0;43614362 patch_input_file = filename;4363 read_patch_file(&buf, fd);4364 offset = 0;4365 while (offset < buf.len) {4366 struct patch *patch;4367 int nr;43684369 patch = xcalloc(1, sizeof(*patch));4370 patch->inaccurate_eof = !!(options & INACCURATE_EOF);4371 patch->recount = !!(options & RECOUNT);4372 nr = parse_chunk(buf.buf + offset, buf.len - offset, patch);4373 if (nr < 0)4374 break;4375 if (apply_in_reverse)4376 reverse_patches(patch);4377 if (use_patch(patch)) {4378 patch_stats(patch);4379 *listp = patch;4380 listp = &patch->next;4381 }4382 else {4383 free_patch(patch);4384 skipped_patch++;4385 }4386 offset += nr;4387 }43884389 if (!list && !skipped_patch)4390 die(_("unrecognized input"));43914392 if (whitespace_error && (ws_error_action == die_on_ws_error))4393 apply = 0;43944395 update_index = check_index && apply;4396 if (update_index && newfd < 0)4397 newfd = hold_locked_index(&lock_file, 1);43984399 if (check_index) {4400 if (read_cache() < 0)4401 die(_("unable to read index file"));4402 }44034404 if ((check || apply) &&4405 check_patch_list(list) < 0 &&4406 !apply_with_reject)4407 exit(1);44084409 if (apply && write_out_results(list)) {4410 if (apply_with_reject)4411 exit(1);4412 /* with --3way, we still need to write the index out */4413 return 1;4414 }44154416 if (fake_ancestor)4417 build_fake_ancestor(list, fake_ancestor);44184419 if (diffstat)4420 stat_patch_list(list);44214422 if (numstat)4423 numstat_patch_list(list);44244425 if (summary)4426 summary_patch_list(list);44274428 free_patch_list(list);4429 strbuf_release(&buf);4430 string_list_clear(&fn_table, 0);4431 return 0;4432}44334434static void git_apply_config(void)4435{4436 git_config_get_string_const("apply.whitespace", &apply_default_whitespace);4437 git_config_get_string_const("apply.ignorewhitespace", &apply_default_ignorewhitespace);4438 git_config(git_default_config, NULL);4439}44404441static int option_parse_exclude(const struct option *opt,4442 const char *arg, int unset)4443{4444 add_name_limit(arg, 1);4445 return 0;4446}44474448static int option_parse_include(const struct option *opt,4449 const char *arg, int unset)4450{4451 add_name_limit(arg, 0);4452 has_include = 1;4453 return 0;4454}44554456static int option_parse_p(const struct option *opt,4457 const char *arg, int unset)4458{4459 p_value = atoi(arg);4460 p_value_known = 1;4461 return 0;4462}44634464static int option_parse_space_change(const struct option *opt,4465 const char *arg, int unset)4466{4467 if (unset)4468 ws_ignore_action = ignore_ws_none;4469 else4470 ws_ignore_action = ignore_ws_change;4471 return 0;4472}44734474static int option_parse_whitespace(const struct option *opt,4475 const char *arg, int unset)4476{4477 const char **whitespace_option = opt->value;44784479 *whitespace_option = arg;4480 parse_whitespace_option(arg);4481 return 0;4482}44834484static int option_parse_directory(const struct option *opt,4485 const char *arg, int unset)4486{4487 strbuf_reset(&root);4488 strbuf_addstr(&root, arg);4489 strbuf_complete(&root, '/');4490 return 0;4491}44924493int cmd_apply(int argc, const char **argv, const char *prefix_)4494{4495 int i;4496 int errs = 0;4497 int is_not_gitdir = !startup_info->have_repository;4498 int force_apply = 0;44994500 const char *whitespace_option = NULL;45014502 struct option builtin_apply_options[] = {4503 { OPTION_CALLBACK, 0, "exclude", NULL, N_("path"),4504 N_("don't apply changes matching the given path"),4505 0, option_parse_exclude },4506 { OPTION_CALLBACK, 0, "include", NULL, N_("path"),4507 N_("apply changes matching the given path"),4508 0, option_parse_include },4509 { OPTION_CALLBACK, 'p', NULL, NULL, N_("num"),4510 N_("remove <num> leading slashes from traditional diff paths"),4511 0, option_parse_p },4512 OPT_BOOL(0, "no-add", &no_add,4513 N_("ignore additions made by the patch")),4514 OPT_BOOL(0, "stat", &diffstat,4515 N_("instead of applying the patch, output diffstat for the input")),4516 OPT_NOOP_NOARG(0, "allow-binary-replacement"),4517 OPT_NOOP_NOARG(0, "binary"),4518 OPT_BOOL(0, "numstat", &numstat,4519 N_("show number of added and deleted lines in decimal notation")),4520 OPT_BOOL(0, "summary", &summary,4521 N_("instead of applying the patch, output a summary for the input")),4522 OPT_BOOL(0, "check", &check,4523 N_("instead of applying the patch, see if the patch is applicable")),4524 OPT_BOOL(0, "index", &check_index,4525 N_("make sure the patch is applicable to the current index")),4526 OPT_BOOL(0, "cached", &cached,4527 N_("apply a patch without touching the working tree")),4528 OPT_BOOL(0, "unsafe-paths", &unsafe_paths,4529 N_("accept a patch that touches outside the working area")),4530 OPT_BOOL(0, "apply", &force_apply,4531 N_("also apply the patch (use with --stat/--summary/--check)")),4532 OPT_BOOL('3', "3way", &threeway,4533 N_( "attempt three-way merge if a patch does not apply")),4534 OPT_FILENAME(0, "build-fake-ancestor", &fake_ancestor,4535 N_("build a temporary index based on embedded index information")),4536 /* Think twice before adding "--nul" synonym to this */4537 OPT_SET_INT('z', NULL, &line_termination,4538 N_("paths are separated with NUL character"), '\0'),4539 OPT_INTEGER('C', NULL, &p_context,4540 N_("ensure at least <n> lines of context match")),4541 { OPTION_CALLBACK, 0, "whitespace", &whitespace_option, N_("action"),4542 N_("detect new or modified lines that have whitespace errors"),4543 0, option_parse_whitespace },4544 { OPTION_CALLBACK, 0, "ignore-space-change", NULL, NULL,4545 N_("ignore changes in whitespace when finding context"),4546 PARSE_OPT_NOARG, option_parse_space_change },4547 { OPTION_CALLBACK, 0, "ignore-whitespace", NULL, NULL,4548 N_("ignore changes in whitespace when finding context"),4549 PARSE_OPT_NOARG, option_parse_space_change },4550 OPT_BOOL('R', "reverse", &apply_in_reverse,4551 N_("apply the patch in reverse")),4552 OPT_BOOL(0, "unidiff-zero", &unidiff_zero,4553 N_("don't expect at least one line of context")),4554 OPT_BOOL(0, "reject", &apply_with_reject,4555 N_("leave the rejected hunks in corresponding *.rej files")),4556 OPT_BOOL(0, "allow-overlap", &allow_overlap,4557 N_("allow overlapping hunks")),4558 OPT__VERBOSE(&apply_verbosely, N_("be verbose")),4559 OPT_BIT(0, "inaccurate-eof", &options,4560 N_("tolerate incorrectly detected missing new-line at the end of file"),4561 INACCURATE_EOF),4562 OPT_BIT(0, "recount", &options,4563 N_("do not trust the line counts in the hunk headers"),4564 RECOUNT),4565 { OPTION_CALLBACK, 0, "directory", NULL, N_("root"),4566 N_("prepend <root> to all filenames"),4567 0, option_parse_directory },4568 OPT_END()4569 };45704571 prefix = prefix_;4572 prefix_length = prefix ? strlen(prefix) : 0;4573 git_apply_config();4574 if (apply_default_whitespace)4575 parse_whitespace_option(apply_default_whitespace);4576 if (apply_default_ignorewhitespace)4577 parse_ignorewhitespace_option(apply_default_ignorewhitespace);45784579 argc = parse_options(argc, argv, prefix, builtin_apply_options,4580 apply_usage, 0);45814582 if (apply_with_reject && threeway)4583 die("--reject and --3way cannot be used together.");4584 if (cached && threeway)4585 die("--cached and --3way cannot be used together.");4586 if (threeway) {4587 if (is_not_gitdir)4588 die(_("--3way outside a repository"));4589 check_index = 1;4590 }4591 if (apply_with_reject)4592 apply = apply_verbosely = 1;4593 if (!force_apply && (diffstat || numstat || summary || check || fake_ancestor))4594 apply = 0;4595 if (check_index && is_not_gitdir)4596 die(_("--index outside a repository"));4597 if (cached) {4598 if (is_not_gitdir)4599 die(_("--cached outside a repository"));4600 check_index = 1;4601 }4602 if (check_index)4603 unsafe_paths = 0;46044605 for (i = 0; i < argc; i++) {4606 const char *arg = argv[i];4607 int fd;46084609 if (!strcmp(arg, "-")) {4610 errs |= apply_patch(0, "<stdin>", options);4611 read_stdin = 0;4612 continue;4613 } else if (0 < prefix_length)4614 arg = prefix_filename(prefix, prefix_length, arg);46154616 fd = open(arg, O_RDONLY);4617 if (fd < 0)4618 die_errno(_("can't open patch '%s'"), arg);4619 read_stdin = 0;4620 set_default_whitespace_mode(whitespace_option);4621 errs |= apply_patch(fd, arg, options);4622 close(fd);4623 }4624 set_default_whitespace_mode(whitespace_option);4625 if (read_stdin)4626 errs |= apply_patch(0, "<stdin>", options);4627 if (whitespace_error) {4628 if (squelch_whitespace_errors &&4629 squelch_whitespace_errors < whitespace_error) {4630 int squelched =4631 whitespace_error - squelch_whitespace_errors;4632 warning(Q_("squelched %d whitespace error",4633 "squelched %d whitespace errors",4634 squelched),4635 squelched);4636 }4637 if (ws_error_action == die_on_ws_error)4638 die(Q_("%d line adds whitespace errors.",4639 "%d lines add whitespace errors.",4640 whitespace_error),4641 whitespace_error);4642 if (applied_after_fixing_ws && apply)4643 warning("%d line%s applied after"4644 " fixing whitespace errors.",4645 applied_after_fixing_ws,4646 applied_after_fixing_ws == 1 ? "" : "s");4647 else if (whitespace_error)4648 warning(Q_("%d line adds whitespace errors.",4649 "%d lines add whitespace errors.",4650 whitespace_error),4651 whitespace_error);4652 }46534654 if (update_index) {4655 if (write_locked_index(&the_index, &lock_file, COMMIT_LOCK))4656 die(_("Unable to write new index file"));4657 }46584659 return !!errs;4660}