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 state_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; 81 82static void parse_whitespace_option(const char *option) 83{ 84 if (!option) { 85 ws_error_action = warn_on_ws_error; 86 return; 87 } 88 if (!strcmp(option, "warn")) { 89 ws_error_action = warn_on_ws_error; 90 return; 91 } 92 if (!strcmp(option, "nowarn")) { 93 ws_error_action = nowarn_ws_error; 94 return; 95 } 96 if (!strcmp(option, "error")) { 97 ws_error_action = die_on_ws_error; 98 return; 99 } 100 if (!strcmp(option, "error-all")) { 101 ws_error_action = die_on_ws_error; 102 squelch_whitespace_errors = 0; 103 return; 104 } 105 if (!strcmp(option, "strip") || !strcmp(option, "fix")) { 106 ws_error_action = correct_ws_error; 107 return; 108 } 109 die(_("unrecognized whitespace option '%s'"), option); 110} 111 112static void parse_ignorewhitespace_option(const char *option) 113{ 114 if (!option || !strcmp(option, "no") || 115 !strcmp(option, "false") || !strcmp(option, "never") || 116 !strcmp(option, "none")) { 117 ws_ignore_action = ignore_ws_none; 118 return; 119 } 120 if (!strcmp(option, "change")) { 121 ws_ignore_action = ignore_ws_change; 122 return; 123 } 124 die(_("unrecognized whitespace ignore option '%s'"), option); 125} 126 127static void set_default_whitespace_mode(const char *whitespace_option) 128{ 129 if (!whitespace_option && !apply_default_whitespace) 130 ws_error_action = (apply ? warn_on_ws_error : nowarn_ws_error); 131} 132 133/* 134 * For "diff-stat" like behaviour, we keep track of the biggest change 135 * we've seen, and the longest filename. That allows us to do simple 136 * scaling. 137 */ 138static int max_change, max_len; 139 140/* 141 * Various "current state", notably line numbers and what 142 * file (and how) we're patching right now.. The "is_xxxx" 143 * things are flags, where -1 means "don't know yet". 144 */ 145static int state_linenr = 1; 146 147/* 148 * This represents one "hunk" from a patch, starting with 149 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The 150 * patch text is pointed at by patch, and its byte length 151 * is stored in size. leading and trailing are the number 152 * of context lines. 153 */ 154struct fragment { 155 unsigned long leading, trailing; 156 unsigned long oldpos, oldlines; 157 unsigned long newpos, newlines; 158 /* 159 * 'patch' is usually borrowed from buf in apply_patch(), 160 * but some codepaths store an allocated buffer. 161 */ 162 const char *patch; 163 unsigned free_patch:1, 164 rejected:1; 165 int size; 166 int linenr; 167 struct fragment *next; 168}; 169 170/* 171 * When dealing with a binary patch, we reuse "leading" field 172 * to store the type of the binary hunk, either deflated "delta" 173 * or deflated "literal". 174 */ 175#define binary_patch_method leading 176#define BINARY_DELTA_DEFLATED 1 177#define BINARY_LITERAL_DEFLATED 2 178 179/* 180 * This represents a "patch" to a file, both metainfo changes 181 * such as creation/deletion, filemode and content changes represented 182 * as a series of fragments. 183 */ 184struct patch { 185 char *new_name, *old_name, *def_name; 186 unsigned int old_mode, new_mode; 187 int is_new, is_delete; /* -1 = unknown, 0 = false, 1 = true */ 188 int rejected; 189 unsigned ws_rule; 190 int lines_added, lines_deleted; 191 int score; 192 unsigned int is_toplevel_relative:1; 193 unsigned int inaccurate_eof:1; 194 unsigned int is_binary:1; 195 unsigned int is_copy:1; 196 unsigned int is_rename:1; 197 unsigned int recount:1; 198 unsigned int conflicted_threeway:1; 199 unsigned int direct_to_threeway:1; 200 struct fragment *fragments; 201 char *result; 202 size_t resultsize; 203 char old_sha1_prefix[41]; 204 char new_sha1_prefix[41]; 205 struct patch *next; 206 207 /* three-way fallback result */ 208 struct object_id threeway_stage[3]; 209}; 210 211static void free_fragment_list(struct fragment *list) 212{ 213 while (list) { 214 struct fragment *next = list->next; 215 if (list->free_patch) 216 free((char *)list->patch); 217 free(list); 218 list = next; 219 } 220} 221 222static void free_patch(struct patch *patch) 223{ 224 free_fragment_list(patch->fragments); 225 free(patch->def_name); 226 free(patch->old_name); 227 free(patch->new_name); 228 free(patch->result); 229 free(patch); 230} 231 232static void free_patch_list(struct patch *list) 233{ 234 while (list) { 235 struct patch *next = list->next; 236 free_patch(list); 237 list = next; 238 } 239} 240 241/* 242 * A line in a file, len-bytes long (includes the terminating LF, 243 * except for an incomplete line at the end if the file ends with 244 * one), and its contents hashes to 'hash'. 245 */ 246struct line { 247 size_t len; 248 unsigned hash : 24; 249 unsigned flag : 8; 250#define LINE_COMMON 1 251#define LINE_PATCHED 2 252}; 253 254/* 255 * This represents a "file", which is an array of "lines". 256 */ 257struct image { 258 char *buf; 259 size_t len; 260 size_t nr; 261 size_t alloc; 262 struct line *line_allocated; 263 struct line *line; 264}; 265 266/* 267 * Records filenames that have been touched, in order to handle 268 * the case where more than one patches touch the same file. 269 */ 270 271static struct string_list fn_table; 272 273static uint32_t hash_line(const char *cp, size_t len) 274{ 275 size_t i; 276 uint32_t h; 277 for (i = 0, h = 0; i < len; i++) { 278 if (!isspace(cp[i])) { 279 h = h * 3 + (cp[i] & 0xff); 280 } 281 } 282 return h; 283} 284 285/* 286 * Compare lines s1 of length n1 and s2 of length n2, ignoring 287 * whitespace difference. Returns 1 if they match, 0 otherwise 288 */ 289static int fuzzy_matchlines(const char *s1, size_t n1, 290 const char *s2, size_t n2) 291{ 292 const char *last1 = s1 + n1 - 1; 293 const char *last2 = s2 + n2 - 1; 294 int result = 0; 295 296 /* ignore line endings */ 297 while ((*last1 == '\r') || (*last1 == '\n')) 298 last1--; 299 while ((*last2 == '\r') || (*last2 == '\n')) 300 last2--; 301 302 /* skip leading whitespaces, if both begin with whitespace */ 303 if (s1 <= last1 && s2 <= last2 && isspace(*s1) && isspace(*s2)) { 304 while (isspace(*s1) && (s1 <= last1)) 305 s1++; 306 while (isspace(*s2) && (s2 <= last2)) 307 s2++; 308 } 309 /* early return if both lines are empty */ 310 if ((s1 > last1) && (s2 > last2)) 311 return 1; 312 while (!result) { 313 result = *s1++ - *s2++; 314 /* 315 * Skip whitespace inside. We check for whitespace on 316 * both buffers because we don't want "a b" to match 317 * "ab" 318 */ 319 if (isspace(*s1) && isspace(*s2)) { 320 while (isspace(*s1) && s1 <= last1) 321 s1++; 322 while (isspace(*s2) && s2 <= last2) 323 s2++; 324 } 325 /* 326 * If we reached the end on one side only, 327 * lines don't match 328 */ 329 if ( 330 ((s2 > last2) && (s1 <= last1)) || 331 ((s1 > last1) && (s2 <= last2))) 332 return 0; 333 if ((s1 > last1) && (s2 > last2)) 334 break; 335 } 336 337 return !result; 338} 339 340static void add_line_info(struct image *img, const char *bol, size_t len, unsigned flag) 341{ 342 ALLOC_GROW(img->line_allocated, img->nr + 1, img->alloc); 343 img->line_allocated[img->nr].len = len; 344 img->line_allocated[img->nr].hash = hash_line(bol, len); 345 img->line_allocated[img->nr].flag = flag; 346 img->nr++; 347} 348 349/* 350 * "buf" has the file contents to be patched (read from various sources). 351 * attach it to "image" and add line-based index to it. 352 * "image" now owns the "buf". 353 */ 354static void prepare_image(struct image *image, char *buf, size_t len, 355 int prepare_linetable) 356{ 357 const char *cp, *ep; 358 359 memset(image, 0, sizeof(*image)); 360 image->buf = buf; 361 image->len = len; 362 363 if (!prepare_linetable) 364 return; 365 366 ep = image->buf + image->len; 367 cp = image->buf; 368 while (cp < ep) { 369 const char *next; 370 for (next = cp; next < ep && *next != '\n'; next++) 371 ; 372 if (next < ep) 373 next++; 374 add_line_info(image, cp, next - cp, 0); 375 cp = next; 376 } 377 image->line = image->line_allocated; 378} 379 380static void clear_image(struct image *image) 381{ 382 free(image->buf); 383 free(image->line_allocated); 384 memset(image, 0, sizeof(*image)); 385} 386 387/* fmt must contain _one_ %s and no other substitution */ 388static void say_patch_name(FILE *output, const char *fmt, struct patch *patch) 389{ 390 struct strbuf sb = STRBUF_INIT; 391 392 if (patch->old_name && patch->new_name && 393 strcmp(patch->old_name, patch->new_name)) { 394 quote_c_style(patch->old_name, &sb, NULL, 0); 395 strbuf_addstr(&sb, " => "); 396 quote_c_style(patch->new_name, &sb, NULL, 0); 397 } else { 398 const char *n = patch->new_name; 399 if (!n) 400 n = patch->old_name; 401 quote_c_style(n, &sb, NULL, 0); 402 } 403 fprintf(output, fmt, sb.buf); 404 fputc('\n', output); 405 strbuf_release(&sb); 406} 407 408#define SLOP (16) 409 410static void read_patch_file(struct strbuf *sb, int fd) 411{ 412 if (strbuf_read(sb, fd, 0) < 0) 413 die_errno("git apply: failed to read"); 414 415 /* 416 * Make sure that we have some slop in the buffer 417 * so that we can do speculative "memcmp" etc, and 418 * see to it that it is NUL-filled. 419 */ 420 strbuf_grow(sb, SLOP); 421 memset(sb->buf + sb->len, 0, SLOP); 422} 423 424static unsigned long linelen(const char *buffer, unsigned long size) 425{ 426 unsigned long len = 0; 427 while (size--) { 428 len++; 429 if (*buffer++ == '\n') 430 break; 431 } 432 return len; 433} 434 435static int is_dev_null(const char *str) 436{ 437 return skip_prefix(str, "/dev/null", &str) && isspace(*str); 438} 439 440#define TERM_SPACE 1 441#define TERM_TAB 2 442 443static int name_terminate(const char *name, int namelen, int c, int terminate) 444{ 445 if (c == ' ' && !(terminate & TERM_SPACE)) 446 return 0; 447 if (c == '\t' && !(terminate & TERM_TAB)) 448 return 0; 449 450 return 1; 451} 452 453/* remove double slashes to make --index work with such filenames */ 454static char *squash_slash(char *name) 455{ 456 int i = 0, j = 0; 457 458 if (!name) 459 return NULL; 460 461 while (name[i]) { 462 if ((name[j++] = name[i++]) == '/') 463 while (name[i] == '/') 464 i++; 465 } 466 name[j] = '\0'; 467 return name; 468} 469 470static char *find_name_gnu(const char *line, const char *def, int p_value) 471{ 472 struct strbuf name = STRBUF_INIT; 473 char *cp; 474 475 /* 476 * Proposed "new-style" GNU patch/diff format; see 477 * http://marc.info/?l=git&m=112927316408690&w=2 478 */ 479 if (unquote_c_style(&name, line, NULL)) { 480 strbuf_release(&name); 481 return NULL; 482 } 483 484 for (cp = name.buf; p_value; p_value--) { 485 cp = strchr(cp, '/'); 486 if (!cp) { 487 strbuf_release(&name); 488 return NULL; 489 } 490 cp++; 491 } 492 493 strbuf_remove(&name, 0, cp - name.buf); 494 if (root.len) 495 strbuf_insert(&name, 0, root.buf, root.len); 496 return squash_slash(strbuf_detach(&name, NULL)); 497} 498 499static size_t sane_tz_len(const char *line, size_t len) 500{ 501 const char *tz, *p; 502 503 if (len < strlen(" +0500") || line[len-strlen(" +0500")] != ' ') 504 return 0; 505 tz = line + len - strlen(" +0500"); 506 507 if (tz[1] != '+' && tz[1] != '-') 508 return 0; 509 510 for (p = tz + 2; p != line + len; p++) 511 if (!isdigit(*p)) 512 return 0; 513 514 return line + len - tz; 515} 516 517static size_t tz_with_colon_len(const char *line, size_t len) 518{ 519 const char *tz, *p; 520 521 if (len < strlen(" +08:00") || line[len - strlen(":00")] != ':') 522 return 0; 523 tz = line + len - strlen(" +08:00"); 524 525 if (tz[0] != ' ' || (tz[1] != '+' && tz[1] != '-')) 526 return 0; 527 p = tz + 2; 528 if (!isdigit(*p++) || !isdigit(*p++) || *p++ != ':' || 529 !isdigit(*p++) || !isdigit(*p++)) 530 return 0; 531 532 return line + len - tz; 533} 534 535static size_t date_len(const char *line, size_t len) 536{ 537 const char *date, *p; 538 539 if (len < strlen("72-02-05") || line[len-strlen("-05")] != '-') 540 return 0; 541 p = date = line + len - strlen("72-02-05"); 542 543 if (!isdigit(*p++) || !isdigit(*p++) || *p++ != '-' || 544 !isdigit(*p++) || !isdigit(*p++) || *p++ != '-' || 545 !isdigit(*p++) || !isdigit(*p++)) /* Not a date. */ 546 return 0; 547 548 if (date - line >= strlen("19") && 549 isdigit(date[-1]) && isdigit(date[-2])) /* 4-digit year */ 550 date -= strlen("19"); 551 552 return line + len - date; 553} 554 555static size_t short_time_len(const char *line, size_t len) 556{ 557 const char *time, *p; 558 559 if (len < strlen(" 07:01:32") || line[len-strlen(":32")] != ':') 560 return 0; 561 p = time = line + len - strlen(" 07:01:32"); 562 563 /* Permit 1-digit hours? */ 564 if (*p++ != ' ' || 565 !isdigit(*p++) || !isdigit(*p++) || *p++ != ':' || 566 !isdigit(*p++) || !isdigit(*p++) || *p++ != ':' || 567 !isdigit(*p++) || !isdigit(*p++)) /* Not a time. */ 568 return 0; 569 570 return line + len - time; 571} 572 573static size_t fractional_time_len(const char *line, size_t len) 574{ 575 const char *p; 576 size_t n; 577 578 /* Expected format: 19:41:17.620000023 */ 579 if (!len || !isdigit(line[len - 1])) 580 return 0; 581 p = line + len - 1; 582 583 /* Fractional seconds. */ 584 while (p > line && isdigit(*p)) 585 p--; 586 if (*p != '.') 587 return 0; 588 589 /* Hours, minutes, and whole seconds. */ 590 n = short_time_len(line, p - line); 591 if (!n) 592 return 0; 593 594 return line + len - p + n; 595} 596 597static size_t trailing_spaces_len(const char *line, size_t len) 598{ 599 const char *p; 600 601 /* Expected format: ' ' x (1 or more) */ 602 if (!len || line[len - 1] != ' ') 603 return 0; 604 605 p = line + len; 606 while (p != line) { 607 p--; 608 if (*p != ' ') 609 return line + len - (p + 1); 610 } 611 612 /* All spaces! */ 613 return len; 614} 615 616static size_t diff_timestamp_len(const char *line, size_t len) 617{ 618 const char *end = line + len; 619 size_t n; 620 621 /* 622 * Posix: 2010-07-05 19:41:17 623 * GNU: 2010-07-05 19:41:17.620000023 -0500 624 */ 625 626 if (!isdigit(end[-1])) 627 return 0; 628 629 n = sane_tz_len(line, end - line); 630 if (!n) 631 n = tz_with_colon_len(line, end - line); 632 end -= n; 633 634 n = short_time_len(line, end - line); 635 if (!n) 636 n = fractional_time_len(line, end - line); 637 end -= n; 638 639 n = date_len(line, end - line); 640 if (!n) /* No date. Too bad. */ 641 return 0; 642 end -= n; 643 644 if (end == line) /* No space before date. */ 645 return 0; 646 if (end[-1] == '\t') { /* Success! */ 647 end--; 648 return line + len - end; 649 } 650 if (end[-1] != ' ') /* No space before date. */ 651 return 0; 652 653 /* Whitespace damage. */ 654 end -= trailing_spaces_len(line, end - line); 655 return line + len - end; 656} 657 658static char *find_name_common(const char *line, const char *def, 659 int p_value, const char *end, int terminate) 660{ 661 int len; 662 const char *start = NULL; 663 664 if (p_value == 0) 665 start = line; 666 while (line != end) { 667 char c = *line; 668 669 if (!end && isspace(c)) { 670 if (c == '\n') 671 break; 672 if (name_terminate(start, line-start, c, terminate)) 673 break; 674 } 675 line++; 676 if (c == '/' && !--p_value) 677 start = line; 678 } 679 if (!start) 680 return squash_slash(xstrdup_or_null(def)); 681 len = line - start; 682 if (!len) 683 return squash_slash(xstrdup_or_null(def)); 684 685 /* 686 * Generally we prefer the shorter name, especially 687 * if the other one is just a variation of that with 688 * something else tacked on to the end (ie "file.orig" 689 * or "file~"). 690 */ 691 if (def) { 692 int deflen = strlen(def); 693 if (deflen < len && !strncmp(start, def, deflen)) 694 return squash_slash(xstrdup(def)); 695 } 696 697 if (root.len) { 698 char *ret = xstrfmt("%s%.*s", root.buf, len, start); 699 return squash_slash(ret); 700 } 701 702 return squash_slash(xmemdupz(start, len)); 703} 704 705static char *find_name(const char *line, char *def, int p_value, int terminate) 706{ 707 if (*line == '"') { 708 char *name = find_name_gnu(line, def, p_value); 709 if (name) 710 return name; 711 } 712 713 return find_name_common(line, def, p_value, NULL, terminate); 714} 715 716static char *find_name_traditional(const char *line, char *def, int p_value) 717{ 718 size_t len; 719 size_t date_len; 720 721 if (*line == '"') { 722 char *name = find_name_gnu(line, def, p_value); 723 if (name) 724 return name; 725 } 726 727 len = strchrnul(line, '\n') - line; 728 date_len = diff_timestamp_len(line, len); 729 if (!date_len) 730 return find_name_common(line, def, p_value, NULL, TERM_TAB); 731 len -= date_len; 732 733 return find_name_common(line, def, p_value, line + len, 0); 734} 735 736static int count_slashes(const char *cp) 737{ 738 int cnt = 0; 739 char ch; 740 741 while ((ch = *cp++)) 742 if (ch == '/') 743 cnt++; 744 return cnt; 745} 746 747/* 748 * Given the string after "--- " or "+++ ", guess the appropriate 749 * p_value for the given patch. 750 */ 751static int guess_p_value(const char *nameline) 752{ 753 char *name, *cp; 754 int val = -1; 755 756 if (is_dev_null(nameline)) 757 return -1; 758 name = find_name_traditional(nameline, NULL, 0); 759 if (!name) 760 return -1; 761 cp = strchr(name, '/'); 762 if (!cp) 763 val = 0; 764 else if (prefix) { 765 /* 766 * Does it begin with "a/$our-prefix" and such? Then this is 767 * very likely to apply to our directory. 768 */ 769 if (!strncmp(name, prefix, prefix_length)) 770 val = count_slashes(prefix); 771 else { 772 cp++; 773 if (!strncmp(cp, prefix, prefix_length)) 774 val = count_slashes(prefix) + 1; 775 } 776 } 777 free(name); 778 return val; 779} 780 781/* 782 * Does the ---/+++ line have the POSIX timestamp after the last HT? 783 * GNU diff puts epoch there to signal a creation/deletion event. Is 784 * this such a timestamp? 785 */ 786static int has_epoch_timestamp(const char *nameline) 787{ 788 /* 789 * We are only interested in epoch timestamp; any non-zero 790 * fraction cannot be one, hence "(\.0+)?" in the regexp below. 791 * For the same reason, the date must be either 1969-12-31 or 792 * 1970-01-01, and the seconds part must be "00". 793 */ 794 const char stamp_regexp[] = 795 "^(1969-12-31|1970-01-01)" 796 " " 797 "[0-2][0-9]:[0-5][0-9]:00(\\.0+)?" 798 " " 799 "([-+][0-2][0-9]:?[0-5][0-9])\n"; 800 const char *timestamp = NULL, *cp, *colon; 801 static regex_t *stamp; 802 regmatch_t m[10]; 803 int zoneoffset; 804 int hourminute; 805 int status; 806 807 for (cp = nameline; *cp != '\n'; cp++) { 808 if (*cp == '\t') 809 timestamp = cp + 1; 810 } 811 if (!timestamp) 812 return 0; 813 if (!stamp) { 814 stamp = xmalloc(sizeof(*stamp)); 815 if (regcomp(stamp, stamp_regexp, REG_EXTENDED)) { 816 warning(_("Cannot prepare timestamp regexp %s"), 817 stamp_regexp); 818 return 0; 819 } 820 } 821 822 status = regexec(stamp, timestamp, ARRAY_SIZE(m), m, 0); 823 if (status) { 824 if (status != REG_NOMATCH) 825 warning(_("regexec returned %d for input: %s"), 826 status, timestamp); 827 return 0; 828 } 829 830 zoneoffset = strtol(timestamp + m[3].rm_so + 1, (char **) &colon, 10); 831 if (*colon == ':') 832 zoneoffset = zoneoffset * 60 + strtol(colon + 1, NULL, 10); 833 else 834 zoneoffset = (zoneoffset / 100) * 60 + (zoneoffset % 100); 835 if (timestamp[m[3].rm_so] == '-') 836 zoneoffset = -zoneoffset; 837 838 /* 839 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31 840 * (west of GMT) or 1970-01-01 (east of GMT) 841 */ 842 if ((zoneoffset < 0 && memcmp(timestamp, "1969-12-31", 10)) || 843 (0 <= zoneoffset && memcmp(timestamp, "1970-01-01", 10))) 844 return 0; 845 846 hourminute = (strtol(timestamp + 11, NULL, 10) * 60 + 847 strtol(timestamp + 14, NULL, 10) - 848 zoneoffset); 849 850 return ((zoneoffset < 0 && hourminute == 1440) || 851 (0 <= zoneoffset && !hourminute)); 852} 853 854/* 855 * Get the name etc info from the ---/+++ lines of a traditional patch header 856 * 857 * FIXME! The end-of-filename heuristics are kind of screwy. For existing 858 * files, we can happily check the index for a match, but for creating a 859 * new file we should try to match whatever "patch" does. I have no idea. 860 */ 861static void parse_traditional_patch(const char *first, const char *second, struct patch *patch) 862{ 863 char *name; 864 865 first += 4; /* skip "--- " */ 866 second += 4; /* skip "+++ " */ 867 if (!p_value_known) { 868 int p, q; 869 p = guess_p_value(first); 870 q = guess_p_value(second); 871 if (p < 0) p = q; 872 if (0 <= p && p == q) { 873 state_p_value = p; 874 p_value_known = 1; 875 } 876 } 877 if (is_dev_null(first)) { 878 patch->is_new = 1; 879 patch->is_delete = 0; 880 name = find_name_traditional(second, NULL, state_p_value); 881 patch->new_name = name; 882 } else if (is_dev_null(second)) { 883 patch->is_new = 0; 884 patch->is_delete = 1; 885 name = find_name_traditional(first, NULL, state_p_value); 886 patch->old_name = name; 887 } else { 888 char *first_name; 889 first_name = find_name_traditional(first, NULL, state_p_value); 890 name = find_name_traditional(second, first_name, state_p_value); 891 free(first_name); 892 if (has_epoch_timestamp(first)) { 893 patch->is_new = 1; 894 patch->is_delete = 0; 895 patch->new_name = name; 896 } else if (has_epoch_timestamp(second)) { 897 patch->is_new = 0; 898 patch->is_delete = 1; 899 patch->old_name = name; 900 } else { 901 patch->old_name = name; 902 patch->new_name = xstrdup_or_null(name); 903 } 904 } 905 if (!name) 906 die(_("unable to find filename in patch at line %d"), state_linenr); 907} 908 909static int gitdiff_hdrend(const char *line, struct patch *patch) 910{ 911 return -1; 912} 913 914/* 915 * We're anal about diff header consistency, to make 916 * sure that we don't end up having strange ambiguous 917 * patches floating around. 918 * 919 * As a result, gitdiff_{old|new}name() will check 920 * their names against any previous information, just 921 * to make sure.. 922 */ 923#define DIFF_OLD_NAME 0 924#define DIFF_NEW_NAME 1 925 926static void gitdiff_verify_name(const char *line, int isnull, char **name, int side) 927{ 928 if (!*name && !isnull) { 929 *name = find_name(line, NULL, state_p_value, TERM_TAB); 930 return; 931 } 932 933 if (*name) { 934 int len = strlen(*name); 935 char *another; 936 if (isnull) 937 die(_("git apply: bad git-diff - expected /dev/null, got %s on line %d"), 938 *name, state_linenr); 939 another = find_name(line, NULL, state_p_value, TERM_TAB); 940 if (!another || memcmp(another, *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"), state_linenr); 944 free(another); 945 } else { 946 /* expect "/dev/null" */ 947 if (memcmp("/dev/null", line, 9) || line[9] != '\n') 948 die(_("git apply: bad git-diff - expected /dev/null on line %d"), state_linenr); 949 } 950} 951 952static int gitdiff_oldname(const char *line, struct patch *patch) 953{ 954 gitdiff_verify_name(line, patch->is_new, &patch->old_name, 955 DIFF_OLD_NAME); 956 return 0; 957} 958 959static int gitdiff_newname(const char *line, struct patch *patch) 960{ 961 gitdiff_verify_name(line, patch->is_delete, &patch->new_name, 962 DIFF_NEW_NAME); 963 return 0; 964} 965 966static int gitdiff_oldmode(const char *line, struct patch *patch) 967{ 968 patch->old_mode = strtoul(line, NULL, 8); 969 return 0; 970} 971 972static int gitdiff_newmode(const char *line, struct patch *patch) 973{ 974 patch->new_mode = strtoul(line, NULL, 8); 975 return 0; 976} 977 978static int gitdiff_delete(const char *line, struct patch *patch) 979{ 980 patch->is_delete = 1; 981 free(patch->old_name); 982 patch->old_name = xstrdup_or_null(patch->def_name); 983 return gitdiff_oldmode(line, patch); 984} 985 986static int gitdiff_newfile(const char *line, struct patch *patch) 987{ 988 patch->is_new = 1; 989 free(patch->new_name); 990 patch->new_name = xstrdup_or_null(patch->def_name); 991 return gitdiff_newmode(line, patch); 992} 993 994static int gitdiff_copysrc(const char *line, struct patch *patch) 995{ 996 patch->is_copy = 1; 997 free(patch->old_name); 998 patch->old_name = find_name(line, NULL, state_p_value ? state_p_value - 1 : 0, 0); 999 return 0;1000}10011002static int gitdiff_copydst(const char *line, struct patch *patch)1003{1004 patch->is_copy = 1;1005 free(patch->new_name);1006 patch->new_name = find_name(line, NULL, state_p_value ? state_p_value - 1 : 0, 0);1007 return 0;1008}10091010static int gitdiff_renamesrc(const char *line, struct patch *patch)1011{1012 patch->is_rename = 1;1013 free(patch->old_name);1014 patch->old_name = find_name(line, NULL, state_p_value ? state_p_value - 1 : 0, 0);1015 return 0;1016}10171018static int gitdiff_renamedst(const char *line, struct patch *patch)1019{1020 patch->is_rename = 1;1021 free(patch->new_name);1022 patch->new_name = find_name(line, NULL, state_p_value ? state_p_value - 1 : 0, 0);1023 return 0;1024}10251026static int gitdiff_similarity(const char *line, struct patch *patch)1027{1028 unsigned long val = strtoul(line, NULL, 10);1029 if (val <= 100)1030 patch->score = val;1031 return 0;1032}10331034static int gitdiff_dissimilarity(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_index(const char *line, struct patch *patch)1043{1044 /*1045 * index line is N hexadecimal, "..", N hexadecimal,1046 * and optional space with octal mode.1047 */1048 const char *ptr, *eol;1049 int len;10501051 ptr = strchr(line, '.');1052 if (!ptr || ptr[1] != '.' || 40 < ptr - line)1053 return 0;1054 len = ptr - line;1055 memcpy(patch->old_sha1_prefix, line, len);1056 patch->old_sha1_prefix[len] = 0;10571058 line = ptr + 2;1059 ptr = strchr(line, ' ');1060 eol = strchrnul(line, '\n');10611062 if (!ptr || eol < ptr)1063 ptr = eol;1064 len = ptr - line;10651066 if (40 < len)1067 return 0;1068 memcpy(patch->new_sha1_prefix, line, len);1069 patch->new_sha1_prefix[len] = 0;1070 if (*ptr == ' ')1071 patch->old_mode = strtoul(ptr+1, NULL, 8);1072 return 0;1073}10741075/*1076 * This is normal for a diff that doesn't change anything: we'll fall through1077 * into the next diff. Tell the parser to break out.1078 */1079static int gitdiff_unrecognized(const char *line, struct patch *patch)1080{1081 return -1;1082}10831084/*1085 * Skip p_value leading components from "line"; as we do not accept1086 * absolute paths, return NULL in that case.1087 */1088static const char *skip_tree_prefix(const char *line, int llen)1089{1090 int nslash;1091 int i;10921093 if (!state_p_value)1094 return (llen && line[0] == '/') ? NULL : line;10951096 nslash = state_p_value;1097 for (i = 0; i < llen; i++) {1098 int ch = line[i];1099 if (ch == '/' && --nslash <= 0)1100 return (i == 0) ? NULL : &line[i + 1];1101 }1102 return NULL;1103}11041105/*1106 * This is to extract the same name that appears on "diff --git"1107 * line. We do not find and return anything if it is a rename1108 * patch, and it is OK because we will find the name elsewhere.1109 * We need to reliably find name only when it is mode-change only,1110 * creation or deletion of an empty file. In any of these cases,1111 * both sides are the same name under a/ and b/ respectively.1112 */1113static char *git_header_name(const char *line, int llen)1114{1115 const char *name;1116 const char *second = NULL;1117 size_t len, line_len;11181119 line += strlen("diff --git ");1120 llen -= strlen("diff --git ");11211122 if (*line == '"') {1123 const char *cp;1124 struct strbuf first = STRBUF_INIT;1125 struct strbuf sp = STRBUF_INIT;11261127 if (unquote_c_style(&first, line, &second))1128 goto free_and_fail1;11291130 /* strip the a/b prefix including trailing slash */1131 cp = skip_tree_prefix(first.buf, first.len);1132 if (!cp)1133 goto free_and_fail1;1134 strbuf_remove(&first, 0, cp - first.buf);11351136 /*1137 * second points at one past closing dq of name.1138 * find the second name.1139 */1140 while ((second < line + llen) && isspace(*second))1141 second++;11421143 if (line + llen <= second)1144 goto free_and_fail1;1145 if (*second == '"') {1146 if (unquote_c_style(&sp, second, NULL))1147 goto free_and_fail1;1148 cp = skip_tree_prefix(sp.buf, sp.len);1149 if (!cp)1150 goto free_and_fail1;1151 /* They must match, otherwise ignore */1152 if (strcmp(cp, first.buf))1153 goto free_and_fail1;1154 strbuf_release(&sp);1155 return strbuf_detach(&first, NULL);1156 }11571158 /* unquoted second */1159 cp = skip_tree_prefix(second, line + llen - second);1160 if (!cp)1161 goto free_and_fail1;1162 if (line + llen - cp != first.len ||1163 memcmp(first.buf, cp, first.len))1164 goto free_and_fail1;1165 return strbuf_detach(&first, NULL);11661167 free_and_fail1:1168 strbuf_release(&first);1169 strbuf_release(&sp);1170 return NULL;1171 }11721173 /* unquoted first name */1174 name = skip_tree_prefix(line, llen);1175 if (!name)1176 return NULL;11771178 /*1179 * since the first name is unquoted, a dq if exists must be1180 * the beginning of the second name.1181 */1182 for (second = name; second < line + llen; second++) {1183 if (*second == '"') {1184 struct strbuf sp = STRBUF_INIT;1185 const char *np;11861187 if (unquote_c_style(&sp, second, NULL))1188 goto free_and_fail2;11891190 np = skip_tree_prefix(sp.buf, sp.len);1191 if (!np)1192 goto free_and_fail2;11931194 len = sp.buf + sp.len - np;1195 if (len < second - name &&1196 !strncmp(np, name, len) &&1197 isspace(name[len])) {1198 /* Good */1199 strbuf_remove(&sp, 0, np - sp.buf);1200 return strbuf_detach(&sp, NULL);1201 }12021203 free_and_fail2:1204 strbuf_release(&sp);1205 return NULL;1206 }1207 }12081209 /*1210 * Accept a name only if it shows up twice, exactly the same1211 * form.1212 */1213 second = strchr(name, '\n');1214 if (!second)1215 return NULL;1216 line_len = second - name;1217 for (len = 0 ; ; len++) {1218 switch (name[len]) {1219 default:1220 continue;1221 case '\n':1222 return NULL;1223 case '\t': case ' ':1224 /*1225 * Is this the separator between the preimage1226 * and the postimage pathname? Again, we are1227 * only interested in the case where there is1228 * no rename, as this is only to set def_name1229 * and a rename patch has the names elsewhere1230 * in an unambiguous form.1231 */1232 if (!name[len + 1])1233 return NULL; /* no postimage name */1234 second = skip_tree_prefix(name + len + 1,1235 line_len - (len + 1));1236 if (!second)1237 return NULL;1238 /*1239 * Does len bytes starting at "name" and "second"1240 * (that are separated by one HT or SP we just1241 * found) exactly match?1242 */1243 if (second[len] == '\n' && !strncmp(name, second, len))1244 return xmemdupz(name, len);1245 }1246 }1247}12481249/* Verify that we recognize the lines following a git header */1250static int parse_git_header(const char *line, int len, unsigned int size, struct patch *patch)1251{1252 unsigned long offset;12531254 /* A git diff has explicit new/delete information, so we don't guess */1255 patch->is_new = 0;1256 patch->is_delete = 0;12571258 /*1259 * Some things may not have the old name in the1260 * rest of the headers anywhere (pure mode changes,1261 * or removing or adding empty files), so we get1262 * the default name from the header.1263 */1264 patch->def_name = git_header_name(line, len);1265 if (patch->def_name && root.len) {1266 char *s = xstrfmt("%s%s", root.buf, patch->def_name);1267 free(patch->def_name);1268 patch->def_name = s;1269 }12701271 line += len;1272 size -= len;1273 state_linenr++;1274 for (offset = len ; size > 0 ; offset += len, size -= len, line += len, state_linenr++) {1275 static const struct opentry {1276 const char *str;1277 int (*fn)(const char *, struct patch *);1278 } optable[] = {1279 { "@@ -", gitdiff_hdrend },1280 { "--- ", gitdiff_oldname },1281 { "+++ ", gitdiff_newname },1282 { "old mode ", gitdiff_oldmode },1283 { "new mode ", gitdiff_newmode },1284 { "deleted file mode ", gitdiff_delete },1285 { "new file mode ", gitdiff_newfile },1286 { "copy from ", gitdiff_copysrc },1287 { "copy to ", gitdiff_copydst },1288 { "rename old ", gitdiff_renamesrc },1289 { "rename new ", gitdiff_renamedst },1290 { "rename from ", gitdiff_renamesrc },1291 { "rename to ", gitdiff_renamedst },1292 { "similarity index ", gitdiff_similarity },1293 { "dissimilarity index ", gitdiff_dissimilarity },1294 { "index ", gitdiff_index },1295 { "", gitdiff_unrecognized },1296 };1297 int i;12981299 len = linelen(line, size);1300 if (!len || line[len-1] != '\n')1301 break;1302 for (i = 0; i < ARRAY_SIZE(optable); i++) {1303 const struct opentry *p = optable + i;1304 int oplen = strlen(p->str);1305 if (len < oplen || memcmp(p->str, line, oplen))1306 continue;1307 if (p->fn(line + oplen, patch) < 0)1308 return offset;1309 break;1310 }1311 }13121313 return offset;1314}13151316static int parse_num(const char *line, unsigned long *p)1317{1318 char *ptr;13191320 if (!isdigit(*line))1321 return 0;1322 *p = strtoul(line, &ptr, 10);1323 return ptr - line;1324}13251326static int parse_range(const char *line, int len, int offset, const char *expect,1327 unsigned long *p1, unsigned long *p2)1328{1329 int digits, ex;13301331 if (offset < 0 || offset >= len)1332 return -1;1333 line += offset;1334 len -= offset;13351336 digits = parse_num(line, p1);1337 if (!digits)1338 return -1;13391340 offset += digits;1341 line += digits;1342 len -= digits;13431344 *p2 = 1;1345 if (*line == ',') {1346 digits = parse_num(line+1, p2);1347 if (!digits)1348 return -1;13491350 offset += digits+1;1351 line += digits+1;1352 len -= digits+1;1353 }13541355 ex = strlen(expect);1356 if (ex > len)1357 return -1;1358 if (memcmp(line, expect, ex))1359 return -1;13601361 return offset + ex;1362}13631364static void recount_diff(const char *line, int size, struct fragment *fragment)1365{1366 int oldlines = 0, newlines = 0, ret = 0;13671368 if (size < 1) {1369 warning("recount: ignore empty hunk");1370 return;1371 }13721373 for (;;) {1374 int len = linelen(line, size);1375 size -= len;1376 line += len;13771378 if (size < 1)1379 break;13801381 switch (*line) {1382 case ' ': case '\n':1383 newlines++;1384 /* fall through */1385 case '-':1386 oldlines++;1387 continue;1388 case '+':1389 newlines++;1390 continue;1391 case '\\':1392 continue;1393 case '@':1394 ret = size < 3 || !starts_with(line, "@@ ");1395 break;1396 case 'd':1397 ret = size < 5 || !starts_with(line, "diff ");1398 break;1399 default:1400 ret = -1;1401 break;1402 }1403 if (ret) {1404 warning(_("recount: unexpected line: %.*s"),1405 (int)linelen(line, size), line);1406 return;1407 }1408 break;1409 }1410 fragment->oldlines = oldlines;1411 fragment->newlines = newlines;1412}14131414/*1415 * Parse a unified diff fragment header of the1416 * form "@@ -a,b +c,d @@"1417 */1418static int parse_fragment_header(const char *line, int len, struct fragment *fragment)1419{1420 int offset;14211422 if (!len || line[len-1] != '\n')1423 return -1;14241425 /* Figure out the number of lines in a fragment */1426 offset = parse_range(line, len, 4, " +", &fragment->oldpos, &fragment->oldlines);1427 offset = parse_range(line, len, offset, " @@", &fragment->newpos, &fragment->newlines);14281429 return offset;1430}14311432static int find_header(const char *line, unsigned long size, int *hdrsize, struct patch *patch)1433{1434 unsigned long offset, len;14351436 patch->is_toplevel_relative = 0;1437 patch->is_rename = patch->is_copy = 0;1438 patch->is_new = patch->is_delete = -1;1439 patch->old_mode = patch->new_mode = 0;1440 patch->old_name = patch->new_name = NULL;1441 for (offset = 0; size > 0; offset += len, size -= len, line += len, state_linenr++) {1442 unsigned long nextlen;14431444 len = linelen(line, size);1445 if (!len)1446 break;14471448 /* Testing this early allows us to take a few shortcuts.. */1449 if (len < 6)1450 continue;14511452 /*1453 * Make sure we don't find any unconnected patch fragments.1454 * That's a sign that we didn't find a header, and that a1455 * patch has become corrupted/broken up.1456 */1457 if (!memcmp("@@ -", line, 4)) {1458 struct fragment dummy;1459 if (parse_fragment_header(line, len, &dummy) < 0)1460 continue;1461 die(_("patch fragment without header at line %d: %.*s"),1462 state_linenr, (int)len-1, line);1463 }14641465 if (size < len + 6)1466 break;14671468 /*1469 * Git patch? It might not have a real patch, just a rename1470 * or mode change, so we handle that specially1471 */1472 if (!memcmp("diff --git ", line, 11)) {1473 int git_hdr_len = parse_git_header(line, len, size, patch);1474 if (git_hdr_len <= len)1475 continue;1476 if (!patch->old_name && !patch->new_name) {1477 if (!patch->def_name)1478 die(Q_("git diff header lacks filename information when removing "1479 "%d leading pathname component (line %d)",1480 "git diff header lacks filename information when removing "1481 "%d leading pathname components (line %d)",1482 state_p_value),1483 state_p_value, state_linenr);1484 patch->old_name = xstrdup(patch->def_name);1485 patch->new_name = xstrdup(patch->def_name);1486 }1487 if (!patch->is_delete && !patch->new_name)1488 die("git diff header lacks filename information "1489 "(line %d)", state_linenr);1490 patch->is_toplevel_relative = 1;1491 *hdrsize = git_hdr_len;1492 return offset;1493 }14941495 /* --- followed by +++ ? */1496 if (memcmp("--- ", line, 4) || memcmp("+++ ", line + len, 4))1497 continue;14981499 /*1500 * We only accept unified patches, so we want it to1501 * at least have "@@ -a,b +c,d @@\n", which is 14 chars1502 * minimum ("@@ -0,0 +1 @@\n" is the shortest).1503 */1504 nextlen = linelen(line + len, size - len);1505 if (size < nextlen + 14 || memcmp("@@ -", line + len + nextlen, 4))1506 continue;15071508 /* Ok, we'll consider it a patch */1509 parse_traditional_patch(line, line+len, patch);1510 *hdrsize = len + nextlen;1511 state_linenr += 2;1512 return offset;1513 }1514 return -1;1515}15161517static void record_ws_error(unsigned result, const char *line, int len, int linenr)1518{1519 char *err;15201521 if (!result)1522 return;15231524 whitespace_error++;1525 if (squelch_whitespace_errors &&1526 squelch_whitespace_errors < whitespace_error)1527 return;15281529 err = whitespace_error_string(result);1530 fprintf(stderr, "%s:%d: %s.\n%.*s\n",1531 patch_input_file, linenr, err, len, line);1532 free(err);1533}15341535static void check_whitespace(const char *line, int len, unsigned ws_rule)1536{1537 unsigned result = ws_check(line + 1, len - 1, ws_rule);15381539 record_ws_error(result, line + 1, len - 2, state_linenr);1540}15411542/*1543 * Parse a unified diff. Note that this really needs to parse each1544 * fragment separately, since the only way to know the difference1545 * between a "---" that is part of a patch, and a "---" that starts1546 * the next patch is to look at the line counts..1547 */1548static int parse_fragment(const char *line, unsigned long size,1549 struct patch *patch, struct fragment *fragment)1550{1551 int added, deleted;1552 int len = linelen(line, size), offset;1553 unsigned long oldlines, newlines;1554 unsigned long leading, trailing;15551556 offset = parse_fragment_header(line, len, fragment);1557 if (offset < 0)1558 return -1;1559 if (offset > 0 && patch->recount)1560 recount_diff(line + offset, size - offset, fragment);1561 oldlines = fragment->oldlines;1562 newlines = fragment->newlines;1563 leading = 0;1564 trailing = 0;15651566 /* Parse the thing.. */1567 line += len;1568 size -= len;1569 state_linenr++;1570 added = deleted = 0;1571 for (offset = len;1572 0 < size;1573 offset += len, size -= len, line += len, state_linenr++) {1574 if (!oldlines && !newlines)1575 break;1576 len = linelen(line, size);1577 if (!len || line[len-1] != '\n')1578 return -1;1579 switch (*line) {1580 default:1581 return -1;1582 case '\n': /* newer GNU diff, an empty context line */1583 case ' ':1584 oldlines--;1585 newlines--;1586 if (!deleted && !added)1587 leading++;1588 trailing++;1589 if (!apply_in_reverse &&1590 ws_error_action == correct_ws_error)1591 check_whitespace(line, len, patch->ws_rule);1592 break;1593 case '-':1594 if (apply_in_reverse &&1595 ws_error_action != nowarn_ws_error)1596 check_whitespace(line, len, patch->ws_rule);1597 deleted++;1598 oldlines--;1599 trailing = 0;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 added++;1606 newlines--;1607 trailing = 0;1608 break;16091610 /*1611 * We allow "\ No newline at end of file". Depending1612 * on locale settings when the patch was produced we1613 * don't know what this line looks like. The only1614 * thing we do know is that it begins with "\ ".1615 * Checking for 12 is just for sanity check -- any1616 * l10n of "\ No newline..." is at least that long.1617 */1618 case '\\':1619 if (len < 12 || memcmp(line, "\\ ", 2))1620 return -1;1621 break;1622 }1623 }1624 if (oldlines || newlines)1625 return -1;1626 if (!deleted && !added)1627 return -1;16281629 fragment->leading = leading;1630 fragment->trailing = trailing;16311632 /*1633 * If a fragment ends with an incomplete line, we failed to include1634 * it in the above loop because we hit oldlines == newlines == 01635 * before seeing it.1636 */1637 if (12 < size && !memcmp(line, "\\ ", 2))1638 offset += linelen(line, size);16391640 patch->lines_added += added;1641 patch->lines_deleted += deleted;16421643 if (0 < patch->is_new && oldlines)1644 return error(_("new file depends on old contents"));1645 if (0 < patch->is_delete && newlines)1646 return error(_("deleted file still has contents"));1647 return offset;1648}16491650/*1651 * We have seen "diff --git a/... b/..." header (or a traditional patch1652 * header). Read hunks that belong to this patch into fragments and hang1653 * them to the given patch structure.1654 *1655 * The (fragment->patch, fragment->size) pair points into the memory given1656 * by the caller, not a copy, when we return.1657 */1658static int parse_single_patch(const char *line, unsigned long size, struct patch *patch)1659{1660 unsigned long offset = 0;1661 unsigned long oldlines = 0, newlines = 0, context = 0;1662 struct fragment **fragp = &patch->fragments;16631664 while (size > 4 && !memcmp(line, "@@ -", 4)) {1665 struct fragment *fragment;1666 int len;16671668 fragment = xcalloc(1, sizeof(*fragment));1669 fragment->linenr = state_linenr;1670 len = parse_fragment(line, size, patch, fragment);1671 if (len <= 0)1672 die(_("corrupt patch at line %d"), state_linenr);1673 fragment->patch = line;1674 fragment->size = len;1675 oldlines += fragment->oldlines;1676 newlines += fragment->newlines;1677 context += fragment->leading + fragment->trailing;16781679 *fragp = fragment;1680 fragp = &fragment->next;16811682 offset += len;1683 line += len;1684 size -= len;1685 }16861687 /*1688 * If something was removed (i.e. we have old-lines) it cannot1689 * be creation, and if something was added it cannot be1690 * deletion. However, the reverse is not true; --unified=01691 * patches that only add are not necessarily creation even1692 * though they do not have any old lines, and ones that only1693 * delete are not necessarily deletion.1694 *1695 * Unfortunately, a real creation/deletion patch do _not_ have1696 * any context line by definition, so we cannot safely tell it1697 * apart with --unified=0 insanity. At least if the patch has1698 * more than one hunk it is not creation or deletion.1699 */1700 if (patch->is_new < 0 &&1701 (oldlines || (patch->fragments && patch->fragments->next)))1702 patch->is_new = 0;1703 if (patch->is_delete < 0 &&1704 (newlines || (patch->fragments && patch->fragments->next)))1705 patch->is_delete = 0;17061707 if (0 < patch->is_new && oldlines)1708 die(_("new file %s depends on old contents"), patch->new_name);1709 if (0 < patch->is_delete && newlines)1710 die(_("deleted file %s still has contents"), patch->old_name);1711 if (!patch->is_delete && !newlines && context)1712 fprintf_ln(stderr,1713 _("** warning: "1714 "file %s becomes empty but is not deleted"),1715 patch->new_name);17161717 return offset;1718}17191720static inline int metadata_changes(struct patch *patch)1721{1722 return patch->is_rename > 0 ||1723 patch->is_copy > 0 ||1724 patch->is_new > 0 ||1725 patch->is_delete ||1726 (patch->old_mode && patch->new_mode &&1727 patch->old_mode != patch->new_mode);1728}17291730static char *inflate_it(const void *data, unsigned long size,1731 unsigned long inflated_size)1732{1733 git_zstream stream;1734 void *out;1735 int st;17361737 memset(&stream, 0, sizeof(stream));17381739 stream.next_in = (unsigned char *)data;1740 stream.avail_in = size;1741 stream.next_out = out = xmalloc(inflated_size);1742 stream.avail_out = inflated_size;1743 git_inflate_init(&stream);1744 st = git_inflate(&stream, Z_FINISH);1745 git_inflate_end(&stream);1746 if ((st != Z_STREAM_END) || stream.total_out != inflated_size) {1747 free(out);1748 return NULL;1749 }1750 return out;1751}17521753/*1754 * Read a binary hunk and return a new fragment; fragment->patch1755 * points at an allocated memory that the caller must free, so1756 * it is marked as "->free_patch = 1".1757 */1758static struct fragment *parse_binary_hunk(char **buf_p,1759 unsigned long *sz_p,1760 int *status_p,1761 int *used_p)1762{1763 /*1764 * Expect a line that begins with binary patch method ("literal"1765 * or "delta"), followed by the length of data before deflating.1766 * a sequence of 'length-byte' followed by base-85 encoded data1767 * should follow, terminated by a newline.1768 *1769 * Each 5-byte sequence of base-85 encodes up to 4 bytes,1770 * and we would limit the patch line to 66 characters,1771 * so one line can fit up to 13 groups that would decode1772 * to 52 bytes max. The length byte 'A'-'Z' corresponds1773 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.1774 */1775 int llen, used;1776 unsigned long size = *sz_p;1777 char *buffer = *buf_p;1778 int patch_method;1779 unsigned long origlen;1780 char *data = NULL;1781 int hunk_size = 0;1782 struct fragment *frag;17831784 llen = linelen(buffer, size);1785 used = llen;17861787 *status_p = 0;17881789 if (starts_with(buffer, "delta ")) {1790 patch_method = BINARY_DELTA_DEFLATED;1791 origlen = strtoul(buffer + 6, NULL, 10);1792 }1793 else if (starts_with(buffer, "literal ")) {1794 patch_method = BINARY_LITERAL_DEFLATED;1795 origlen = strtoul(buffer + 8, NULL, 10);1796 }1797 else1798 return NULL;17991800 state_linenr++;1801 buffer += llen;1802 while (1) {1803 int byte_length, max_byte_length, newsize;1804 llen = linelen(buffer, size);1805 used += llen;1806 state_linenr++;1807 if (llen == 1) {1808 /* consume the blank line */1809 buffer++;1810 size--;1811 break;1812 }1813 /*1814 * Minimum line is "A00000\n" which is 7-byte long,1815 * and the line length must be multiple of 5 plus 2.1816 */1817 if ((llen < 7) || (llen-2) % 5)1818 goto corrupt;1819 max_byte_length = (llen - 2) / 5 * 4;1820 byte_length = *buffer;1821 if ('A' <= byte_length && byte_length <= 'Z')1822 byte_length = byte_length - 'A' + 1;1823 else if ('a' <= byte_length && byte_length <= 'z')1824 byte_length = byte_length - 'a' + 27;1825 else1826 goto corrupt;1827 /* if the input length was not multiple of 4, we would1828 * have filler at the end but the filler should never1829 * exceed 3 bytes1830 */1831 if (max_byte_length < byte_length ||1832 byte_length <= max_byte_length - 4)1833 goto corrupt;1834 newsize = hunk_size + byte_length;1835 data = xrealloc(data, newsize);1836 if (decode_85(data + hunk_size, buffer + 1, byte_length))1837 goto corrupt;1838 hunk_size = newsize;1839 buffer += llen;1840 size -= llen;1841 }18421843 frag = xcalloc(1, sizeof(*frag));1844 frag->patch = inflate_it(data, hunk_size, origlen);1845 frag->free_patch = 1;1846 if (!frag->patch)1847 goto corrupt;1848 free(data);1849 frag->size = origlen;1850 *buf_p = buffer;1851 *sz_p = size;1852 *used_p = used;1853 frag->binary_patch_method = patch_method;1854 return frag;18551856 corrupt:1857 free(data);1858 *status_p = -1;1859 error(_("corrupt binary patch at line %d: %.*s"),1860 state_linenr-1, llen-1, buffer);1861 return NULL;1862}18631864/*1865 * Returns:1866 * -1 in case of error,1867 * the length of the parsed binary patch otherwise1868 */1869static int parse_binary(char *buffer, unsigned long size, struct patch *patch)1870{1871 /*1872 * We have read "GIT binary patch\n"; what follows is a line1873 * that says the patch method (currently, either "literal" or1874 * "delta") and the length of data before deflating; a1875 * sequence of 'length-byte' followed by base-85 encoded data1876 * follows.1877 *1878 * When a binary patch is reversible, there is another binary1879 * hunk in the same format, starting with patch method (either1880 * "literal" or "delta") with the length of data, and a sequence1881 * of length-byte + base-85 encoded data, terminated with another1882 * empty line. This data, when applied to the postimage, produces1883 * the preimage.1884 */1885 struct fragment *forward;1886 struct fragment *reverse;1887 int status;1888 int used, used_1;18891890 forward = parse_binary_hunk(&buffer, &size, &status, &used);1891 if (!forward && !status)1892 /* there has to be one hunk (forward hunk) */1893 return error(_("unrecognized binary patch at line %d"), state_linenr-1);1894 if (status)1895 /* otherwise we already gave an error message */1896 return status;18971898 reverse = parse_binary_hunk(&buffer, &size, &status, &used_1);1899 if (reverse)1900 used += used_1;1901 else if (status) {1902 /*1903 * Not having reverse hunk is not an error, but having1904 * a corrupt reverse hunk is.1905 */1906 free((void*) forward->patch);1907 free(forward);1908 return status;1909 }1910 forward->next = reverse;1911 patch->fragments = forward;1912 patch->is_binary = 1;1913 return used;1914}19151916static void prefix_one(char **name)1917{1918 char *old_name = *name;1919 if (!old_name)1920 return;1921 *name = xstrdup(prefix_filename(prefix, prefix_length, *name));1922 free(old_name);1923}19241925static void prefix_patch(struct patch *p)1926{1927 if (!prefix || p->is_toplevel_relative)1928 return;1929 prefix_one(&p->new_name);1930 prefix_one(&p->old_name);1931}19321933/*1934 * include/exclude1935 */19361937static struct string_list limit_by_name;1938static int has_include;1939static void add_name_limit(const char *name, int exclude)1940{1941 struct string_list_item *it;19421943 it = string_list_append(&limit_by_name, name);1944 it->util = exclude ? NULL : (void *) 1;1945}19461947static int use_patch(struct patch *p)1948{1949 const char *pathname = p->new_name ? p->new_name : p->old_name;1950 int i;19511952 /* Paths outside are not touched regardless of "--include" */1953 if (0 < prefix_length) {1954 int pathlen = strlen(pathname);1955 if (pathlen <= prefix_length ||1956 memcmp(prefix, pathname, prefix_length))1957 return 0;1958 }19591960 /* See if it matches any of exclude/include rule */1961 for (i = 0; i < limit_by_name.nr; i++) {1962 struct string_list_item *it = &limit_by_name.items[i];1963 if (!wildmatch(it->string, pathname, 0, NULL))1964 return (it->util != NULL);1965 }19661967 /*1968 * If we had any include, a path that does not match any rule is1969 * not used. Otherwise, we saw bunch of exclude rules (or none)1970 * and such a path is used.1971 */1972 return !has_include;1973}197419751976/*1977 * Read the patch text in "buffer" that extends for "size" bytes; stop1978 * reading after seeing a single patch (i.e. changes to a single file).1979 * Create fragments (i.e. patch hunks) and hang them to the given patch.1980 * Return the number of bytes consumed, so that the caller can call us1981 * again for the next patch.1982 */1983static int parse_chunk(char *buffer, unsigned long size, struct patch *patch)1984{1985 int hdrsize, patchsize;1986 int offset = find_header(buffer, size, &hdrsize, patch);19871988 if (offset < 0)1989 return offset;19901991 prefix_patch(patch);19921993 if (!use_patch(patch))1994 patch->ws_rule = 0;1995 else1996 patch->ws_rule = whitespace_rule(patch->new_name1997 ? patch->new_name1998 : patch->old_name);19992000 patchsize = parse_single_patch(buffer + offset + hdrsize,2001 size - offset - hdrsize, patch);20022003 if (!patchsize) {2004 static const char git_binary[] = "GIT binary patch\n";2005 int hd = hdrsize + offset;2006 unsigned long llen = linelen(buffer + hd, size - hd);20072008 if (llen == sizeof(git_binary) - 1 &&2009 !memcmp(git_binary, buffer + hd, llen)) {2010 int used;2011 state_linenr++;2012 used = parse_binary(buffer + hd + llen,2013 size - hd - llen, patch);2014 if (used < 0)2015 return -1;2016 if (used)2017 patchsize = used + llen;2018 else2019 patchsize = 0;2020 }2021 else if (!memcmp(" differ\n", buffer + hd + llen - 8, 8)) {2022 static const char *binhdr[] = {2023 "Binary files ",2024 "Files ",2025 NULL,2026 };2027 int i;2028 for (i = 0; binhdr[i]; i++) {2029 int len = strlen(binhdr[i]);2030 if (len < size - hd &&2031 !memcmp(binhdr[i], buffer + hd, len)) {2032 state_linenr++;2033 patch->is_binary = 1;2034 patchsize = llen;2035 break;2036 }2037 }2038 }20392040 /* Empty patch cannot be applied if it is a text patch2041 * without metadata change. A binary patch appears2042 * empty to us here.2043 */2044 if ((apply || check) &&2045 (!patch->is_binary && !metadata_changes(patch)))2046 die(_("patch with only garbage at line %d"), state_linenr);2047 }20482049 return offset + hdrsize + patchsize;2050}20512052#define swap(a,b) myswap((a),(b),sizeof(a))20532054#define myswap(a, b, size) do { \2055 unsigned char mytmp[size]; \2056 memcpy(mytmp, &a, size); \2057 memcpy(&a, &b, size); \2058 memcpy(&b, mytmp, size); \2059} while (0)20602061static void reverse_patches(struct patch *p)2062{2063 for (; p; p = p->next) {2064 struct fragment *frag = p->fragments;20652066 swap(p->new_name, p->old_name);2067 swap(p->new_mode, p->old_mode);2068 swap(p->is_new, p->is_delete);2069 swap(p->lines_added, p->lines_deleted);2070 swap(p->old_sha1_prefix, p->new_sha1_prefix);20712072 for (; frag; frag = frag->next) {2073 swap(frag->newpos, frag->oldpos);2074 swap(frag->newlines, frag->oldlines);2075 }2076 }2077}20782079static const char pluses[] =2080"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";2081static const char minuses[]=2082"----------------------------------------------------------------------";20832084static void show_stats(struct patch *patch)2085{2086 struct strbuf qname = STRBUF_INIT;2087 char *cp = patch->new_name ? patch->new_name : patch->old_name;2088 int max, add, del;20892090 quote_c_style(cp, &qname, NULL, 0);20912092 /*2093 * "scale" the filename2094 */2095 max = max_len;2096 if (max > 50)2097 max = 50;20982099 if (qname.len > max) {2100 cp = strchr(qname.buf + qname.len + 3 - max, '/');2101 if (!cp)2102 cp = qname.buf + qname.len + 3 - max;2103 strbuf_splice(&qname, 0, cp - qname.buf, "...", 3);2104 }21052106 if (patch->is_binary) {2107 printf(" %-*s | Bin\n", max, qname.buf);2108 strbuf_release(&qname);2109 return;2110 }21112112 printf(" %-*s |", max, qname.buf);2113 strbuf_release(&qname);21142115 /*2116 * scale the add/delete2117 */2118 max = max + max_change > 70 ? 70 - max : max_change;2119 add = patch->lines_added;2120 del = patch->lines_deleted;21212122 if (max_change > 0) {2123 int total = ((add + del) * max + max_change / 2) / max_change;2124 add = (add * max + max_change / 2) / max_change;2125 del = total - add;2126 }2127 printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,2128 add, pluses, del, minuses);2129}21302131static int read_old_data(struct stat *st, const char *path, struct strbuf *buf)2132{2133 switch (st->st_mode & S_IFMT) {2134 case S_IFLNK:2135 if (strbuf_readlink(buf, path, st->st_size) < 0)2136 return error(_("unable to read symlink %s"), path);2137 return 0;2138 case S_IFREG:2139 if (strbuf_read_file(buf, path, st->st_size) != st->st_size)2140 return error(_("unable to open or read %s"), path);2141 convert_to_git(path, buf->buf, buf->len, buf, 0);2142 return 0;2143 default:2144 return -1;2145 }2146}21472148/*2149 * Update the preimage, and the common lines in postimage,2150 * from buffer buf of length len. If postlen is 0 the postimage2151 * is updated in place, otherwise it's updated on a new buffer2152 * of length postlen2153 */21542155static void update_pre_post_images(struct image *preimage,2156 struct image *postimage,2157 char *buf,2158 size_t len, size_t postlen)2159{2160 int i, ctx, reduced;2161 char *new, *old, *fixed;2162 struct image fixed_preimage;21632164 /*2165 * Update the preimage with whitespace fixes. Note that we2166 * are not losing preimage->buf -- apply_one_fragment() will2167 * free "oldlines".2168 */2169 prepare_image(&fixed_preimage, buf, len, 1);2170 assert(postlen2171 ? fixed_preimage.nr == preimage->nr2172 : fixed_preimage.nr <= preimage->nr);2173 for (i = 0; i < fixed_preimage.nr; i++)2174 fixed_preimage.line[i].flag = preimage->line[i].flag;2175 free(preimage->line_allocated);2176 *preimage = fixed_preimage;21772178 /*2179 * Adjust the common context lines in postimage. This can be2180 * done in-place when we are shrinking it with whitespace2181 * fixing, but needs a new buffer when ignoring whitespace or2182 * expanding leading tabs to spaces.2183 *2184 * We trust the caller to tell us if the update can be done2185 * in place (postlen==0) or not.2186 */2187 old = postimage->buf;2188 if (postlen)2189 new = postimage->buf = xmalloc(postlen);2190 else2191 new = old;2192 fixed = preimage->buf;21932194 for (i = reduced = ctx = 0; i < postimage->nr; i++) {2195 size_t l_len = postimage->line[i].len;2196 if (!(postimage->line[i].flag & LINE_COMMON)) {2197 /* an added line -- no counterparts in preimage */2198 memmove(new, old, l_len);2199 old += l_len;2200 new += l_len;2201 continue;2202 }22032204 /* a common context -- skip it in the original postimage */2205 old += l_len;22062207 /* and find the corresponding one in the fixed preimage */2208 while (ctx < preimage->nr &&2209 !(preimage->line[ctx].flag & LINE_COMMON)) {2210 fixed += preimage->line[ctx].len;2211 ctx++;2212 }22132214 /*2215 * preimage is expected to run out, if the caller2216 * fixed addition of trailing blank lines.2217 */2218 if (preimage->nr <= ctx) {2219 reduced++;2220 continue;2221 }22222223 /* and copy it in, while fixing the line length */2224 l_len = preimage->line[ctx].len;2225 memcpy(new, fixed, l_len);2226 new += l_len;2227 fixed += l_len;2228 postimage->line[i].len = l_len;2229 ctx++;2230 }22312232 if (postlen2233 ? postlen < new - postimage->buf2234 : postimage->len < new - postimage->buf)2235 die("BUG: caller miscounted postlen: asked %d, orig = %d, used = %d",2236 (int)postlen, (int) postimage->len, (int)(new - postimage->buf));22372238 /* Fix the length of the whole thing */2239 postimage->len = new - postimage->buf;2240 postimage->nr -= reduced;2241}22422243static int line_by_line_fuzzy_match(struct image *img,2244 struct image *preimage,2245 struct image *postimage,2246 unsigned long try,2247 int try_lno,2248 int preimage_limit)2249{2250 int i;2251 size_t imgoff = 0;2252 size_t preoff = 0;2253 size_t postlen = postimage->len;2254 size_t extra_chars;2255 char *buf;2256 char *preimage_eof;2257 char *preimage_end;2258 struct strbuf fixed;2259 char *fixed_buf;2260 size_t fixed_len;22612262 for (i = 0; i < preimage_limit; i++) {2263 size_t prelen = preimage->line[i].len;2264 size_t imglen = img->line[try_lno+i].len;22652266 if (!fuzzy_matchlines(img->buf + try + imgoff, imglen,2267 preimage->buf + preoff, prelen))2268 return 0;2269 if (preimage->line[i].flag & LINE_COMMON)2270 postlen += imglen - prelen;2271 imgoff += imglen;2272 preoff += prelen;2273 }22742275 /*2276 * Ok, the preimage matches with whitespace fuzz.2277 *2278 * imgoff now holds the true length of the target that2279 * matches the preimage before the end of the file.2280 *2281 * Count the number of characters in the preimage that fall2282 * beyond the end of the file and make sure that all of them2283 * are whitespace characters. (This can only happen if2284 * we are removing blank lines at the end of the file.)2285 */2286 buf = preimage_eof = preimage->buf + preoff;2287 for ( ; i < preimage->nr; i++)2288 preoff += preimage->line[i].len;2289 preimage_end = preimage->buf + preoff;2290 for ( ; buf < preimage_end; buf++)2291 if (!isspace(*buf))2292 return 0;22932294 /*2295 * Update the preimage and the common postimage context2296 * lines to use the same whitespace as the target.2297 * If whitespace is missing in the target (i.e.2298 * if the preimage extends beyond the end of the file),2299 * use the whitespace from the preimage.2300 */2301 extra_chars = preimage_end - preimage_eof;2302 strbuf_init(&fixed, imgoff + extra_chars);2303 strbuf_add(&fixed, img->buf + try, imgoff);2304 strbuf_add(&fixed, preimage_eof, extra_chars);2305 fixed_buf = strbuf_detach(&fixed, &fixed_len);2306 update_pre_post_images(preimage, postimage,2307 fixed_buf, fixed_len, postlen);2308 return 1;2309}23102311static int match_fragment(struct image *img,2312 struct image *preimage,2313 struct image *postimage,2314 unsigned long try,2315 int try_lno,2316 unsigned ws_rule,2317 int match_beginning, int match_end)2318{2319 int i;2320 char *fixed_buf, *buf, *orig, *target;2321 struct strbuf fixed;2322 size_t fixed_len, postlen;2323 int preimage_limit;23242325 if (preimage->nr + try_lno <= img->nr) {2326 /*2327 * The hunk falls within the boundaries of img.2328 */2329 preimage_limit = preimage->nr;2330 if (match_end && (preimage->nr + try_lno != img->nr))2331 return 0;2332 } else if (ws_error_action == correct_ws_error &&2333 (ws_rule & WS_BLANK_AT_EOF)) {2334 /*2335 * This hunk extends beyond the end of img, and we are2336 * removing blank lines at the end of the file. This2337 * many lines from the beginning of the preimage must2338 * match with img, and the remainder of the preimage2339 * must be blank.2340 */2341 preimage_limit = img->nr - try_lno;2342 } else {2343 /*2344 * The hunk extends beyond the end of the img and2345 * we are not removing blanks at the end, so we2346 * should reject the hunk at this position.2347 */2348 return 0;2349 }23502351 if (match_beginning && try_lno)2352 return 0;23532354 /* Quick hash check */2355 for (i = 0; i < preimage_limit; i++)2356 if ((img->line[try_lno + i].flag & LINE_PATCHED) ||2357 (preimage->line[i].hash != img->line[try_lno + i].hash))2358 return 0;23592360 if (preimage_limit == preimage->nr) {2361 /*2362 * Do we have an exact match? If we were told to match2363 * at the end, size must be exactly at try+fragsize,2364 * otherwise try+fragsize must be still within the preimage,2365 * and either case, the old piece should match the preimage2366 * exactly.2367 */2368 if ((match_end2369 ? (try + preimage->len == img->len)2370 : (try + preimage->len <= img->len)) &&2371 !memcmp(img->buf + try, preimage->buf, preimage->len))2372 return 1;2373 } else {2374 /*2375 * The preimage extends beyond the end of img, so2376 * there cannot be an exact match.2377 *2378 * There must be one non-blank context line that match2379 * a line before the end of img.2380 */2381 char *buf_end;23822383 buf = preimage->buf;2384 buf_end = buf;2385 for (i = 0; i < preimage_limit; i++)2386 buf_end += preimage->line[i].len;23872388 for ( ; buf < buf_end; buf++)2389 if (!isspace(*buf))2390 break;2391 if (buf == buf_end)2392 return 0;2393 }23942395 /*2396 * No exact match. If we are ignoring whitespace, run a line-by-line2397 * fuzzy matching. We collect all the line length information because2398 * we need it to adjust whitespace if we match.2399 */2400 if (ws_ignore_action == ignore_ws_change)2401 return line_by_line_fuzzy_match(img, preimage, postimage,2402 try, try_lno, preimage_limit);24032404 if (ws_error_action != correct_ws_error)2405 return 0;24062407 /*2408 * The hunk does not apply byte-by-byte, but the hash says2409 * it might with whitespace fuzz. We weren't asked to2410 * ignore whitespace, we were asked to correct whitespace2411 * errors, so let's try matching after whitespace correction.2412 *2413 * While checking the preimage against the target, whitespace2414 * errors in both fixed, we count how large the corresponding2415 * postimage needs to be. The postimage prepared by2416 * apply_one_fragment() has whitespace errors fixed on added2417 * lines already, but the common lines were propagated as-is,2418 * which may become longer when their whitespace errors are2419 * fixed.2420 */24212422 /* First count added lines in postimage */2423 postlen = 0;2424 for (i = 0; i < postimage->nr; i++) {2425 if (!(postimage->line[i].flag & LINE_COMMON))2426 postlen += postimage->line[i].len;2427 }24282429 /*2430 * The preimage may extend beyond the end of the file,2431 * but in this loop we will only handle the part of the2432 * preimage that falls within the file.2433 */2434 strbuf_init(&fixed, preimage->len + 1);2435 orig = preimage->buf;2436 target = img->buf + try;2437 for (i = 0; i < preimage_limit; i++) {2438 size_t oldlen = preimage->line[i].len;2439 size_t tgtlen = img->line[try_lno + i].len;2440 size_t fixstart = fixed.len;2441 struct strbuf tgtfix;2442 int match;24432444 /* Try fixing the line in the preimage */2445 ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);24462447 /* Try fixing the line in the target */2448 strbuf_init(&tgtfix, tgtlen);2449 ws_fix_copy(&tgtfix, target, tgtlen, ws_rule, NULL);24502451 /*2452 * If they match, either the preimage was based on2453 * a version before our tree fixed whitespace breakage,2454 * or we are lacking a whitespace-fix patch the tree2455 * the preimage was based on already had (i.e. target2456 * has whitespace breakage, the preimage doesn't).2457 * In either case, we are fixing the whitespace breakages2458 * so we might as well take the fix together with their2459 * real change.2460 */2461 match = (tgtfix.len == fixed.len - fixstart &&2462 !memcmp(tgtfix.buf, fixed.buf + fixstart,2463 fixed.len - fixstart));24642465 /* Add the length if this is common with the postimage */2466 if (preimage->line[i].flag & LINE_COMMON)2467 postlen += tgtfix.len;24682469 strbuf_release(&tgtfix);2470 if (!match)2471 goto unmatch_exit;24722473 orig += oldlen;2474 target += tgtlen;2475 }247624772478 /*2479 * Now handle the lines in the preimage that falls beyond the2480 * end of the file (if any). They will only match if they are2481 * empty or only contain whitespace (if WS_BLANK_AT_EOL is2482 * false).2483 */2484 for ( ; i < preimage->nr; i++) {2485 size_t fixstart = fixed.len; /* start of the fixed preimage */2486 size_t oldlen = preimage->line[i].len;2487 int j;24882489 /* Try fixing the line in the preimage */2490 ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);24912492 for (j = fixstart; j < fixed.len; j++)2493 if (!isspace(fixed.buf[j]))2494 goto unmatch_exit;24952496 orig += oldlen;2497 }24982499 /*2500 * Yes, the preimage is based on an older version that still2501 * has whitespace breakages unfixed, and fixing them makes the2502 * hunk match. Update the context lines in the postimage.2503 */2504 fixed_buf = strbuf_detach(&fixed, &fixed_len);2505 if (postlen < postimage->len)2506 postlen = 0;2507 update_pre_post_images(preimage, postimage,2508 fixed_buf, fixed_len, postlen);2509 return 1;25102511 unmatch_exit:2512 strbuf_release(&fixed);2513 return 0;2514}25152516static int find_pos(struct image *img,2517 struct image *preimage,2518 struct image *postimage,2519 int line,2520 unsigned ws_rule,2521 int match_beginning, int match_end)2522{2523 int i;2524 unsigned long backwards, forwards, try;2525 int backwards_lno, forwards_lno, try_lno;25262527 /*2528 * If match_beginning or match_end is specified, there is no2529 * point starting from a wrong line that will never match and2530 * wander around and wait for a match at the specified end.2531 */2532 if (match_beginning)2533 line = 0;2534 else if (match_end)2535 line = img->nr - preimage->nr;25362537 /*2538 * Because the comparison is unsigned, the following test2539 * will also take care of a negative line number that can2540 * result when match_end and preimage is larger than the target.2541 */2542 if ((size_t) line > img->nr)2543 line = img->nr;25442545 try = 0;2546 for (i = 0; i < line; i++)2547 try += img->line[i].len;25482549 /*2550 * There's probably some smart way to do this, but I'll leave2551 * that to the smart and beautiful people. I'm simple and stupid.2552 */2553 backwards = try;2554 backwards_lno = line;2555 forwards = try;2556 forwards_lno = line;2557 try_lno = line;25582559 for (i = 0; ; i++) {2560 if (match_fragment(img, preimage, postimage,2561 try, try_lno, ws_rule,2562 match_beginning, match_end))2563 return try_lno;25642565 again:2566 if (backwards_lno == 0 && forwards_lno == img->nr)2567 break;25682569 if (i & 1) {2570 if (backwards_lno == 0) {2571 i++;2572 goto again;2573 }2574 backwards_lno--;2575 backwards -= img->line[backwards_lno].len;2576 try = backwards;2577 try_lno = backwards_lno;2578 } else {2579 if (forwards_lno == img->nr) {2580 i++;2581 goto again;2582 }2583 forwards += img->line[forwards_lno].len;2584 forwards_lno++;2585 try = forwards;2586 try_lno = forwards_lno;2587 }25882589 }2590 return -1;2591}25922593static void remove_first_line(struct image *img)2594{2595 img->buf += img->line[0].len;2596 img->len -= img->line[0].len;2597 img->line++;2598 img->nr--;2599}26002601static void remove_last_line(struct image *img)2602{2603 img->len -= img->line[--img->nr].len;2604}26052606/*2607 * The change from "preimage" and "postimage" has been found to2608 * apply at applied_pos (counts in line numbers) in "img".2609 * Update "img" to remove "preimage" and replace it with "postimage".2610 */2611static void update_image(struct image *img,2612 int applied_pos,2613 struct image *preimage,2614 struct image *postimage)2615{2616 /*2617 * remove the copy of preimage at offset in img2618 * and replace it with postimage2619 */2620 int i, nr;2621 size_t remove_count, insert_count, applied_at = 0;2622 char *result;2623 int preimage_limit;26242625 /*2626 * If we are removing blank lines at the end of img,2627 * the preimage may extend beyond the end.2628 * If that is the case, we must be careful only to2629 * remove the part of the preimage that falls within2630 * the boundaries of img. Initialize preimage_limit2631 * to the number of lines in the preimage that falls2632 * within the boundaries.2633 */2634 preimage_limit = preimage->nr;2635 if (preimage_limit > img->nr - applied_pos)2636 preimage_limit = img->nr - applied_pos;26372638 for (i = 0; i < applied_pos; i++)2639 applied_at += img->line[i].len;26402641 remove_count = 0;2642 for (i = 0; i < preimage_limit; i++)2643 remove_count += img->line[applied_pos + i].len;2644 insert_count = postimage->len;26452646 /* Adjust the contents */2647 result = xmalloc(st_add3(st_sub(img->len, remove_count), insert_count, 1));2648 memcpy(result, img->buf, applied_at);2649 memcpy(result + applied_at, postimage->buf, postimage->len);2650 memcpy(result + applied_at + postimage->len,2651 img->buf + (applied_at + remove_count),2652 img->len - (applied_at + remove_count));2653 free(img->buf);2654 img->buf = result;2655 img->len += insert_count - remove_count;2656 result[img->len] = '\0';26572658 /* Adjust the line table */2659 nr = img->nr + postimage->nr - preimage_limit;2660 if (preimage_limit < postimage->nr) {2661 /*2662 * NOTE: this knows that we never call remove_first_line()2663 * on anything other than pre/post image.2664 */2665 REALLOC_ARRAY(img->line, nr);2666 img->line_allocated = img->line;2667 }2668 if (preimage_limit != postimage->nr)2669 memmove(img->line + applied_pos + postimage->nr,2670 img->line + applied_pos + preimage_limit,2671 (img->nr - (applied_pos + preimage_limit)) *2672 sizeof(*img->line));2673 memcpy(img->line + applied_pos,2674 postimage->line,2675 postimage->nr * sizeof(*img->line));2676 if (!allow_overlap)2677 for (i = 0; i < postimage->nr; i++)2678 img->line[applied_pos + i].flag |= LINE_PATCHED;2679 img->nr = nr;2680}26812682/*2683 * Use the patch-hunk text in "frag" to prepare two images (preimage and2684 * postimage) for the hunk. Find lines that match "preimage" in "img" and2685 * replace the part of "img" with "postimage" text.2686 */2687static int apply_one_fragment(struct image *img, struct fragment *frag,2688 int inaccurate_eof, unsigned ws_rule,2689 int nth_fragment)2690{2691 int match_beginning, match_end;2692 const char *patch = frag->patch;2693 int size = frag->size;2694 char *old, *oldlines;2695 struct strbuf newlines;2696 int new_blank_lines_at_end = 0;2697 int found_new_blank_lines_at_end = 0;2698 int hunk_linenr = frag->linenr;2699 unsigned long leading, trailing;2700 int pos, applied_pos;2701 struct image preimage;2702 struct image postimage;27032704 memset(&preimage, 0, sizeof(preimage));2705 memset(&postimage, 0, sizeof(postimage));2706 oldlines = xmalloc(size);2707 strbuf_init(&newlines, size);27082709 old = oldlines;2710 while (size > 0) {2711 char first;2712 int len = linelen(patch, size);2713 int plen;2714 int added_blank_line = 0;2715 int is_blank_context = 0;2716 size_t start;27172718 if (!len)2719 break;27202721 /*2722 * "plen" is how much of the line we should use for2723 * the actual patch data. Normally we just remove the2724 * first character on the line, but if the line is2725 * followed by "\ No newline", then we also remove the2726 * last one (which is the newline, of course).2727 */2728 plen = len - 1;2729 if (len < size && patch[len] == '\\')2730 plen--;2731 first = *patch;2732 if (apply_in_reverse) {2733 if (first == '-')2734 first = '+';2735 else if (first == '+')2736 first = '-';2737 }27382739 switch (first) {2740 case '\n':2741 /* Newer GNU diff, empty context line */2742 if (plen < 0)2743 /* ... followed by '\No newline'; nothing */2744 break;2745 *old++ = '\n';2746 strbuf_addch(&newlines, '\n');2747 add_line_info(&preimage, "\n", 1, LINE_COMMON);2748 add_line_info(&postimage, "\n", 1, LINE_COMMON);2749 is_blank_context = 1;2750 break;2751 case ' ':2752 if (plen && (ws_rule & WS_BLANK_AT_EOF) &&2753 ws_blank_line(patch + 1, plen, ws_rule))2754 is_blank_context = 1;2755 case '-':2756 memcpy(old, patch + 1, plen);2757 add_line_info(&preimage, old, plen,2758 (first == ' ' ? LINE_COMMON : 0));2759 old += plen;2760 if (first == '-')2761 break;2762 /* Fall-through for ' ' */2763 case '+':2764 /* --no-add does not add new lines */2765 if (first == '+' && no_add)2766 break;27672768 start = newlines.len;2769 if (first != '+' ||2770 !whitespace_error ||2771 ws_error_action != correct_ws_error) {2772 strbuf_add(&newlines, patch + 1, plen);2773 }2774 else {2775 ws_fix_copy(&newlines, patch + 1, plen, ws_rule, &applied_after_fixing_ws);2776 }2777 add_line_info(&postimage, newlines.buf + start, newlines.len - start,2778 (first == '+' ? 0 : LINE_COMMON));2779 if (first == '+' &&2780 (ws_rule & WS_BLANK_AT_EOF) &&2781 ws_blank_line(patch + 1, plen, ws_rule))2782 added_blank_line = 1;2783 break;2784 case '@': case '\\':2785 /* Ignore it, we already handled it */2786 break;2787 default:2788 if (apply_verbosely)2789 error(_("invalid start of line: '%c'"), first);2790 applied_pos = -1;2791 goto out;2792 }2793 if (added_blank_line) {2794 if (!new_blank_lines_at_end)2795 found_new_blank_lines_at_end = hunk_linenr;2796 new_blank_lines_at_end++;2797 }2798 else if (is_blank_context)2799 ;2800 else2801 new_blank_lines_at_end = 0;2802 patch += len;2803 size -= len;2804 hunk_linenr++;2805 }2806 if (inaccurate_eof &&2807 old > oldlines && old[-1] == '\n' &&2808 newlines.len > 0 && newlines.buf[newlines.len - 1] == '\n') {2809 old--;2810 strbuf_setlen(&newlines, newlines.len - 1);2811 }28122813 leading = frag->leading;2814 trailing = frag->trailing;28152816 /*2817 * A hunk to change lines at the beginning would begin with2818 * @@ -1,L +N,M @@2819 * but we need to be careful. -U0 that inserts before the second2820 * line also has this pattern.2821 *2822 * And a hunk to add to an empty file would begin with2823 * @@ -0,0 +N,M @@2824 *2825 * In other words, a hunk that is (frag->oldpos <= 1) with or2826 * without leading context must match at the beginning.2827 */2828 match_beginning = (!frag->oldpos ||2829 (frag->oldpos == 1 && !unidiff_zero));28302831 /*2832 * A hunk without trailing lines must match at the end.2833 * However, we simply cannot tell if a hunk must match end2834 * from the lack of trailing lines if the patch was generated2835 * with unidiff without any context.2836 */2837 match_end = !unidiff_zero && !trailing;28382839 pos = frag->newpos ? (frag->newpos - 1) : 0;2840 preimage.buf = oldlines;2841 preimage.len = old - oldlines;2842 postimage.buf = newlines.buf;2843 postimage.len = newlines.len;2844 preimage.line = preimage.line_allocated;2845 postimage.line = postimage.line_allocated;28462847 for (;;) {28482849 applied_pos = find_pos(img, &preimage, &postimage, pos,2850 ws_rule, match_beginning, match_end);28512852 if (applied_pos >= 0)2853 break;28542855 /* Am I at my context limits? */2856 if ((leading <= p_context) && (trailing <= p_context))2857 break;2858 if (match_beginning || match_end) {2859 match_beginning = match_end = 0;2860 continue;2861 }28622863 /*2864 * Reduce the number of context lines; reduce both2865 * leading and trailing if they are equal otherwise2866 * just reduce the larger context.2867 */2868 if (leading >= trailing) {2869 remove_first_line(&preimage);2870 remove_first_line(&postimage);2871 pos--;2872 leading--;2873 }2874 if (trailing > leading) {2875 remove_last_line(&preimage);2876 remove_last_line(&postimage);2877 trailing--;2878 }2879 }28802881 if (applied_pos >= 0) {2882 if (new_blank_lines_at_end &&2883 preimage.nr + applied_pos >= img->nr &&2884 (ws_rule & WS_BLANK_AT_EOF) &&2885 ws_error_action != nowarn_ws_error) {2886 record_ws_error(WS_BLANK_AT_EOF, "+", 1,2887 found_new_blank_lines_at_end);2888 if (ws_error_action == correct_ws_error) {2889 while (new_blank_lines_at_end--)2890 remove_last_line(&postimage);2891 }2892 /*2893 * We would want to prevent write_out_results()2894 * from taking place in apply_patch() that follows2895 * the callchain led us here, which is:2896 * apply_patch->check_patch_list->check_patch->2897 * apply_data->apply_fragments->apply_one_fragment2898 */2899 if (ws_error_action == die_on_ws_error)2900 apply = 0;2901 }29022903 if (apply_verbosely && applied_pos != pos) {2904 int offset = applied_pos - pos;2905 if (apply_in_reverse)2906 offset = 0 - offset;2907 fprintf_ln(stderr,2908 Q_("Hunk #%d succeeded at %d (offset %d line).",2909 "Hunk #%d succeeded at %d (offset %d lines).",2910 offset),2911 nth_fragment, applied_pos + 1, offset);2912 }29132914 /*2915 * Warn if it was necessary to reduce the number2916 * of context lines.2917 */2918 if ((leading != frag->leading) ||2919 (trailing != frag->trailing))2920 fprintf_ln(stderr, _("Context reduced to (%ld/%ld)"2921 " to apply fragment at %d"),2922 leading, trailing, applied_pos+1);2923 update_image(img, applied_pos, &preimage, &postimage);2924 } else {2925 if (apply_verbosely)2926 error(_("while searching for:\n%.*s"),2927 (int)(old - oldlines), oldlines);2928 }29292930out:2931 free(oldlines);2932 strbuf_release(&newlines);2933 free(preimage.line_allocated);2934 free(postimage.line_allocated);29352936 return (applied_pos < 0);2937}29382939static int apply_binary_fragment(struct image *img, struct patch *patch)2940{2941 struct fragment *fragment = patch->fragments;2942 unsigned long len;2943 void *dst;29442945 if (!fragment)2946 return error(_("missing binary patch data for '%s'"),2947 patch->new_name ?2948 patch->new_name :2949 patch->old_name);29502951 /* Binary patch is irreversible without the optional second hunk */2952 if (apply_in_reverse) {2953 if (!fragment->next)2954 return error("cannot reverse-apply a binary patch "2955 "without the reverse hunk to '%s'",2956 patch->new_name2957 ? patch->new_name : patch->old_name);2958 fragment = fragment->next;2959 }2960 switch (fragment->binary_patch_method) {2961 case BINARY_DELTA_DEFLATED:2962 dst = patch_delta(img->buf, img->len, fragment->patch,2963 fragment->size, &len);2964 if (!dst)2965 return -1;2966 clear_image(img);2967 img->buf = dst;2968 img->len = len;2969 return 0;2970 case BINARY_LITERAL_DEFLATED:2971 clear_image(img);2972 img->len = fragment->size;2973 img->buf = xmemdupz(fragment->patch, img->len);2974 return 0;2975 }2976 return -1;2977}29782979/*2980 * Replace "img" with the result of applying the binary patch.2981 * The binary patch data itself in patch->fragment is still kept2982 * but the preimage prepared by the caller in "img" is freed here2983 * or in the helper function apply_binary_fragment() this calls.2984 */2985static int apply_binary(struct image *img, struct patch *patch)2986{2987 const char *name = patch->old_name ? patch->old_name : patch->new_name;2988 unsigned char sha1[20];29892990 /*2991 * For safety, we require patch index line to contain2992 * full 40-byte textual SHA1 for old and new, at least for now.2993 */2994 if (strlen(patch->old_sha1_prefix) != 40 ||2995 strlen(patch->new_sha1_prefix) != 40 ||2996 get_sha1_hex(patch->old_sha1_prefix, sha1) ||2997 get_sha1_hex(patch->new_sha1_prefix, sha1))2998 return error("cannot apply binary patch to '%s' "2999 "without full index line", name);30003001 if (patch->old_name) {3002 /*3003 * See if the old one matches what the patch3004 * applies to.3005 */3006 hash_sha1_file(img->buf, img->len, blob_type, sha1);3007 if (strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))3008 return error("the patch applies to '%s' (%s), "3009 "which does not match the "3010 "current contents.",3011 name, sha1_to_hex(sha1));3012 }3013 else {3014 /* Otherwise, the old one must be empty. */3015 if (img->len)3016 return error("the patch applies to an empty "3017 "'%s' but it is not empty", name);3018 }30193020 get_sha1_hex(patch->new_sha1_prefix, sha1);3021 if (is_null_sha1(sha1)) {3022 clear_image(img);3023 return 0; /* deletion patch */3024 }30253026 if (has_sha1_file(sha1)) {3027 /* We already have the postimage */3028 enum object_type type;3029 unsigned long size;3030 char *result;30313032 result = read_sha1_file(sha1, &type, &size);3033 if (!result)3034 return error("the necessary postimage %s for "3035 "'%s' cannot be read",3036 patch->new_sha1_prefix, name);3037 clear_image(img);3038 img->buf = result;3039 img->len = size;3040 } else {3041 /*3042 * We have verified buf matches the preimage;3043 * apply the patch data to it, which is stored3044 * in the patch->fragments->{patch,size}.3045 */3046 if (apply_binary_fragment(img, patch))3047 return error(_("binary patch does not apply to '%s'"),3048 name);30493050 /* verify that the result matches */3051 hash_sha1_file(img->buf, img->len, blob_type, sha1);3052 if (strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))3053 return error(_("binary patch to '%s' creates incorrect result (expecting %s, got %s)"),3054 name, patch->new_sha1_prefix, sha1_to_hex(sha1));3055 }30563057 return 0;3058}30593060static int apply_fragments(struct image *img, struct patch *patch)3061{3062 struct fragment *frag = patch->fragments;3063 const char *name = patch->old_name ? patch->old_name : patch->new_name;3064 unsigned ws_rule = patch->ws_rule;3065 unsigned inaccurate_eof = patch->inaccurate_eof;3066 int nth = 0;30673068 if (patch->is_binary)3069 return apply_binary(img, patch);30703071 while (frag) {3072 nth++;3073 if (apply_one_fragment(img, frag, inaccurate_eof, ws_rule, nth)) {3074 error(_("patch failed: %s:%ld"), name, frag->oldpos);3075 if (!apply_with_reject)3076 return -1;3077 frag->rejected = 1;3078 }3079 frag = frag->next;3080 }3081 return 0;3082}30833084static int read_blob_object(struct strbuf *buf, const unsigned char *sha1, unsigned mode)3085{3086 if (S_ISGITLINK(mode)) {3087 strbuf_grow(buf, 100);3088 strbuf_addf(buf, "Subproject commit %s\n", sha1_to_hex(sha1));3089 } else {3090 enum object_type type;3091 unsigned long sz;3092 char *result;30933094 result = read_sha1_file(sha1, &type, &sz);3095 if (!result)3096 return -1;3097 /* XXX read_sha1_file NUL-terminates */3098 strbuf_attach(buf, result, sz, sz + 1);3099 }3100 return 0;3101}31023103static int read_file_or_gitlink(const struct cache_entry *ce, struct strbuf *buf)3104{3105 if (!ce)3106 return 0;3107 return read_blob_object(buf, ce->sha1, ce->ce_mode);3108}31093110static struct patch *in_fn_table(const char *name)3111{3112 struct string_list_item *item;31133114 if (name == NULL)3115 return NULL;31163117 item = string_list_lookup(&fn_table, name);3118 if (item != NULL)3119 return (struct patch *)item->util;31203121 return NULL;3122}31233124/*3125 * item->util in the filename table records the status of the path.3126 * Usually it points at a patch (whose result records the contents3127 * of it after applying it), but it could be PATH_WAS_DELETED for a3128 * path that a previously applied patch has already removed, or3129 * PATH_TO_BE_DELETED for a path that a later patch would remove.3130 *3131 * The latter is needed to deal with a case where two paths A and B3132 * are swapped by first renaming A to B and then renaming B to A;3133 * moving A to B should not be prevented due to presence of B as we3134 * will remove it in a later patch.3135 */3136#define PATH_TO_BE_DELETED ((struct patch *) -2)3137#define PATH_WAS_DELETED ((struct patch *) -1)31383139static int to_be_deleted(struct patch *patch)3140{3141 return patch == PATH_TO_BE_DELETED;3142}31433144static int was_deleted(struct patch *patch)3145{3146 return patch == PATH_WAS_DELETED;3147}31483149static void add_to_fn_table(struct patch *patch)3150{3151 struct string_list_item *item;31523153 /*3154 * Always add new_name unless patch is a deletion3155 * This should cover the cases for normal diffs,3156 * file creations and copies3157 */3158 if (patch->new_name != NULL) {3159 item = string_list_insert(&fn_table, patch->new_name);3160 item->util = patch;3161 }31623163 /*3164 * store a failure on rename/deletion cases because3165 * later chunks shouldn't patch old names3166 */3167 if ((patch->new_name == NULL) || (patch->is_rename)) {3168 item = string_list_insert(&fn_table, patch->old_name);3169 item->util = PATH_WAS_DELETED;3170 }3171}31723173static void prepare_fn_table(struct patch *patch)3174{3175 /*3176 * store information about incoming file deletion3177 */3178 while (patch) {3179 if ((patch->new_name == NULL) || (patch->is_rename)) {3180 struct string_list_item *item;3181 item = string_list_insert(&fn_table, patch->old_name);3182 item->util = PATH_TO_BE_DELETED;3183 }3184 patch = patch->next;3185 }3186}31873188static int checkout_target(struct index_state *istate,3189 struct cache_entry *ce, struct stat *st)3190{3191 struct checkout costate;31923193 memset(&costate, 0, sizeof(costate));3194 costate.base_dir = "";3195 costate.refresh_cache = 1;3196 costate.istate = istate;3197 if (checkout_entry(ce, &costate, NULL) || lstat(ce->name, st))3198 return error(_("cannot checkout %s"), ce->name);3199 return 0;3200}32013202static struct patch *previous_patch(struct patch *patch, int *gone)3203{3204 struct patch *previous;32053206 *gone = 0;3207 if (patch->is_copy || patch->is_rename)3208 return NULL; /* "git" patches do not depend on the order */32093210 previous = in_fn_table(patch->old_name);3211 if (!previous)3212 return NULL;32133214 if (to_be_deleted(previous))3215 return NULL; /* the deletion hasn't happened yet */32163217 if (was_deleted(previous))3218 *gone = 1;32193220 return previous;3221}32223223static int verify_index_match(const struct cache_entry *ce, struct stat *st)3224{3225 if (S_ISGITLINK(ce->ce_mode)) {3226 if (!S_ISDIR(st->st_mode))3227 return -1;3228 return 0;3229 }3230 return ce_match_stat(ce, st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE);3231}32323233#define SUBMODULE_PATCH_WITHOUT_INDEX 132343235static int load_patch_target(struct strbuf *buf,3236 const struct cache_entry *ce,3237 struct stat *st,3238 const char *name,3239 unsigned expected_mode)3240{3241 if (cached || check_index) {3242 if (read_file_or_gitlink(ce, buf))3243 return error(_("read of %s failed"), name);3244 } else if (name) {3245 if (S_ISGITLINK(expected_mode)) {3246 if (ce)3247 return read_file_or_gitlink(ce, buf);3248 else3249 return SUBMODULE_PATCH_WITHOUT_INDEX;3250 } else if (has_symlink_leading_path(name, strlen(name))) {3251 return error(_("reading from '%s' beyond a symbolic link"), name);3252 } else {3253 if (read_old_data(st, name, buf))3254 return error(_("read of %s failed"), name);3255 }3256 }3257 return 0;3258}32593260/*3261 * We are about to apply "patch"; populate the "image" with the3262 * current version we have, from the working tree or from the index,3263 * depending on the situation e.g. --cached/--index. If we are3264 * applying a non-git patch that incrementally updates the tree,3265 * we read from the result of a previous diff.3266 */3267static int load_preimage(struct image *image,3268 struct patch *patch, struct stat *st,3269 const struct cache_entry *ce)3270{3271 struct strbuf buf = STRBUF_INIT;3272 size_t len;3273 char *img;3274 struct patch *previous;3275 int status;32763277 previous = previous_patch(patch, &status);3278 if (status)3279 return error(_("path %s has been renamed/deleted"),3280 patch->old_name);3281 if (previous) {3282 /* We have a patched copy in memory; use that. */3283 strbuf_add(&buf, previous->result, previous->resultsize);3284 } else {3285 status = load_patch_target(&buf, ce, st,3286 patch->old_name, patch->old_mode);3287 if (status < 0)3288 return status;3289 else if (status == SUBMODULE_PATCH_WITHOUT_INDEX) {3290 /*3291 * There is no way to apply subproject3292 * patch without looking at the index.3293 * NEEDSWORK: shouldn't this be flagged3294 * as an error???3295 */3296 free_fragment_list(patch->fragments);3297 patch->fragments = NULL;3298 } else if (status) {3299 return error(_("read of %s failed"), patch->old_name);3300 }3301 }33023303 img = strbuf_detach(&buf, &len);3304 prepare_image(image, img, len, !patch->is_binary);3305 return 0;3306}33073308static int three_way_merge(struct image *image,3309 char *path,3310 const unsigned char *base,3311 const unsigned char *ours,3312 const unsigned char *theirs)3313{3314 mmfile_t base_file, our_file, their_file;3315 mmbuffer_t result = { NULL };3316 int status;33173318 read_mmblob(&base_file, base);3319 read_mmblob(&our_file, ours);3320 read_mmblob(&their_file, theirs);3321 status = ll_merge(&result, path,3322 &base_file, "base",3323 &our_file, "ours",3324 &their_file, "theirs", NULL);3325 free(base_file.ptr);3326 free(our_file.ptr);3327 free(their_file.ptr);3328 if (status < 0 || !result.ptr) {3329 free(result.ptr);3330 return -1;3331 }3332 clear_image(image);3333 image->buf = result.ptr;3334 image->len = result.size;33353336 return status;3337}33383339/*3340 * When directly falling back to add/add three-way merge, we read from3341 * the current contents of the new_name. In no cases other than that3342 * this function will be called.3343 */3344static int load_current(struct image *image, struct patch *patch)3345{3346 struct strbuf buf = STRBUF_INIT;3347 int status, pos;3348 size_t len;3349 char *img;3350 struct stat st;3351 struct cache_entry *ce;3352 char *name = patch->new_name;3353 unsigned mode = patch->new_mode;33543355 if (!patch->is_new)3356 die("BUG: patch to %s is not a creation", patch->old_name);33573358 pos = cache_name_pos(name, strlen(name));3359 if (pos < 0)3360 return error(_("%s: does not exist in index"), name);3361 ce = active_cache[pos];3362 if (lstat(name, &st)) {3363 if (errno != ENOENT)3364 return error(_("%s: %s"), name, strerror(errno));3365 if (checkout_target(&the_index, ce, &st))3366 return -1;3367 }3368 if (verify_index_match(ce, &st))3369 return error(_("%s: does not match index"), name);33703371 status = load_patch_target(&buf, ce, &st, name, mode);3372 if (status < 0)3373 return status;3374 else if (status)3375 return -1;3376 img = strbuf_detach(&buf, &len);3377 prepare_image(image, img, len, !patch->is_binary);3378 return 0;3379}33803381static int try_threeway(struct image *image, struct patch *patch,3382 struct stat *st, const struct cache_entry *ce)3383{3384 unsigned char pre_sha1[20], post_sha1[20], our_sha1[20];3385 struct strbuf buf = STRBUF_INIT;3386 size_t len;3387 int status;3388 char *img;3389 struct image tmp_image;33903391 /* No point falling back to 3-way merge in these cases */3392 if (patch->is_delete ||3393 S_ISGITLINK(patch->old_mode) || S_ISGITLINK(patch->new_mode))3394 return -1;33953396 /* Preimage the patch was prepared for */3397 if (patch->is_new)3398 write_sha1_file("", 0, blob_type, pre_sha1);3399 else if (get_sha1(patch->old_sha1_prefix, pre_sha1) ||3400 read_blob_object(&buf, pre_sha1, patch->old_mode))3401 return error("repository lacks the necessary blob to fall back on 3-way merge.");34023403 fprintf(stderr, "Falling back to three-way merge...\n");34043405 img = strbuf_detach(&buf, &len);3406 prepare_image(&tmp_image, img, len, 1);3407 /* Apply the patch to get the post image */3408 if (apply_fragments(&tmp_image, patch) < 0) {3409 clear_image(&tmp_image);3410 return -1;3411 }3412 /* post_sha1[] is theirs */3413 write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, post_sha1);3414 clear_image(&tmp_image);34153416 /* our_sha1[] is ours */3417 if (patch->is_new) {3418 if (load_current(&tmp_image, patch))3419 return error("cannot read the current contents of '%s'",3420 patch->new_name);3421 } else {3422 if (load_preimage(&tmp_image, patch, st, ce))3423 return error("cannot read the current contents of '%s'",3424 patch->old_name);3425 }3426 write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, our_sha1);3427 clear_image(&tmp_image);34283429 /* in-core three-way merge between post and our using pre as base */3430 status = three_way_merge(image, patch->new_name,3431 pre_sha1, our_sha1, post_sha1);3432 if (status < 0) {3433 fprintf(stderr, "Failed to fall back on three-way merge...\n");3434 return status;3435 }34363437 if (status) {3438 patch->conflicted_threeway = 1;3439 if (patch->is_new)3440 oidclr(&patch->threeway_stage[0]);3441 else3442 hashcpy(patch->threeway_stage[0].hash, pre_sha1);3443 hashcpy(patch->threeway_stage[1].hash, our_sha1);3444 hashcpy(patch->threeway_stage[2].hash, post_sha1);3445 fprintf(stderr, "Applied patch to '%s' with conflicts.\n", patch->new_name);3446 } else {3447 fprintf(stderr, "Applied patch to '%s' cleanly.\n", patch->new_name);3448 }3449 return 0;3450}34513452static int apply_data(struct patch *patch, struct stat *st, const struct cache_entry *ce)3453{3454 struct image image;34553456 if (load_preimage(&image, patch, st, ce) < 0)3457 return -1;34583459 if (patch->direct_to_threeway ||3460 apply_fragments(&image, patch) < 0) {3461 /* Note: with --reject, apply_fragments() returns 0 */3462 if (!threeway || try_threeway(&image, patch, st, ce) < 0)3463 return -1;3464 }3465 patch->result = image.buf;3466 patch->resultsize = image.len;3467 add_to_fn_table(patch);3468 free(image.line_allocated);34693470 if (0 < patch->is_delete && patch->resultsize)3471 return error(_("removal patch leaves file contents"));34723473 return 0;3474}34753476/*3477 * If "patch" that we are looking at modifies or deletes what we have,3478 * we would want it not to lose any local modification we have, either3479 * in the working tree or in the index.3480 *3481 * This also decides if a non-git patch is a creation patch or a3482 * modification to an existing empty file. We do not check the state3483 * of the current tree for a creation patch in this function; the caller3484 * check_patch() separately makes sure (and errors out otherwise) that3485 * the path the patch creates does not exist in the current tree.3486 */3487static int check_preimage(struct patch *patch, struct cache_entry **ce, struct stat *st)3488{3489 const char *old_name = patch->old_name;3490 struct patch *previous = NULL;3491 int stat_ret = 0, status;3492 unsigned st_mode = 0;34933494 if (!old_name)3495 return 0;34963497 assert(patch->is_new <= 0);3498 previous = previous_patch(patch, &status);34993500 if (status)3501 return error(_("path %s has been renamed/deleted"), old_name);3502 if (previous) {3503 st_mode = previous->new_mode;3504 } else if (!cached) {3505 stat_ret = lstat(old_name, st);3506 if (stat_ret && errno != ENOENT)3507 return error(_("%s: %s"), old_name, strerror(errno));3508 }35093510 if (check_index && !previous) {3511 int pos = cache_name_pos(old_name, strlen(old_name));3512 if (pos < 0) {3513 if (patch->is_new < 0)3514 goto is_new;3515 return error(_("%s: does not exist in index"), old_name);3516 }3517 *ce = active_cache[pos];3518 if (stat_ret < 0) {3519 if (checkout_target(&the_index, *ce, st))3520 return -1;3521 }3522 if (!cached && verify_index_match(*ce, st))3523 return error(_("%s: does not match index"), old_name);3524 if (cached)3525 st_mode = (*ce)->ce_mode;3526 } else if (stat_ret < 0) {3527 if (patch->is_new < 0)3528 goto is_new;3529 return error(_("%s: %s"), old_name, strerror(errno));3530 }35313532 if (!cached && !previous)3533 st_mode = ce_mode_from_stat(*ce, st->st_mode);35343535 if (patch->is_new < 0)3536 patch->is_new = 0;3537 if (!patch->old_mode)3538 patch->old_mode = st_mode;3539 if ((st_mode ^ patch->old_mode) & S_IFMT)3540 return error(_("%s: wrong type"), old_name);3541 if (st_mode != patch->old_mode)3542 warning(_("%s has type %o, expected %o"),3543 old_name, st_mode, patch->old_mode);3544 if (!patch->new_mode && !patch->is_delete)3545 patch->new_mode = st_mode;3546 return 0;35473548 is_new:3549 patch->is_new = 1;3550 patch->is_delete = 0;3551 free(patch->old_name);3552 patch->old_name = NULL;3553 return 0;3554}355535563557#define EXISTS_IN_INDEX 13558#define EXISTS_IN_WORKTREE 235593560static int check_to_create(const char *new_name, int ok_if_exists)3561{3562 struct stat nst;35633564 if (check_index &&3565 cache_name_pos(new_name, strlen(new_name)) >= 0 &&3566 !ok_if_exists)3567 return EXISTS_IN_INDEX;3568 if (cached)3569 return 0;35703571 if (!lstat(new_name, &nst)) {3572 if (S_ISDIR(nst.st_mode) || ok_if_exists)3573 return 0;3574 /*3575 * A leading component of new_name might be a symlink3576 * that is going to be removed with this patch, but3577 * still pointing at somewhere that has the path.3578 * In such a case, path "new_name" does not exist as3579 * far as git is concerned.3580 */3581 if (has_symlink_leading_path(new_name, strlen(new_name)))3582 return 0;35833584 return EXISTS_IN_WORKTREE;3585 } else if ((errno != ENOENT) && (errno != ENOTDIR)) {3586 return error("%s: %s", new_name, strerror(errno));3587 }3588 return 0;3589}35903591/*3592 * We need to keep track of how symlinks in the preimage are3593 * manipulated by the patches. A patch to add a/b/c where a/b3594 * is a symlink should not be allowed to affect the directory3595 * the symlink points at, but if the same patch removes a/b,3596 * it is perfectly fine, as the patch removes a/b to make room3597 * to create a directory a/b so that a/b/c can be created.3598 */3599static struct string_list symlink_changes;3600#define SYMLINK_GOES_AWAY 013601#define SYMLINK_IN_RESULT 0236023603static uintptr_t register_symlink_changes(const char *path, uintptr_t what)3604{3605 struct string_list_item *ent;36063607 ent = string_list_lookup(&symlink_changes, path);3608 if (!ent) {3609 ent = string_list_insert(&symlink_changes, path);3610 ent->util = (void *)0;3611 }3612 ent->util = (void *)(what | ((uintptr_t)ent->util));3613 return (uintptr_t)ent->util;3614}36153616static uintptr_t check_symlink_changes(const char *path)3617{3618 struct string_list_item *ent;36193620 ent = string_list_lookup(&symlink_changes, path);3621 if (!ent)3622 return 0;3623 return (uintptr_t)ent->util;3624}36253626static void prepare_symlink_changes(struct patch *patch)3627{3628 for ( ; patch; patch = patch->next) {3629 if ((patch->old_name && S_ISLNK(patch->old_mode)) &&3630 (patch->is_rename || patch->is_delete))3631 /* the symlink at patch->old_name is removed */3632 register_symlink_changes(patch->old_name, SYMLINK_GOES_AWAY);36333634 if (patch->new_name && S_ISLNK(patch->new_mode))3635 /* the symlink at patch->new_name is created or remains */3636 register_symlink_changes(patch->new_name, SYMLINK_IN_RESULT);3637 }3638}36393640static int path_is_beyond_symlink_1(struct strbuf *name)3641{3642 do {3643 unsigned int change;36443645 while (--name->len && name->buf[name->len] != '/')3646 ; /* scan backwards */3647 if (!name->len)3648 break;3649 name->buf[name->len] = '\0';3650 change = check_symlink_changes(name->buf);3651 if (change & SYMLINK_IN_RESULT)3652 return 1;3653 if (change & SYMLINK_GOES_AWAY)3654 /*3655 * This cannot be "return 0", because we may3656 * see a new one created at a higher level.3657 */3658 continue;36593660 /* otherwise, check the preimage */3661 if (check_index) {3662 struct cache_entry *ce;36633664 ce = cache_file_exists(name->buf, name->len, ignore_case);3665 if (ce && S_ISLNK(ce->ce_mode))3666 return 1;3667 } else {3668 struct stat st;3669 if (!lstat(name->buf, &st) && S_ISLNK(st.st_mode))3670 return 1;3671 }3672 } while (1);3673 return 0;3674}36753676static int path_is_beyond_symlink(const char *name_)3677{3678 int ret;3679 struct strbuf name = STRBUF_INIT;36803681 assert(*name_ != '\0');3682 strbuf_addstr(&name, name_);3683 ret = path_is_beyond_symlink_1(&name);3684 strbuf_release(&name);36853686 return ret;3687}36883689static void die_on_unsafe_path(struct patch *patch)3690{3691 const char *old_name = NULL;3692 const char *new_name = NULL;3693 if (patch->is_delete)3694 old_name = patch->old_name;3695 else if (!patch->is_new && !patch->is_copy)3696 old_name = patch->old_name;3697 if (!patch->is_delete)3698 new_name = patch->new_name;36993700 if (old_name && !verify_path(old_name))3701 die(_("invalid path '%s'"), old_name);3702 if (new_name && !verify_path(new_name))3703 die(_("invalid path '%s'"), new_name);3704}37053706/*3707 * Check and apply the patch in-core; leave the result in patch->result3708 * for the caller to write it out to the final destination.3709 */3710static int check_patch(struct patch *patch)3711{3712 struct stat st;3713 const char *old_name = patch->old_name;3714 const char *new_name = patch->new_name;3715 const char *name = old_name ? old_name : new_name;3716 struct cache_entry *ce = NULL;3717 struct patch *tpatch;3718 int ok_if_exists;3719 int status;37203721 patch->rejected = 1; /* we will drop this after we succeed */37223723 status = check_preimage(patch, &ce, &st);3724 if (status)3725 return status;3726 old_name = patch->old_name;37273728 /*3729 * A type-change diff is always split into a patch to delete3730 * old, immediately followed by a patch to create new (see3731 * diff.c::run_diff()); in such a case it is Ok that the entry3732 * to be deleted by the previous patch is still in the working3733 * tree and in the index.3734 *3735 * A patch to swap-rename between A and B would first rename A3736 * to B and then rename B to A. While applying the first one,3737 * the presence of B should not stop A from getting renamed to3738 * B; ask to_be_deleted() about the later rename. Removal of3739 * B and rename from A to B is handled the same way by asking3740 * was_deleted().3741 */3742 if ((tpatch = in_fn_table(new_name)) &&3743 (was_deleted(tpatch) || to_be_deleted(tpatch)))3744 ok_if_exists = 1;3745 else3746 ok_if_exists = 0;37473748 if (new_name &&3749 ((0 < patch->is_new) || patch->is_rename || patch->is_copy)) {3750 int err = check_to_create(new_name, ok_if_exists);37513752 if (err && threeway) {3753 patch->direct_to_threeway = 1;3754 } else switch (err) {3755 case 0:3756 break; /* happy */3757 case EXISTS_IN_INDEX:3758 return error(_("%s: already exists in index"), new_name);3759 break;3760 case EXISTS_IN_WORKTREE:3761 return error(_("%s: already exists in working directory"),3762 new_name);3763 default:3764 return err;3765 }37663767 if (!patch->new_mode) {3768 if (0 < patch->is_new)3769 patch->new_mode = S_IFREG | 0644;3770 else3771 patch->new_mode = patch->old_mode;3772 }3773 }37743775 if (new_name && old_name) {3776 int same = !strcmp(old_name, new_name);3777 if (!patch->new_mode)3778 patch->new_mode = patch->old_mode;3779 if ((patch->old_mode ^ patch->new_mode) & S_IFMT) {3780 if (same)3781 return error(_("new mode (%o) of %s does not "3782 "match old mode (%o)"),3783 patch->new_mode, new_name,3784 patch->old_mode);3785 else3786 return error(_("new mode (%o) of %s does not "3787 "match old mode (%o) of %s"),3788 patch->new_mode, new_name,3789 patch->old_mode, old_name);3790 }3791 }37923793 if (!unsafe_paths)3794 die_on_unsafe_path(patch);37953796 /*3797 * An attempt to read from or delete a path that is beyond a3798 * symbolic link will be prevented by load_patch_target() that3799 * is called at the beginning of apply_data() so we do not3800 * have to worry about a patch marked with "is_delete" bit3801 * here. We however need to make sure that the patch result3802 * is not deposited to a path that is beyond a symbolic link3803 * here.3804 */3805 if (!patch->is_delete && path_is_beyond_symlink(patch->new_name))3806 return error(_("affected file '%s' is beyond a symbolic link"),3807 patch->new_name);38083809 if (apply_data(patch, &st, ce) < 0)3810 return error(_("%s: patch does not apply"), name);3811 patch->rejected = 0;3812 return 0;3813}38143815static int check_patch_list(struct patch *patch)3816{3817 int err = 0;38183819 prepare_symlink_changes(patch);3820 prepare_fn_table(patch);3821 while (patch) {3822 if (apply_verbosely)3823 say_patch_name(stderr,3824 _("Checking patch %s..."), patch);3825 err |= check_patch(patch);3826 patch = patch->next;3827 }3828 return err;3829}38303831/* This function tries to read the sha1 from the current index */3832static int get_current_sha1(const char *path, unsigned char *sha1)3833{3834 int pos;38353836 if (read_cache() < 0)3837 return -1;3838 pos = cache_name_pos(path, strlen(path));3839 if (pos < 0)3840 return -1;3841 hashcpy(sha1, active_cache[pos]->sha1);3842 return 0;3843}38443845static int preimage_sha1_in_gitlink_patch(struct patch *p, unsigned char sha1[20])3846{3847 /*3848 * A usable gitlink patch has only one fragment (hunk) that looks like:3849 * @@ -1 +1 @@3850 * -Subproject commit <old sha1>3851 * +Subproject commit <new sha1>3852 * or3853 * @@ -1 +0,0 @@3854 * -Subproject commit <old sha1>3855 * for a removal patch.3856 */3857 struct fragment *hunk = p->fragments;3858 static const char heading[] = "-Subproject commit ";3859 char *preimage;38603861 if (/* does the patch have only one hunk? */3862 hunk && !hunk->next &&3863 /* is its preimage one line? */3864 hunk->oldpos == 1 && hunk->oldlines == 1 &&3865 /* does preimage begin with the heading? */3866 (preimage = memchr(hunk->patch, '\n', hunk->size)) != NULL &&3867 starts_with(++preimage, heading) &&3868 /* does it record full SHA-1? */3869 !get_sha1_hex(preimage + sizeof(heading) - 1, sha1) &&3870 preimage[sizeof(heading) + 40 - 1] == '\n' &&3871 /* does the abbreviated name on the index line agree with it? */3872 starts_with(preimage + sizeof(heading) - 1, p->old_sha1_prefix))3873 return 0; /* it all looks fine */38743875 /* we may have full object name on the index line */3876 return get_sha1_hex(p->old_sha1_prefix, sha1);3877}38783879/* Build an index that contains the just the files needed for a 3way merge */3880static void build_fake_ancestor(struct patch *list, const char *filename)3881{3882 struct patch *patch;3883 struct index_state result = { NULL };3884 static struct lock_file lock;38853886 /* Once we start supporting the reverse patch, it may be3887 * worth showing the new sha1 prefix, but until then...3888 */3889 for (patch = list; patch; patch = patch->next) {3890 unsigned char sha1[20];3891 struct cache_entry *ce;3892 const char *name;38933894 name = patch->old_name ? patch->old_name : patch->new_name;3895 if (0 < patch->is_new)3896 continue;38973898 if (S_ISGITLINK(patch->old_mode)) {3899 if (!preimage_sha1_in_gitlink_patch(patch, sha1))3900 ; /* ok, the textual part looks sane */3901 else3902 die("sha1 information is lacking or useless for submodule %s",3903 name);3904 } else if (!get_sha1_blob(patch->old_sha1_prefix, sha1)) {3905 ; /* ok */3906 } else if (!patch->lines_added && !patch->lines_deleted) {3907 /* mode-only change: update the current */3908 if (get_current_sha1(patch->old_name, sha1))3909 die("mode change for %s, which is not "3910 "in current HEAD", name);3911 } else3912 die("sha1 information is lacking or useless "3913 "(%s).", name);39143915 ce = make_cache_entry(patch->old_mode, sha1, name, 0, 0);3916 if (!ce)3917 die(_("make_cache_entry failed for path '%s'"), name);3918 if (add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD))3919 die ("Could not add %s to temporary index", name);3920 }39213922 hold_lock_file_for_update(&lock, filename, LOCK_DIE_ON_ERROR);3923 if (write_locked_index(&result, &lock, COMMIT_LOCK))3924 die ("Could not write temporary index to %s", filename);39253926 discard_index(&result);3927}39283929static void stat_patch_list(struct patch *patch)3930{3931 int files, adds, dels;39323933 for (files = adds = dels = 0 ; patch ; patch = patch->next) {3934 files++;3935 adds += patch->lines_added;3936 dels += patch->lines_deleted;3937 show_stats(patch);3938 }39393940 print_stat_summary(stdout, files, adds, dels);3941}39423943static void numstat_patch_list(struct patch *patch)3944{3945 for ( ; patch; patch = patch->next) {3946 const char *name;3947 name = patch->new_name ? patch->new_name : patch->old_name;3948 if (patch->is_binary)3949 printf("-\t-\t");3950 else3951 printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);3952 write_name_quoted(name, stdout, line_termination);3953 }3954}39553956static void show_file_mode_name(const char *newdelete, unsigned int mode, const char *name)3957{3958 if (mode)3959 printf(" %s mode %06o %s\n", newdelete, mode, name);3960 else3961 printf(" %s %s\n", newdelete, name);3962}39633964static void show_mode_change(struct patch *p, int show_name)3965{3966 if (p->old_mode && p->new_mode && p->old_mode != p->new_mode) {3967 if (show_name)3968 printf(" mode change %06o => %06o %s\n",3969 p->old_mode, p->new_mode, p->new_name);3970 else3971 printf(" mode change %06o => %06o\n",3972 p->old_mode, p->new_mode);3973 }3974}39753976static void show_rename_copy(struct patch *p)3977{3978 const char *renamecopy = p->is_rename ? "rename" : "copy";3979 const char *old, *new;39803981 /* Find common prefix */3982 old = p->old_name;3983 new = p->new_name;3984 while (1) {3985 const char *slash_old, *slash_new;3986 slash_old = strchr(old, '/');3987 slash_new = strchr(new, '/');3988 if (!slash_old ||3989 !slash_new ||3990 slash_old - old != slash_new - new ||3991 memcmp(old, new, slash_new - new))3992 break;3993 old = slash_old + 1;3994 new = slash_new + 1;3995 }3996 /* p->old_name thru old is the common prefix, and old and new3997 * through the end of names are renames3998 */3999 if (old != p->old_name)4000 printf(" %s %.*s{%s => %s} (%d%%)\n", renamecopy,4001 (int)(old - p->old_name), p->old_name,4002 old, new, p->score);4003 else4004 printf(" %s %s => %s (%d%%)\n", renamecopy,4005 p->old_name, p->new_name, p->score);4006 show_mode_change(p, 0);4007}40084009static void summary_patch_list(struct patch *patch)4010{4011 struct patch *p;40124013 for (p = patch; p; p = p->next) {4014 if (p->is_new)4015 show_file_mode_name("create", p->new_mode, p->new_name);4016 else if (p->is_delete)4017 show_file_mode_name("delete", p->old_mode, p->old_name);4018 else {4019 if (p->is_rename || p->is_copy)4020 show_rename_copy(p);4021 else {4022 if (p->score) {4023 printf(" rewrite %s (%d%%)\n",4024 p->new_name, p->score);4025 show_mode_change(p, 0);4026 }4027 else4028 show_mode_change(p, 1);4029 }4030 }4031 }4032}40334034static void patch_stats(struct patch *patch)4035{4036 int lines = patch->lines_added + patch->lines_deleted;40374038 if (lines > max_change)4039 max_change = lines;4040 if (patch->old_name) {4041 int len = quote_c_style(patch->old_name, NULL, NULL, 0);4042 if (!len)4043 len = strlen(patch->old_name);4044 if (len > max_len)4045 max_len = len;4046 }4047 if (patch->new_name) {4048 int len = quote_c_style(patch->new_name, NULL, NULL, 0);4049 if (!len)4050 len = strlen(patch->new_name);4051 if (len > max_len)4052 max_len = len;4053 }4054}40554056static void remove_file(struct patch *patch, int rmdir_empty)4057{4058 if (update_index) {4059 if (remove_file_from_cache(patch->old_name) < 0)4060 die(_("unable to remove %s from index"), patch->old_name);4061 }4062 if (!cached) {4063 if (!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {4064 remove_path(patch->old_name);4065 }4066 }4067}40684069static void add_index_file(const char *path, unsigned mode, void *buf, unsigned long size)4070{4071 struct stat st;4072 struct cache_entry *ce;4073 int namelen = strlen(path);4074 unsigned ce_size = cache_entry_size(namelen);40754076 if (!update_index)4077 return;40784079 ce = xcalloc(1, ce_size);4080 memcpy(ce->name, path, namelen);4081 ce->ce_mode = create_ce_mode(mode);4082 ce->ce_flags = create_ce_flags(0);4083 ce->ce_namelen = namelen;4084 if (S_ISGITLINK(mode)) {4085 const char *s;40864087 if (!skip_prefix(buf, "Subproject commit ", &s) ||4088 get_sha1_hex(s, ce->sha1))4089 die(_("corrupt patch for submodule %s"), path);4090 } else {4091 if (!cached) {4092 if (lstat(path, &st) < 0)4093 die_errno(_("unable to stat newly created file '%s'"),4094 path);4095 fill_stat_cache_info(ce, &st);4096 }4097 if (write_sha1_file(buf, size, blob_type, ce->sha1) < 0)4098 die(_("unable to create backing store for newly created file %s"), path);4099 }4100 if (add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) < 0)4101 die(_("unable to add cache entry for %s"), path);4102}41034104static int try_create_file(const char *path, unsigned int mode, const char *buf, unsigned long size)4105{4106 int fd;4107 struct strbuf nbuf = STRBUF_INIT;41084109 if (S_ISGITLINK(mode)) {4110 struct stat st;4111 if (!lstat(path, &st) && S_ISDIR(st.st_mode))4112 return 0;4113 return mkdir(path, 0777);4114 }41154116 if (has_symlinks && S_ISLNK(mode))4117 /* Although buf:size is counted string, it also is NUL4118 * terminated.4119 */4120 return symlink(buf, path);41214122 fd = open(path, O_CREAT | O_EXCL | O_WRONLY, (mode & 0100) ? 0777 : 0666);4123 if (fd < 0)4124 return -1;41254126 if (convert_to_working_tree(path, buf, size, &nbuf)) {4127 size = nbuf.len;4128 buf = nbuf.buf;4129 }4130 write_or_die(fd, buf, size);4131 strbuf_release(&nbuf);41324133 if (close(fd) < 0)4134 die_errno(_("closing file '%s'"), path);4135 return 0;4136}41374138/*4139 * We optimistically assume that the directories exist,4140 * which is true 99% of the time anyway. If they don't,4141 * we create them and try again.4142 */4143static void create_one_file(char *path, unsigned mode, const char *buf, unsigned long size)4144{4145 if (cached)4146 return;4147 if (!try_create_file(path, mode, buf, size))4148 return;41494150 if (errno == ENOENT) {4151 if (safe_create_leading_directories(path))4152 return;4153 if (!try_create_file(path, mode, buf, size))4154 return;4155 }41564157 if (errno == EEXIST || errno == EACCES) {4158 /* We may be trying to create a file where a directory4159 * used to be.4160 */4161 struct stat st;4162 if (!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))4163 errno = EEXIST;4164 }41654166 if (errno == EEXIST) {4167 unsigned int nr = getpid();41684169 for (;;) {4170 char newpath[PATH_MAX];4171 mksnpath(newpath, sizeof(newpath), "%s~%u", path, nr);4172 if (!try_create_file(newpath, mode, buf, size)) {4173 if (!rename(newpath, path))4174 return;4175 unlink_or_warn(newpath);4176 break;4177 }4178 if (errno != EEXIST)4179 break;4180 ++nr;4181 }4182 }4183 die_errno(_("unable to write file '%s' mode %o"), path, mode);4184}41854186static void add_conflicted_stages_file(struct patch *patch)4187{4188 int stage, namelen;4189 unsigned ce_size, mode;4190 struct cache_entry *ce;41914192 if (!update_index)4193 return;4194 namelen = strlen(patch->new_name);4195 ce_size = cache_entry_size(namelen);4196 mode = patch->new_mode ? patch->new_mode : (S_IFREG | 0644);41974198 remove_file_from_cache(patch->new_name);4199 for (stage = 1; stage < 4; stage++) {4200 if (is_null_oid(&patch->threeway_stage[stage - 1]))4201 continue;4202 ce = xcalloc(1, ce_size);4203 memcpy(ce->name, patch->new_name, namelen);4204 ce->ce_mode = create_ce_mode(mode);4205 ce->ce_flags = create_ce_flags(stage);4206 ce->ce_namelen = namelen;4207 hashcpy(ce->sha1, patch->threeway_stage[stage - 1].hash);4208 if (add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) < 0)4209 die(_("unable to add cache entry for %s"), patch->new_name);4210 }4211}42124213static void create_file(struct patch *patch)4214{4215 char *path = patch->new_name;4216 unsigned mode = patch->new_mode;4217 unsigned long size = patch->resultsize;4218 char *buf = patch->result;42194220 if (!mode)4221 mode = S_IFREG | 0644;4222 create_one_file(path, mode, buf, size);42234224 if (patch->conflicted_threeway)4225 add_conflicted_stages_file(patch);4226 else4227 add_index_file(path, mode, buf, size);4228}42294230/* phase zero is to remove, phase one is to create */4231static void write_out_one_result(struct patch *patch, int phase)4232{4233 if (patch->is_delete > 0) {4234 if (phase == 0)4235 remove_file(patch, 1);4236 return;4237 }4238 if (patch->is_new > 0 || patch->is_copy) {4239 if (phase == 1)4240 create_file(patch);4241 return;4242 }4243 /*4244 * Rename or modification boils down to the same4245 * thing: remove the old, write the new4246 */4247 if (phase == 0)4248 remove_file(patch, patch->is_rename);4249 if (phase == 1)4250 create_file(patch);4251}42524253static int write_out_one_reject(struct patch *patch)4254{4255 FILE *rej;4256 char namebuf[PATH_MAX];4257 struct fragment *frag;4258 int cnt = 0;4259 struct strbuf sb = STRBUF_INIT;42604261 for (cnt = 0, frag = patch->fragments; frag; frag = frag->next) {4262 if (!frag->rejected)4263 continue;4264 cnt++;4265 }42664267 if (!cnt) {4268 if (apply_verbosely)4269 say_patch_name(stderr,4270 _("Applied patch %s cleanly."), patch);4271 return 0;4272 }42734274 /* This should not happen, because a removal patch that leaves4275 * contents are marked "rejected" at the patch level.4276 */4277 if (!patch->new_name)4278 die(_("internal error"));42794280 /* Say this even without --verbose */4281 strbuf_addf(&sb, Q_("Applying patch %%s with %d reject...",4282 "Applying patch %%s with %d rejects...",4283 cnt),4284 cnt);4285 say_patch_name(stderr, sb.buf, patch);4286 strbuf_release(&sb);42874288 cnt = strlen(patch->new_name);4289 if (ARRAY_SIZE(namebuf) <= cnt + 5) {4290 cnt = ARRAY_SIZE(namebuf) - 5;4291 warning(_("truncating .rej filename to %.*s.rej"),4292 cnt - 1, patch->new_name);4293 }4294 memcpy(namebuf, patch->new_name, cnt);4295 memcpy(namebuf + cnt, ".rej", 5);42964297 rej = fopen(namebuf, "w");4298 if (!rej)4299 return error(_("cannot open %s: %s"), namebuf, strerror(errno));43004301 /* Normal git tools never deal with .rej, so do not pretend4302 * this is a git patch by saying --git or giving extended4303 * headers. While at it, maybe please "kompare" that wants4304 * the trailing TAB and some garbage at the end of line ;-).4305 */4306 fprintf(rej, "diff a/%s b/%s\t(rejected hunks)\n",4307 patch->new_name, patch->new_name);4308 for (cnt = 1, frag = patch->fragments;4309 frag;4310 cnt++, frag = frag->next) {4311 if (!frag->rejected) {4312 fprintf_ln(stderr, _("Hunk #%d applied cleanly."), cnt);4313 continue;4314 }4315 fprintf_ln(stderr, _("Rejected hunk #%d."), cnt);4316 fprintf(rej, "%.*s", frag->size, frag->patch);4317 if (frag->patch[frag->size-1] != '\n')4318 fputc('\n', rej);4319 }4320 fclose(rej);4321 return -1;4322}43234324static int write_out_results(struct patch *list)4325{4326 int phase;4327 int errs = 0;4328 struct patch *l;4329 struct string_list cpath = STRING_LIST_INIT_DUP;43304331 for (phase = 0; phase < 2; phase++) {4332 l = list;4333 while (l) {4334 if (l->rejected)4335 errs = 1;4336 else {4337 write_out_one_result(l, phase);4338 if (phase == 1) {4339 if (write_out_one_reject(l))4340 errs = 1;4341 if (l->conflicted_threeway) {4342 string_list_append(&cpath, l->new_name);4343 errs = 1;4344 }4345 }4346 }4347 l = l->next;4348 }4349 }43504351 if (cpath.nr) {4352 struct string_list_item *item;43534354 string_list_sort(&cpath);4355 for_each_string_list_item(item, &cpath)4356 fprintf(stderr, "U %s\n", item->string);4357 string_list_clear(&cpath, 0);43584359 rerere(0);4360 }43614362 return errs;4363}43644365static struct lock_file lock_file;43664367#define INACCURATE_EOF (1<<0)4368#define RECOUNT (1<<1)43694370static int apply_patch(int fd, const char *filename, int options)4371{4372 size_t offset;4373 struct strbuf buf = STRBUF_INIT; /* owns the patch text */4374 struct patch *list = NULL, **listp = &list;4375 int skipped_patch = 0;43764377 patch_input_file = filename;4378 read_patch_file(&buf, fd);4379 offset = 0;4380 while (offset < buf.len) {4381 struct patch *patch;4382 int nr;43834384 patch = xcalloc(1, sizeof(*patch));4385 patch->inaccurate_eof = !!(options & INACCURATE_EOF);4386 patch->recount = !!(options & RECOUNT);4387 nr = parse_chunk(buf.buf + offset, buf.len - offset, patch);4388 if (nr < 0) {4389 free_patch(patch);4390 break;4391 }4392 if (apply_in_reverse)4393 reverse_patches(patch);4394 if (use_patch(patch)) {4395 patch_stats(patch);4396 *listp = patch;4397 listp = &patch->next;4398 }4399 else {4400 if (apply_verbosely)4401 say_patch_name(stderr, _("Skipped patch '%s'."), patch);4402 free_patch(patch);4403 skipped_patch++;4404 }4405 offset += nr;4406 }44074408 if (!list && !skipped_patch)4409 die(_("unrecognized input"));44104411 if (whitespace_error && (ws_error_action == die_on_ws_error))4412 apply = 0;44134414 update_index = check_index && apply;4415 if (update_index && newfd < 0)4416 newfd = hold_locked_index(&lock_file, 1);44174418 if (check_index) {4419 if (read_cache() < 0)4420 die(_("unable to read index file"));4421 }44224423 if ((check || apply) &&4424 check_patch_list(list) < 0 &&4425 !apply_with_reject)4426 exit(1);44274428 if (apply && write_out_results(list)) {4429 if (apply_with_reject)4430 exit(1);4431 /* with --3way, we still need to write the index out */4432 return 1;4433 }44344435 if (fake_ancestor)4436 build_fake_ancestor(list, fake_ancestor);44374438 if (diffstat)4439 stat_patch_list(list);44404441 if (numstat)4442 numstat_patch_list(list);44434444 if (summary)4445 summary_patch_list(list);44464447 free_patch_list(list);4448 strbuf_release(&buf);4449 string_list_clear(&fn_table, 0);4450 return 0;4451}44524453static void git_apply_config(void)4454{4455 git_config_get_string_const("apply.whitespace", &apply_default_whitespace);4456 git_config_get_string_const("apply.ignorewhitespace", &apply_default_ignorewhitespace);4457 git_config(git_default_config, NULL);4458}44594460static int option_parse_exclude(const struct option *opt,4461 const char *arg, int unset)4462{4463 add_name_limit(arg, 1);4464 return 0;4465}44664467static int option_parse_include(const struct option *opt,4468 const char *arg, int unset)4469{4470 add_name_limit(arg, 0);4471 has_include = 1;4472 return 0;4473}44744475static int option_parse_p(const struct option *opt,4476 const char *arg, int unset)4477{4478 state_p_value = atoi(arg);4479 p_value_known = 1;4480 return 0;4481}44824483static int option_parse_space_change(const struct option *opt,4484 const char *arg, int unset)4485{4486 if (unset)4487 ws_ignore_action = ignore_ws_none;4488 else4489 ws_ignore_action = ignore_ws_change;4490 return 0;4491}44924493static int option_parse_whitespace(const struct option *opt,4494 const char *arg, int unset)4495{4496 const char **whitespace_option = opt->value;44974498 *whitespace_option = arg;4499 parse_whitespace_option(arg);4500 return 0;4501}45024503static int option_parse_directory(const struct option *opt,4504 const char *arg, int unset)4505{4506 strbuf_reset(&root);4507 strbuf_addstr(&root, arg);4508 strbuf_complete(&root, '/');4509 return 0;4510}45114512int cmd_apply(int argc, const char **argv, const char *prefix_)4513{4514 int i;4515 int errs = 0;4516 int is_not_gitdir = !startup_info->have_repository;4517 int force_apply = 0;4518 int options = 0;4519 int read_stdin = 1;45204521 const char *whitespace_option = NULL;45224523 struct option builtin_apply_options[] = {4524 { OPTION_CALLBACK, 0, "exclude", NULL, N_("path"),4525 N_("don't apply changes matching the given path"),4526 0, option_parse_exclude },4527 { OPTION_CALLBACK, 0, "include", NULL, N_("path"),4528 N_("apply changes matching the given path"),4529 0, option_parse_include },4530 { OPTION_CALLBACK, 'p', NULL, NULL, N_("num"),4531 N_("remove <num> leading slashes from traditional diff paths"),4532 0, option_parse_p },4533 OPT_BOOL(0, "no-add", &no_add,4534 N_("ignore additions made by the patch")),4535 OPT_BOOL(0, "stat", &diffstat,4536 N_("instead of applying the patch, output diffstat for the input")),4537 OPT_NOOP_NOARG(0, "allow-binary-replacement"),4538 OPT_NOOP_NOARG(0, "binary"),4539 OPT_BOOL(0, "numstat", &numstat,4540 N_("show number of added and deleted lines in decimal notation")),4541 OPT_BOOL(0, "summary", &summary,4542 N_("instead of applying the patch, output a summary for the input")),4543 OPT_BOOL(0, "check", &check,4544 N_("instead of applying the patch, see if the patch is applicable")),4545 OPT_BOOL(0, "index", &check_index,4546 N_("make sure the patch is applicable to the current index")),4547 OPT_BOOL(0, "cached", &cached,4548 N_("apply a patch without touching the working tree")),4549 OPT_BOOL(0, "unsafe-paths", &unsafe_paths,4550 N_("accept a patch that touches outside the working area")),4551 OPT_BOOL(0, "apply", &force_apply,4552 N_("also apply the patch (use with --stat/--summary/--check)")),4553 OPT_BOOL('3', "3way", &threeway,4554 N_( "attempt three-way merge if a patch does not apply")),4555 OPT_FILENAME(0, "build-fake-ancestor", &fake_ancestor,4556 N_("build a temporary index based on embedded index information")),4557 /* Think twice before adding "--nul" synonym to this */4558 OPT_SET_INT('z', NULL, &line_termination,4559 N_("paths are separated with NUL character"), '\0'),4560 OPT_INTEGER('C', NULL, &p_context,4561 N_("ensure at least <n> lines of context match")),4562 { OPTION_CALLBACK, 0, "whitespace", &whitespace_option, N_("action"),4563 N_("detect new or modified lines that have whitespace errors"),4564 0, option_parse_whitespace },4565 { OPTION_CALLBACK, 0, "ignore-space-change", NULL, NULL,4566 N_("ignore changes in whitespace when finding context"),4567 PARSE_OPT_NOARG, option_parse_space_change },4568 { OPTION_CALLBACK, 0, "ignore-whitespace", NULL, NULL,4569 N_("ignore changes in whitespace when finding context"),4570 PARSE_OPT_NOARG, option_parse_space_change },4571 OPT_BOOL('R', "reverse", &apply_in_reverse,4572 N_("apply the patch in reverse")),4573 OPT_BOOL(0, "unidiff-zero", &unidiff_zero,4574 N_("don't expect at least one line of context")),4575 OPT_BOOL(0, "reject", &apply_with_reject,4576 N_("leave the rejected hunks in corresponding *.rej files")),4577 OPT_BOOL(0, "allow-overlap", &allow_overlap,4578 N_("allow overlapping hunks")),4579 OPT__VERBOSE(&apply_verbosely, N_("be verbose")),4580 OPT_BIT(0, "inaccurate-eof", &options,4581 N_("tolerate incorrectly detected missing new-line at the end of file"),4582 INACCURATE_EOF),4583 OPT_BIT(0, "recount", &options,4584 N_("do not trust the line counts in the hunk headers"),4585 RECOUNT),4586 { OPTION_CALLBACK, 0, "directory", NULL, N_("root"),4587 N_("prepend <root> to all filenames"),4588 0, option_parse_directory },4589 OPT_END()4590 };45914592 prefix = prefix_;4593 prefix_length = prefix ? strlen(prefix) : 0;4594 git_apply_config();4595 if (apply_default_whitespace)4596 parse_whitespace_option(apply_default_whitespace);4597 if (apply_default_ignorewhitespace)4598 parse_ignorewhitespace_option(apply_default_ignorewhitespace);45994600 argc = parse_options(argc, argv, prefix, builtin_apply_options,4601 apply_usage, 0);46024603 if (apply_with_reject && threeway)4604 die("--reject and --3way cannot be used together.");4605 if (cached && threeway)4606 die("--cached and --3way cannot be used together.");4607 if (threeway) {4608 if (is_not_gitdir)4609 die(_("--3way outside a repository"));4610 check_index = 1;4611 }4612 if (apply_with_reject)4613 apply = apply_verbosely = 1;4614 if (!force_apply && (diffstat || numstat || summary || check || fake_ancestor))4615 apply = 0;4616 if (check_index && is_not_gitdir)4617 die(_("--index outside a repository"));4618 if (cached) {4619 if (is_not_gitdir)4620 die(_("--cached outside a repository"));4621 check_index = 1;4622 }4623 if (check_index)4624 unsafe_paths = 0;46254626 for (i = 0; i < argc; i++) {4627 const char *arg = argv[i];4628 int fd;46294630 if (!strcmp(arg, "-")) {4631 errs |= apply_patch(0, "<stdin>", options);4632 read_stdin = 0;4633 continue;4634 } else if (0 < prefix_length)4635 arg = prefix_filename(prefix, prefix_length, arg);46364637 fd = open(arg, O_RDONLY);4638 if (fd < 0)4639 die_errno(_("can't open patch '%s'"), arg);4640 read_stdin = 0;4641 set_default_whitespace_mode(whitespace_option);4642 errs |= apply_patch(fd, arg, options);4643 close(fd);4644 }4645 set_default_whitespace_mode(whitespace_option);4646 if (read_stdin)4647 errs |= apply_patch(0, "<stdin>", options);4648 if (whitespace_error) {4649 if (squelch_whitespace_errors &&4650 squelch_whitespace_errors < whitespace_error) {4651 int squelched =4652 whitespace_error - squelch_whitespace_errors;4653 warning(Q_("squelched %d whitespace error",4654 "squelched %d whitespace errors",4655 squelched),4656 squelched);4657 }4658 if (ws_error_action == die_on_ws_error)4659 die(Q_("%d line adds whitespace errors.",4660 "%d lines add whitespace errors.",4661 whitespace_error),4662 whitespace_error);4663 if (applied_after_fixing_ws && apply)4664 warning("%d line%s applied after"4665 " fixing whitespace errors.",4666 applied_after_fixing_ws,4667 applied_after_fixing_ws == 1 ? "" : "s");4668 else if (whitespace_error)4669 warning(Q_("%d line adds whitespace errors.",4670 "%d lines add whitespace errors.",4671 whitespace_error),4672 whitespace_error);4673 }46744675 if (update_index) {4676 if (write_locked_index(&the_index, &lock_file, COMMIT_LOCK))4677 die(_("Unable to write new index file"));4678 }46794680 return !!errs;4681}