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 24enum ws_error_action { 25 nowarn_ws_error, 26 warn_on_ws_error, 27 die_on_ws_error, 28 correct_ws_error 29}; 30 31 32enum ws_ignore { 33 ignore_ws_none, 34 ignore_ws_change 35}; 36 37/* 38 * We need to keep track of how symlinks in the preimage are 39 * manipulated by the patches. A patch to add a/b/c where a/b 40 * is a symlink should not be allowed to affect the directory 41 * the symlink points at, but if the same patch removes a/b, 42 * it is perfectly fine, as the patch removes a/b to make room 43 * to create a directory a/b so that a/b/c can be created. 44 * 45 * See also "struct string_list symlink_changes" in "struct 46 * apply_state". 47 */ 48#define SYMLINK_GOES_AWAY 01 49#define SYMLINK_IN_RESULT 02 50 51struct apply_state { 52 const char *prefix; 53 int prefix_length; 54 55 /* 56 * Since lockfile.c keeps a linked list of all created 57 * lock_file structures, it isn't safe to free(lock_file). 58 */ 59 struct lock_file *lock_file; 60 61 /* These control what gets looked at and modified */ 62 int apply; /* this is not a dry-run */ 63 int cached; /* apply to the index only */ 64 int check; /* preimage must match working tree, don't actually apply */ 65 int check_index; /* preimage must match the indexed version */ 66 int update_index; /* check_index && apply */ 67 68 /* These control cosmetic aspect of the output */ 69 int diffstat; /* just show a diffstat, and don't actually apply */ 70 int numstat; /* just show a numeric diffstat, and don't actually apply */ 71 int summary; /* just report creation, deletion, etc, and don't actually apply */ 72 73 /* These boolean parameters control how the apply is done */ 74 int allow_overlap; 75 int apply_in_reverse; 76 int apply_with_reject; 77 int apply_verbosely; 78 int no_add; 79 int threeway; 80 int unidiff_zero; 81 int unsafe_paths; 82 83 /* Other non boolean parameters */ 84 const char *fake_ancestor; 85 const char *patch_input_file; 86 int line_termination; 87 struct strbuf root; 88 int p_value; 89 int p_value_known; 90 unsigned int p_context; 91 92 /* Exclude and include path parameters */ 93 struct string_list limit_by_name; 94 int has_include; 95 96 /* Various "current state" */ 97 int linenr; /* current line number */ 98 struct string_list symlink_changes; /* we have to track symlinks */ 99 100 /* 101 * For "diff-stat" like behaviour, we keep track of the biggest change 102 * we've seen, and the longest filename. That allows us to do simple 103 * scaling. 104 */ 105 int max_change; 106 int max_len; 107 108 /* 109 * Records filenames that have been touched, in order to handle 110 * the case where more than one patches touch the same file. 111 */ 112 struct string_list fn_table; 113 114 /* These control whitespace errors */ 115 enum ws_error_action ws_error_action; 116 enum ws_ignore ws_ignore_action; 117 const char *whitespace_option; 118 int whitespace_error; 119 int squelch_whitespace_errors; 120 int applied_after_fixing_ws; 121}; 122 123static int newfd = -1; 124 125static const char * const apply_usage[] = { 126 N_("git apply [<options>] [<patch>...]"), 127 NULL 128}; 129 130static void parse_whitespace_option(struct apply_state *state, const char *option) 131{ 132 if (!option) { 133 state->ws_error_action = warn_on_ws_error; 134 return; 135 } 136 if (!strcmp(option, "warn")) { 137 state->ws_error_action = warn_on_ws_error; 138 return; 139 } 140 if (!strcmp(option, "nowarn")) { 141 state->ws_error_action = nowarn_ws_error; 142 return; 143 } 144 if (!strcmp(option, "error")) { 145 state->ws_error_action = die_on_ws_error; 146 return; 147 } 148 if (!strcmp(option, "error-all")) { 149 state->ws_error_action = die_on_ws_error; 150 state->squelch_whitespace_errors = 0; 151 return; 152 } 153 if (!strcmp(option, "strip") || !strcmp(option, "fix")) { 154 state->ws_error_action = correct_ws_error; 155 return; 156 } 157 die(_("unrecognized whitespace option '%s'"), option); 158} 159 160static void parse_ignorewhitespace_option(struct apply_state *state, 161 const char *option) 162{ 163 if (!option || !strcmp(option, "no") || 164 !strcmp(option, "false") || !strcmp(option, "never") || 165 !strcmp(option, "none")) { 166 state->ws_ignore_action = ignore_ws_none; 167 return; 168 } 169 if (!strcmp(option, "change")) { 170 state->ws_ignore_action = ignore_ws_change; 171 return; 172 } 173 die(_("unrecognized whitespace ignore option '%s'"), option); 174} 175 176static void set_default_whitespace_mode(struct apply_state *state) 177{ 178 if (!state->whitespace_option && !apply_default_whitespace) 179 state->ws_error_action = (state->apply ? warn_on_ws_error : nowarn_ws_error); 180} 181 182/* 183 * This represents one "hunk" from a patch, starting with 184 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The 185 * patch text is pointed at by patch, and its byte length 186 * is stored in size. leading and trailing are the number 187 * of context lines. 188 */ 189struct fragment { 190 unsigned long leading, trailing; 191 unsigned long oldpos, oldlines; 192 unsigned long newpos, newlines; 193 /* 194 * 'patch' is usually borrowed from buf in apply_patch(), 195 * but some codepaths store an allocated buffer. 196 */ 197 const char *patch; 198 unsigned free_patch:1, 199 rejected:1; 200 int size; 201 int linenr; 202 struct fragment *next; 203}; 204 205/* 206 * When dealing with a binary patch, we reuse "leading" field 207 * to store the type of the binary hunk, either deflated "delta" 208 * or deflated "literal". 209 */ 210#define binary_patch_method leading 211#define BINARY_DELTA_DEFLATED 1 212#define BINARY_LITERAL_DEFLATED 2 213 214/* 215 * This represents a "patch" to a file, both metainfo changes 216 * such as creation/deletion, filemode and content changes represented 217 * as a series of fragments. 218 */ 219struct patch { 220 char *new_name, *old_name, *def_name; 221 unsigned int old_mode, new_mode; 222 int is_new, is_delete; /* -1 = unknown, 0 = false, 1 = true */ 223 int rejected; 224 unsigned ws_rule; 225 int lines_added, lines_deleted; 226 int score; 227 unsigned int is_toplevel_relative:1; 228 unsigned int inaccurate_eof:1; 229 unsigned int is_binary:1; 230 unsigned int is_copy:1; 231 unsigned int is_rename:1; 232 unsigned int recount:1; 233 unsigned int conflicted_threeway:1; 234 unsigned int direct_to_threeway:1; 235 struct fragment *fragments; 236 char *result; 237 size_t resultsize; 238 char old_sha1_prefix[41]; 239 char new_sha1_prefix[41]; 240 struct patch *next; 241 242 /* three-way fallback result */ 243 struct object_id threeway_stage[3]; 244}; 245 246static void free_fragment_list(struct fragment *list) 247{ 248 while (list) { 249 struct fragment *next = list->next; 250 if (list->free_patch) 251 free((char *)list->patch); 252 free(list); 253 list = next; 254 } 255} 256 257static void free_patch(struct patch *patch) 258{ 259 free_fragment_list(patch->fragments); 260 free(patch->def_name); 261 free(patch->old_name); 262 free(patch->new_name); 263 free(patch->result); 264 free(patch); 265} 266 267static void free_patch_list(struct patch *list) 268{ 269 while (list) { 270 struct patch *next = list->next; 271 free_patch(list); 272 list = next; 273 } 274} 275 276/* 277 * A line in a file, len-bytes long (includes the terminating LF, 278 * except for an incomplete line at the end if the file ends with 279 * one), and its contents hashes to 'hash'. 280 */ 281struct line { 282 size_t len; 283 unsigned hash : 24; 284 unsigned flag : 8; 285#define LINE_COMMON 1 286#define LINE_PATCHED 2 287}; 288 289/* 290 * This represents a "file", which is an array of "lines". 291 */ 292struct image { 293 char *buf; 294 size_t len; 295 size_t nr; 296 size_t alloc; 297 struct line *line_allocated; 298 struct line *line; 299}; 300 301static uint32_t hash_line(const char *cp, size_t len) 302{ 303 size_t i; 304 uint32_t h; 305 for (i = 0, h = 0; i < len; i++) { 306 if (!isspace(cp[i])) { 307 h = h * 3 + (cp[i] & 0xff); 308 } 309 } 310 return h; 311} 312 313/* 314 * Compare lines s1 of length n1 and s2 of length n2, ignoring 315 * whitespace difference. Returns 1 if they match, 0 otherwise 316 */ 317static int fuzzy_matchlines(const char *s1, size_t n1, 318 const char *s2, size_t n2) 319{ 320 const char *last1 = s1 + n1 - 1; 321 const char *last2 = s2 + n2 - 1; 322 int result = 0; 323 324 /* ignore line endings */ 325 while ((*last1 == '\r') || (*last1 == '\n')) 326 last1--; 327 while ((*last2 == '\r') || (*last2 == '\n')) 328 last2--; 329 330 /* skip leading whitespaces, if both begin with whitespace */ 331 if (s1 <= last1 && s2 <= last2 && isspace(*s1) && isspace(*s2)) { 332 while (isspace(*s1) && (s1 <= last1)) 333 s1++; 334 while (isspace(*s2) && (s2 <= last2)) 335 s2++; 336 } 337 /* early return if both lines are empty */ 338 if ((s1 > last1) && (s2 > last2)) 339 return 1; 340 while (!result) { 341 result = *s1++ - *s2++; 342 /* 343 * Skip whitespace inside. We check for whitespace on 344 * both buffers because we don't want "a b" to match 345 * "ab" 346 */ 347 if (isspace(*s1) && isspace(*s2)) { 348 while (isspace(*s1) && s1 <= last1) 349 s1++; 350 while (isspace(*s2) && s2 <= last2) 351 s2++; 352 } 353 /* 354 * If we reached the end on one side only, 355 * lines don't match 356 */ 357 if ( 358 ((s2 > last2) && (s1 <= last1)) || 359 ((s1 > last1) && (s2 <= last2))) 360 return 0; 361 if ((s1 > last1) && (s2 > last2)) 362 break; 363 } 364 365 return !result; 366} 367 368static void add_line_info(struct image *img, const char *bol, size_t len, unsigned flag) 369{ 370 ALLOC_GROW(img->line_allocated, img->nr + 1, img->alloc); 371 img->line_allocated[img->nr].len = len; 372 img->line_allocated[img->nr].hash = hash_line(bol, len); 373 img->line_allocated[img->nr].flag = flag; 374 img->nr++; 375} 376 377/* 378 * "buf" has the file contents to be patched (read from various sources). 379 * attach it to "image" and add line-based index to it. 380 * "image" now owns the "buf". 381 */ 382static void prepare_image(struct image *image, char *buf, size_t len, 383 int prepare_linetable) 384{ 385 const char *cp, *ep; 386 387 memset(image, 0, sizeof(*image)); 388 image->buf = buf; 389 image->len = len; 390 391 if (!prepare_linetable) 392 return; 393 394 ep = image->buf + image->len; 395 cp = image->buf; 396 while (cp < ep) { 397 const char *next; 398 for (next = cp; next < ep && *next != '\n'; next++) 399 ; 400 if (next < ep) 401 next++; 402 add_line_info(image, cp, next - cp, 0); 403 cp = next; 404 } 405 image->line = image->line_allocated; 406} 407 408static void clear_image(struct image *image) 409{ 410 free(image->buf); 411 free(image->line_allocated); 412 memset(image, 0, sizeof(*image)); 413} 414 415/* fmt must contain _one_ %s and no other substitution */ 416static void say_patch_name(FILE *output, const char *fmt, struct patch *patch) 417{ 418 struct strbuf sb = STRBUF_INIT; 419 420 if (patch->old_name && patch->new_name && 421 strcmp(patch->old_name, patch->new_name)) { 422 quote_c_style(patch->old_name, &sb, NULL, 0); 423 strbuf_addstr(&sb, " => "); 424 quote_c_style(patch->new_name, &sb, NULL, 0); 425 } else { 426 const char *n = patch->new_name; 427 if (!n) 428 n = patch->old_name; 429 quote_c_style(n, &sb, NULL, 0); 430 } 431 fprintf(output, fmt, sb.buf); 432 fputc('\n', output); 433 strbuf_release(&sb); 434} 435 436#define SLOP (16) 437 438static void read_patch_file(struct strbuf *sb, int fd) 439{ 440 if (strbuf_read(sb, fd, 0) < 0) 441 die_errno("git apply: failed to read"); 442 443 /* 444 * Make sure that we have some slop in the buffer 445 * so that we can do speculative "memcmp" etc, and 446 * see to it that it is NUL-filled. 447 */ 448 strbuf_grow(sb, SLOP); 449 memset(sb->buf + sb->len, 0, SLOP); 450} 451 452static unsigned long linelen(const char *buffer, unsigned long size) 453{ 454 unsigned long len = 0; 455 while (size--) { 456 len++; 457 if (*buffer++ == '\n') 458 break; 459 } 460 return len; 461} 462 463static int is_dev_null(const char *str) 464{ 465 return skip_prefix(str, "/dev/null", &str) && isspace(*str); 466} 467 468#define TERM_SPACE 1 469#define TERM_TAB 2 470 471static int name_terminate(const char *name, int namelen, int c, int terminate) 472{ 473 if (c == ' ' && !(terminate & TERM_SPACE)) 474 return 0; 475 if (c == '\t' && !(terminate & TERM_TAB)) 476 return 0; 477 478 return 1; 479} 480 481/* remove double slashes to make --index work with such filenames */ 482static char *squash_slash(char *name) 483{ 484 int i = 0, j = 0; 485 486 if (!name) 487 return NULL; 488 489 while (name[i]) { 490 if ((name[j++] = name[i++]) == '/') 491 while (name[i] == '/') 492 i++; 493 } 494 name[j] = '\0'; 495 return name; 496} 497 498static char *find_name_gnu(struct apply_state *state, 499 const char *line, 500 const char *def, 501 int p_value) 502{ 503 struct strbuf name = STRBUF_INIT; 504 char *cp; 505 506 /* 507 * Proposed "new-style" GNU patch/diff format; see 508 * http://marc.info/?l=git&m=112927316408690&w=2 509 */ 510 if (unquote_c_style(&name, line, NULL)) { 511 strbuf_release(&name); 512 return NULL; 513 } 514 515 for (cp = name.buf; p_value; p_value--) { 516 cp = strchr(cp, '/'); 517 if (!cp) { 518 strbuf_release(&name); 519 return NULL; 520 } 521 cp++; 522 } 523 524 strbuf_remove(&name, 0, cp - name.buf); 525 if (state->root.len) 526 strbuf_insert(&name, 0, state->root.buf, state->root.len); 527 return squash_slash(strbuf_detach(&name, NULL)); 528} 529 530static size_t sane_tz_len(const char *line, size_t len) 531{ 532 const char *tz, *p; 533 534 if (len < strlen(" +0500") || line[len-strlen(" +0500")] != ' ') 535 return 0; 536 tz = line + len - strlen(" +0500"); 537 538 if (tz[1] != '+' && tz[1] != '-') 539 return 0; 540 541 for (p = tz + 2; p != line + len; p++) 542 if (!isdigit(*p)) 543 return 0; 544 545 return line + len - tz; 546} 547 548static size_t tz_with_colon_len(const char *line, size_t len) 549{ 550 const char *tz, *p; 551 552 if (len < strlen(" +08:00") || line[len - strlen(":00")] != ':') 553 return 0; 554 tz = line + len - strlen(" +08:00"); 555 556 if (tz[0] != ' ' || (tz[1] != '+' && tz[1] != '-')) 557 return 0; 558 p = tz + 2; 559 if (!isdigit(*p++) || !isdigit(*p++) || *p++ != ':' || 560 !isdigit(*p++) || !isdigit(*p++)) 561 return 0; 562 563 return line + len - tz; 564} 565 566static size_t date_len(const char *line, size_t len) 567{ 568 const char *date, *p; 569 570 if (len < strlen("72-02-05") || line[len-strlen("-05")] != '-') 571 return 0; 572 p = date = line + len - strlen("72-02-05"); 573 574 if (!isdigit(*p++) || !isdigit(*p++) || *p++ != '-' || 575 !isdigit(*p++) || !isdigit(*p++) || *p++ != '-' || 576 !isdigit(*p++) || !isdigit(*p++)) /* Not a date. */ 577 return 0; 578 579 if (date - line >= strlen("19") && 580 isdigit(date[-1]) && isdigit(date[-2])) /* 4-digit year */ 581 date -= strlen("19"); 582 583 return line + len - date; 584} 585 586static size_t short_time_len(const char *line, size_t len) 587{ 588 const char *time, *p; 589 590 if (len < strlen(" 07:01:32") || line[len-strlen(":32")] != ':') 591 return 0; 592 p = time = line + len - strlen(" 07:01:32"); 593 594 /* Permit 1-digit hours? */ 595 if (*p++ != ' ' || 596 !isdigit(*p++) || !isdigit(*p++) || *p++ != ':' || 597 !isdigit(*p++) || !isdigit(*p++) || *p++ != ':' || 598 !isdigit(*p++) || !isdigit(*p++)) /* Not a time. */ 599 return 0; 600 601 return line + len - time; 602} 603 604static size_t fractional_time_len(const char *line, size_t len) 605{ 606 const char *p; 607 size_t n; 608 609 /* Expected format: 19:41:17.620000023 */ 610 if (!len || !isdigit(line[len - 1])) 611 return 0; 612 p = line + len - 1; 613 614 /* Fractional seconds. */ 615 while (p > line && isdigit(*p)) 616 p--; 617 if (*p != '.') 618 return 0; 619 620 /* Hours, minutes, and whole seconds. */ 621 n = short_time_len(line, p - line); 622 if (!n) 623 return 0; 624 625 return line + len - p + n; 626} 627 628static size_t trailing_spaces_len(const char *line, size_t len) 629{ 630 const char *p; 631 632 /* Expected format: ' ' x (1 or more) */ 633 if (!len || line[len - 1] != ' ') 634 return 0; 635 636 p = line + len; 637 while (p != line) { 638 p--; 639 if (*p != ' ') 640 return line + len - (p + 1); 641 } 642 643 /* All spaces! */ 644 return len; 645} 646 647static size_t diff_timestamp_len(const char *line, size_t len) 648{ 649 const char *end = line + len; 650 size_t n; 651 652 /* 653 * Posix: 2010-07-05 19:41:17 654 * GNU: 2010-07-05 19:41:17.620000023 -0500 655 */ 656 657 if (!isdigit(end[-1])) 658 return 0; 659 660 n = sane_tz_len(line, end - line); 661 if (!n) 662 n = tz_with_colon_len(line, end - line); 663 end -= n; 664 665 n = short_time_len(line, end - line); 666 if (!n) 667 n = fractional_time_len(line, end - line); 668 end -= n; 669 670 n = date_len(line, end - line); 671 if (!n) /* No date. Too bad. */ 672 return 0; 673 end -= n; 674 675 if (end == line) /* No space before date. */ 676 return 0; 677 if (end[-1] == '\t') { /* Success! */ 678 end--; 679 return line + len - end; 680 } 681 if (end[-1] != ' ') /* No space before date. */ 682 return 0; 683 684 /* Whitespace damage. */ 685 end -= trailing_spaces_len(line, end - line); 686 return line + len - end; 687} 688 689static char *find_name_common(struct apply_state *state, 690 const char *line, 691 const char *def, 692 int p_value, 693 const char *end, 694 int terminate) 695{ 696 int len; 697 const char *start = NULL; 698 699 if (p_value == 0) 700 start = line; 701 while (line != end) { 702 char c = *line; 703 704 if (!end && isspace(c)) { 705 if (c == '\n') 706 break; 707 if (name_terminate(start, line-start, c, terminate)) 708 break; 709 } 710 line++; 711 if (c == '/' && !--p_value) 712 start = line; 713 } 714 if (!start) 715 return squash_slash(xstrdup_or_null(def)); 716 len = line - start; 717 if (!len) 718 return squash_slash(xstrdup_or_null(def)); 719 720 /* 721 * Generally we prefer the shorter name, especially 722 * if the other one is just a variation of that with 723 * something else tacked on to the end (ie "file.orig" 724 * or "file~"). 725 */ 726 if (def) { 727 int deflen = strlen(def); 728 if (deflen < len && !strncmp(start, def, deflen)) 729 return squash_slash(xstrdup(def)); 730 } 731 732 if (state->root.len) { 733 char *ret = xstrfmt("%s%.*s", state->root.buf, len, start); 734 return squash_slash(ret); 735 } 736 737 return squash_slash(xmemdupz(start, len)); 738} 739 740static char *find_name(struct apply_state *state, 741 const char *line, 742 char *def, 743 int p_value, 744 int terminate) 745{ 746 if (*line == '"') { 747 char *name = find_name_gnu(state, line, def, p_value); 748 if (name) 749 return name; 750 } 751 752 return find_name_common(state, line, def, p_value, NULL, terminate); 753} 754 755static char *find_name_traditional(struct apply_state *state, 756 const char *line, 757 char *def, 758 int p_value) 759{ 760 size_t len; 761 size_t date_len; 762 763 if (*line == '"') { 764 char *name = find_name_gnu(state, line, def, p_value); 765 if (name) 766 return name; 767 } 768 769 len = strchrnul(line, '\n') - line; 770 date_len = diff_timestamp_len(line, len); 771 if (!date_len) 772 return find_name_common(state, line, def, p_value, NULL, TERM_TAB); 773 len -= date_len; 774 775 return find_name_common(state, line, def, p_value, line + len, 0); 776} 777 778static int count_slashes(const char *cp) 779{ 780 int cnt = 0; 781 char ch; 782 783 while ((ch = *cp++)) 784 if (ch == '/') 785 cnt++; 786 return cnt; 787} 788 789/* 790 * Given the string after "--- " or "+++ ", guess the appropriate 791 * p_value for the given patch. 792 */ 793static int guess_p_value(struct apply_state *state, const char *nameline) 794{ 795 char *name, *cp; 796 int val = -1; 797 798 if (is_dev_null(nameline)) 799 return -1; 800 name = find_name_traditional(state, nameline, NULL, 0); 801 if (!name) 802 return -1; 803 cp = strchr(name, '/'); 804 if (!cp) 805 val = 0; 806 else if (state->prefix) { 807 /* 808 * Does it begin with "a/$our-prefix" and such? Then this is 809 * very likely to apply to our directory. 810 */ 811 if (!strncmp(name, state->prefix, state->prefix_length)) 812 val = count_slashes(state->prefix); 813 else { 814 cp++; 815 if (!strncmp(cp, state->prefix, state->prefix_length)) 816 val = count_slashes(state->prefix) + 1; 817 } 818 } 819 free(name); 820 return val; 821} 822 823/* 824 * Does the ---/+++ line have the POSIX timestamp after the last HT? 825 * GNU diff puts epoch there to signal a creation/deletion event. Is 826 * this such a timestamp? 827 */ 828static int has_epoch_timestamp(const char *nameline) 829{ 830 /* 831 * We are only interested in epoch timestamp; any non-zero 832 * fraction cannot be one, hence "(\.0+)?" in the regexp below. 833 * For the same reason, the date must be either 1969-12-31 or 834 * 1970-01-01, and the seconds part must be "00". 835 */ 836 const char stamp_regexp[] = 837 "^(1969-12-31|1970-01-01)" 838 " " 839 "[0-2][0-9]:[0-5][0-9]:00(\\.0+)?" 840 " " 841 "([-+][0-2][0-9]:?[0-5][0-9])\n"; 842 const char *timestamp = NULL, *cp, *colon; 843 static regex_t *stamp; 844 regmatch_t m[10]; 845 int zoneoffset; 846 int hourminute; 847 int status; 848 849 for (cp = nameline; *cp != '\n'; cp++) { 850 if (*cp == '\t') 851 timestamp = cp + 1; 852 } 853 if (!timestamp) 854 return 0; 855 if (!stamp) { 856 stamp = xmalloc(sizeof(*stamp)); 857 if (regcomp(stamp, stamp_regexp, REG_EXTENDED)) { 858 warning(_("Cannot prepare timestamp regexp %s"), 859 stamp_regexp); 860 return 0; 861 } 862 } 863 864 status = regexec(stamp, timestamp, ARRAY_SIZE(m), m, 0); 865 if (status) { 866 if (status != REG_NOMATCH) 867 warning(_("regexec returned %d for input: %s"), 868 status, timestamp); 869 return 0; 870 } 871 872 zoneoffset = strtol(timestamp + m[3].rm_so + 1, (char **) &colon, 10); 873 if (*colon == ':') 874 zoneoffset = zoneoffset * 60 + strtol(colon + 1, NULL, 10); 875 else 876 zoneoffset = (zoneoffset / 100) * 60 + (zoneoffset % 100); 877 if (timestamp[m[3].rm_so] == '-') 878 zoneoffset = -zoneoffset; 879 880 /* 881 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31 882 * (west of GMT) or 1970-01-01 (east of GMT) 883 */ 884 if ((zoneoffset < 0 && memcmp(timestamp, "1969-12-31", 10)) || 885 (0 <= zoneoffset && memcmp(timestamp, "1970-01-01", 10))) 886 return 0; 887 888 hourminute = (strtol(timestamp + 11, NULL, 10) * 60 + 889 strtol(timestamp + 14, NULL, 10) - 890 zoneoffset); 891 892 return ((zoneoffset < 0 && hourminute == 1440) || 893 (0 <= zoneoffset && !hourminute)); 894} 895 896/* 897 * Get the name etc info from the ---/+++ lines of a traditional patch header 898 * 899 * FIXME! The end-of-filename heuristics are kind of screwy. For existing 900 * files, we can happily check the index for a match, but for creating a 901 * new file we should try to match whatever "patch" does. I have no idea. 902 */ 903static void parse_traditional_patch(struct apply_state *state, 904 const char *first, 905 const char *second, 906 struct patch *patch) 907{ 908 char *name; 909 910 first += 4; /* skip "--- " */ 911 second += 4; /* skip "+++ " */ 912 if (!state->p_value_known) { 913 int p, q; 914 p = guess_p_value(state, first); 915 q = guess_p_value(state, second); 916 if (p < 0) p = q; 917 if (0 <= p && p == q) { 918 state->p_value = p; 919 state->p_value_known = 1; 920 } 921 } 922 if (is_dev_null(first)) { 923 patch->is_new = 1; 924 patch->is_delete = 0; 925 name = find_name_traditional(state, second, NULL, state->p_value); 926 patch->new_name = name; 927 } else if (is_dev_null(second)) { 928 patch->is_new = 0; 929 patch->is_delete = 1; 930 name = find_name_traditional(state, first, NULL, state->p_value); 931 patch->old_name = name; 932 } else { 933 char *first_name; 934 first_name = find_name_traditional(state, first, NULL, state->p_value); 935 name = find_name_traditional(state, second, first_name, state->p_value); 936 free(first_name); 937 if (has_epoch_timestamp(first)) { 938 patch->is_new = 1; 939 patch->is_delete = 0; 940 patch->new_name = name; 941 } else if (has_epoch_timestamp(second)) { 942 patch->is_new = 0; 943 patch->is_delete = 1; 944 patch->old_name = name; 945 } else { 946 patch->old_name = name; 947 patch->new_name = xstrdup_or_null(name); 948 } 949 } 950 if (!name) 951 die(_("unable to find filename in patch at line %d"), state->linenr); 952} 953 954static int gitdiff_hdrend(struct apply_state *state, 955 const char *line, 956 struct patch *patch) 957{ 958 return -1; 959} 960 961/* 962 * We're anal about diff header consistency, to make 963 * sure that we don't end up having strange ambiguous 964 * patches floating around. 965 * 966 * As a result, gitdiff_{old|new}name() will check 967 * their names against any previous information, just 968 * to make sure.. 969 */ 970#define DIFF_OLD_NAME 0 971#define DIFF_NEW_NAME 1 972 973static void gitdiff_verify_name(struct apply_state *state, 974 const char *line, 975 int isnull, 976 char **name, 977 int side) 978{ 979 if (!*name && !isnull) { 980 *name = find_name(state, line, NULL, state->p_value, TERM_TAB); 981 return; 982 } 983 984 if (*name) { 985 int len = strlen(*name); 986 char *another; 987 if (isnull) 988 die(_("git apply: bad git-diff - expected /dev/null, got %s on line %d"), 989 *name, state->linenr); 990 another = find_name(state, line, NULL, state->p_value, TERM_TAB); 991 if (!another || memcmp(another, *name, len + 1)) 992 die((side == DIFF_NEW_NAME) ? 993 _("git apply: bad git-diff - inconsistent new filename on line %d") : 994 _("git apply: bad git-diff - inconsistent old filename on line %d"), state->linenr); 995 free(another); 996 } else { 997 /* expect "/dev/null" */ 998 if (memcmp("/dev/null", line, 9) || line[9] != '\n') 999 die(_("git apply: bad git-diff - expected /dev/null on line %d"), state->linenr);1000 }1001}10021003static int gitdiff_oldname(struct apply_state *state,1004 const char *line,1005 struct patch *patch)1006{1007 gitdiff_verify_name(state, line,1008 patch->is_new, &patch->old_name,1009 DIFF_OLD_NAME);1010 return 0;1011}10121013static int gitdiff_newname(struct apply_state *state,1014 const char *line,1015 struct patch *patch)1016{1017 gitdiff_verify_name(state, line,1018 patch->is_delete, &patch->new_name,1019 DIFF_NEW_NAME);1020 return 0;1021}10221023static int gitdiff_oldmode(struct apply_state *state,1024 const char *line,1025 struct patch *patch)1026{1027 patch->old_mode = strtoul(line, NULL, 8);1028 return 0;1029}10301031static int gitdiff_newmode(struct apply_state *state,1032 const char *line,1033 struct patch *patch)1034{1035 patch->new_mode = strtoul(line, NULL, 8);1036 return 0;1037}10381039static int gitdiff_delete(struct apply_state *state,1040 const char *line,1041 struct patch *patch)1042{1043 patch->is_delete = 1;1044 free(patch->old_name);1045 patch->old_name = xstrdup_or_null(patch->def_name);1046 return gitdiff_oldmode(state, line, patch);1047}10481049static int gitdiff_newfile(struct apply_state *state,1050 const char *line,1051 struct patch *patch)1052{1053 patch->is_new = 1;1054 free(patch->new_name);1055 patch->new_name = xstrdup_or_null(patch->def_name);1056 return gitdiff_newmode(state, line, patch);1057}10581059static int gitdiff_copysrc(struct apply_state *state,1060 const char *line,1061 struct patch *patch)1062{1063 patch->is_copy = 1;1064 free(patch->old_name);1065 patch->old_name = find_name(state, line, NULL, state->p_value ? state->p_value - 1 : 0, 0);1066 return 0;1067}10681069static int gitdiff_copydst(struct apply_state *state,1070 const char *line,1071 struct patch *patch)1072{1073 patch->is_copy = 1;1074 free(patch->new_name);1075 patch->new_name = find_name(state, line, NULL, state->p_value ? state->p_value - 1 : 0, 0);1076 return 0;1077}10781079static int gitdiff_renamesrc(struct apply_state *state,1080 const char *line,1081 struct patch *patch)1082{1083 patch->is_rename = 1;1084 free(patch->old_name);1085 patch->old_name = find_name(state, line, NULL, state->p_value ? state->p_value - 1 : 0, 0);1086 return 0;1087}10881089static int gitdiff_renamedst(struct apply_state *state,1090 const char *line,1091 struct patch *patch)1092{1093 patch->is_rename = 1;1094 free(patch->new_name);1095 patch->new_name = find_name(state, line, NULL, state->p_value ? state->p_value - 1 : 0, 0);1096 return 0;1097}10981099static int gitdiff_similarity(struct apply_state *state,1100 const char *line,1101 struct patch *patch)1102{1103 unsigned long val = strtoul(line, NULL, 10);1104 if (val <= 100)1105 patch->score = val;1106 return 0;1107}11081109static int gitdiff_dissimilarity(struct apply_state *state,1110 const char *line,1111 struct patch *patch)1112{1113 unsigned long val = strtoul(line, NULL, 10);1114 if (val <= 100)1115 patch->score = val;1116 return 0;1117}11181119static int gitdiff_index(struct apply_state *state,1120 const char *line,1121 struct patch *patch)1122{1123 /*1124 * index line is N hexadecimal, "..", N hexadecimal,1125 * and optional space with octal mode.1126 */1127 const char *ptr, *eol;1128 int len;11291130 ptr = strchr(line, '.');1131 if (!ptr || ptr[1] != '.' || 40 < ptr - line)1132 return 0;1133 len = ptr - line;1134 memcpy(patch->old_sha1_prefix, line, len);1135 patch->old_sha1_prefix[len] = 0;11361137 line = ptr + 2;1138 ptr = strchr(line, ' ');1139 eol = strchrnul(line, '\n');11401141 if (!ptr || eol < ptr)1142 ptr = eol;1143 len = ptr - line;11441145 if (40 < len)1146 return 0;1147 memcpy(patch->new_sha1_prefix, line, len);1148 patch->new_sha1_prefix[len] = 0;1149 if (*ptr == ' ')1150 patch->old_mode = strtoul(ptr+1, NULL, 8);1151 return 0;1152}11531154/*1155 * This is normal for a diff that doesn't change anything: we'll fall through1156 * into the next diff. Tell the parser to break out.1157 */1158static int gitdiff_unrecognized(struct apply_state *state,1159 const char *line,1160 struct patch *patch)1161{1162 return -1;1163}11641165/*1166 * Skip p_value leading components from "line"; as we do not accept1167 * absolute paths, return NULL in that case.1168 */1169static const char *skip_tree_prefix(struct apply_state *state,1170 const char *line,1171 int llen)1172{1173 int nslash;1174 int i;11751176 if (!state->p_value)1177 return (llen && line[0] == '/') ? NULL : line;11781179 nslash = state->p_value;1180 for (i = 0; i < llen; i++) {1181 int ch = line[i];1182 if (ch == '/' && --nslash <= 0)1183 return (i == 0) ? NULL : &line[i + 1];1184 }1185 return NULL;1186}11871188/*1189 * This is to extract the same name that appears on "diff --git"1190 * line. We do not find and return anything if it is a rename1191 * patch, and it is OK because we will find the name elsewhere.1192 * We need to reliably find name only when it is mode-change only,1193 * creation or deletion of an empty file. In any of these cases,1194 * both sides are the same name under a/ and b/ respectively.1195 */1196static char *git_header_name(struct apply_state *state,1197 const char *line,1198 int llen)1199{1200 const char *name;1201 const char *second = NULL;1202 size_t len, line_len;12031204 line += strlen("diff --git ");1205 llen -= strlen("diff --git ");12061207 if (*line == '"') {1208 const char *cp;1209 struct strbuf first = STRBUF_INIT;1210 struct strbuf sp = STRBUF_INIT;12111212 if (unquote_c_style(&first, line, &second))1213 goto free_and_fail1;12141215 /* strip the a/b prefix including trailing slash */1216 cp = skip_tree_prefix(state, first.buf, first.len);1217 if (!cp)1218 goto free_and_fail1;1219 strbuf_remove(&first, 0, cp - first.buf);12201221 /*1222 * second points at one past closing dq of name.1223 * find the second name.1224 */1225 while ((second < line + llen) && isspace(*second))1226 second++;12271228 if (line + llen <= second)1229 goto free_and_fail1;1230 if (*second == '"') {1231 if (unquote_c_style(&sp, second, NULL))1232 goto free_and_fail1;1233 cp = skip_tree_prefix(state, sp.buf, sp.len);1234 if (!cp)1235 goto free_and_fail1;1236 /* They must match, otherwise ignore */1237 if (strcmp(cp, first.buf))1238 goto free_and_fail1;1239 strbuf_release(&sp);1240 return strbuf_detach(&first, NULL);1241 }12421243 /* unquoted second */1244 cp = skip_tree_prefix(state, second, line + llen - second);1245 if (!cp)1246 goto free_and_fail1;1247 if (line + llen - cp != first.len ||1248 memcmp(first.buf, cp, first.len))1249 goto free_and_fail1;1250 return strbuf_detach(&first, NULL);12511252 free_and_fail1:1253 strbuf_release(&first);1254 strbuf_release(&sp);1255 return NULL;1256 }12571258 /* unquoted first name */1259 name = skip_tree_prefix(state, line, llen);1260 if (!name)1261 return NULL;12621263 /*1264 * since the first name is unquoted, a dq if exists must be1265 * the beginning of the second name.1266 */1267 for (second = name; second < line + llen; second++) {1268 if (*second == '"') {1269 struct strbuf sp = STRBUF_INIT;1270 const char *np;12711272 if (unquote_c_style(&sp, second, NULL))1273 goto free_and_fail2;12741275 np = skip_tree_prefix(state, sp.buf, sp.len);1276 if (!np)1277 goto free_and_fail2;12781279 len = sp.buf + sp.len - np;1280 if (len < second - name &&1281 !strncmp(np, name, len) &&1282 isspace(name[len])) {1283 /* Good */1284 strbuf_remove(&sp, 0, np - sp.buf);1285 return strbuf_detach(&sp, NULL);1286 }12871288 free_and_fail2:1289 strbuf_release(&sp);1290 return NULL;1291 }1292 }12931294 /*1295 * Accept a name only if it shows up twice, exactly the same1296 * form.1297 */1298 second = strchr(name, '\n');1299 if (!second)1300 return NULL;1301 line_len = second - name;1302 for (len = 0 ; ; len++) {1303 switch (name[len]) {1304 default:1305 continue;1306 case '\n':1307 return NULL;1308 case '\t': case ' ':1309 /*1310 * Is this the separator between the preimage1311 * and the postimage pathname? Again, we are1312 * only interested in the case where there is1313 * no rename, as this is only to set def_name1314 * and a rename patch has the names elsewhere1315 * in an unambiguous form.1316 */1317 if (!name[len + 1])1318 return NULL; /* no postimage name */1319 second = skip_tree_prefix(state, name + len + 1,1320 line_len - (len + 1));1321 if (!second)1322 return NULL;1323 /*1324 * Does len bytes starting at "name" and "second"1325 * (that are separated by one HT or SP we just1326 * found) exactly match?1327 */1328 if (second[len] == '\n' && !strncmp(name, second, len))1329 return xmemdupz(name, len);1330 }1331 }1332}13331334/* Verify that we recognize the lines following a git header */1335static int parse_git_header(struct apply_state *state,1336 const char *line,1337 int len,1338 unsigned int size,1339 struct patch *patch)1340{1341 unsigned long offset;13421343 /* A git diff has explicit new/delete information, so we don't guess */1344 patch->is_new = 0;1345 patch->is_delete = 0;13461347 /*1348 * Some things may not have the old name in the1349 * rest of the headers anywhere (pure mode changes,1350 * or removing or adding empty files), so we get1351 * the default name from the header.1352 */1353 patch->def_name = git_header_name(state, line, len);1354 if (patch->def_name && state->root.len) {1355 char *s = xstrfmt("%s%s", state->root.buf, patch->def_name);1356 free(patch->def_name);1357 patch->def_name = s;1358 }13591360 line += len;1361 size -= len;1362 state->linenr++;1363 for (offset = len ; size > 0 ; offset += len, size -= len, line += len, state->linenr++) {1364 static const struct opentry {1365 const char *str;1366 int (*fn)(struct apply_state *, const char *, struct patch *);1367 } optable[] = {1368 { "@@ -", gitdiff_hdrend },1369 { "--- ", gitdiff_oldname },1370 { "+++ ", gitdiff_newname },1371 { "old mode ", gitdiff_oldmode },1372 { "new mode ", gitdiff_newmode },1373 { "deleted file mode ", gitdiff_delete },1374 { "new file mode ", gitdiff_newfile },1375 { "copy from ", gitdiff_copysrc },1376 { "copy to ", gitdiff_copydst },1377 { "rename old ", gitdiff_renamesrc },1378 { "rename new ", gitdiff_renamedst },1379 { "rename from ", gitdiff_renamesrc },1380 { "rename to ", gitdiff_renamedst },1381 { "similarity index ", gitdiff_similarity },1382 { "dissimilarity index ", gitdiff_dissimilarity },1383 { "index ", gitdiff_index },1384 { "", gitdiff_unrecognized },1385 };1386 int i;13871388 len = linelen(line, size);1389 if (!len || line[len-1] != '\n')1390 break;1391 for (i = 0; i < ARRAY_SIZE(optable); i++) {1392 const struct opentry *p = optable + i;1393 int oplen = strlen(p->str);1394 if (len < oplen || memcmp(p->str, line, oplen))1395 continue;1396 if (p->fn(state, line + oplen, patch) < 0)1397 return offset;1398 break;1399 }1400 }14011402 return offset;1403}14041405static int parse_num(const char *line, unsigned long *p)1406{1407 char *ptr;14081409 if (!isdigit(*line))1410 return 0;1411 *p = strtoul(line, &ptr, 10);1412 return ptr - line;1413}14141415static int parse_range(const char *line, int len, int offset, const char *expect,1416 unsigned long *p1, unsigned long *p2)1417{1418 int digits, ex;14191420 if (offset < 0 || offset >= len)1421 return -1;1422 line += offset;1423 len -= offset;14241425 digits = parse_num(line, p1);1426 if (!digits)1427 return -1;14281429 offset += digits;1430 line += digits;1431 len -= digits;14321433 *p2 = 1;1434 if (*line == ',') {1435 digits = parse_num(line+1, p2);1436 if (!digits)1437 return -1;14381439 offset += digits+1;1440 line += digits+1;1441 len -= digits+1;1442 }14431444 ex = strlen(expect);1445 if (ex > len)1446 return -1;1447 if (memcmp(line, expect, ex))1448 return -1;14491450 return offset + ex;1451}14521453static void recount_diff(const char *line, int size, struct fragment *fragment)1454{1455 int oldlines = 0, newlines = 0, ret = 0;14561457 if (size < 1) {1458 warning("recount: ignore empty hunk");1459 return;1460 }14611462 for (;;) {1463 int len = linelen(line, size);1464 size -= len;1465 line += len;14661467 if (size < 1)1468 break;14691470 switch (*line) {1471 case ' ': case '\n':1472 newlines++;1473 /* fall through */1474 case '-':1475 oldlines++;1476 continue;1477 case '+':1478 newlines++;1479 continue;1480 case '\\':1481 continue;1482 case '@':1483 ret = size < 3 || !starts_with(line, "@@ ");1484 break;1485 case 'd':1486 ret = size < 5 || !starts_with(line, "diff ");1487 break;1488 default:1489 ret = -1;1490 break;1491 }1492 if (ret) {1493 warning(_("recount: unexpected line: %.*s"),1494 (int)linelen(line, size), line);1495 return;1496 }1497 break;1498 }1499 fragment->oldlines = oldlines;1500 fragment->newlines = newlines;1501}15021503/*1504 * Parse a unified diff fragment header of the1505 * form "@@ -a,b +c,d @@"1506 */1507static int parse_fragment_header(const char *line, int len, struct fragment *fragment)1508{1509 int offset;15101511 if (!len || line[len-1] != '\n')1512 return -1;15131514 /* Figure out the number of lines in a fragment */1515 offset = parse_range(line, len, 4, " +", &fragment->oldpos, &fragment->oldlines);1516 offset = parse_range(line, len, offset, " @@", &fragment->newpos, &fragment->newlines);15171518 return offset;1519}15201521static int find_header(struct apply_state *state,1522 const char *line,1523 unsigned long size,1524 int *hdrsize,1525 struct patch *patch)1526{1527 unsigned long offset, len;15281529 patch->is_toplevel_relative = 0;1530 patch->is_rename = patch->is_copy = 0;1531 patch->is_new = patch->is_delete = -1;1532 patch->old_mode = patch->new_mode = 0;1533 patch->old_name = patch->new_name = NULL;1534 for (offset = 0; size > 0; offset += len, size -= len, line += len, state->linenr++) {1535 unsigned long nextlen;15361537 len = linelen(line, size);1538 if (!len)1539 break;15401541 /* Testing this early allows us to take a few shortcuts.. */1542 if (len < 6)1543 continue;15441545 /*1546 * Make sure we don't find any unconnected patch fragments.1547 * That's a sign that we didn't find a header, and that a1548 * patch has become corrupted/broken up.1549 */1550 if (!memcmp("@@ -", line, 4)) {1551 struct fragment dummy;1552 if (parse_fragment_header(line, len, &dummy) < 0)1553 continue;1554 die(_("patch fragment without header at line %d: %.*s"),1555 state->linenr, (int)len-1, line);1556 }15571558 if (size < len + 6)1559 break;15601561 /*1562 * Git patch? It might not have a real patch, just a rename1563 * or mode change, so we handle that specially1564 */1565 if (!memcmp("diff --git ", line, 11)) {1566 int git_hdr_len = parse_git_header(state, line, len, size, patch);1567 if (git_hdr_len <= len)1568 continue;1569 if (!patch->old_name && !patch->new_name) {1570 if (!patch->def_name)1571 die(Q_("git diff header lacks filename information when removing "1572 "%d leading pathname component (line %d)",1573 "git diff header lacks filename information when removing "1574 "%d leading pathname components (line %d)",1575 state->p_value),1576 state->p_value, state->linenr);1577 patch->old_name = xstrdup(patch->def_name);1578 patch->new_name = xstrdup(patch->def_name);1579 }1580 if (!patch->is_delete && !patch->new_name)1581 die("git diff header lacks filename information "1582 "(line %d)", state->linenr);1583 patch->is_toplevel_relative = 1;1584 *hdrsize = git_hdr_len;1585 return offset;1586 }15871588 /* --- followed by +++ ? */1589 if (memcmp("--- ", line, 4) || memcmp("+++ ", line + len, 4))1590 continue;15911592 /*1593 * We only accept unified patches, so we want it to1594 * at least have "@@ -a,b +c,d @@\n", which is 14 chars1595 * minimum ("@@ -0,0 +1 @@\n" is the shortest).1596 */1597 nextlen = linelen(line + len, size - len);1598 if (size < nextlen + 14 || memcmp("@@ -", line + len + nextlen, 4))1599 continue;16001601 /* Ok, we'll consider it a patch */1602 parse_traditional_patch(state, line, line+len, patch);1603 *hdrsize = len + nextlen;1604 state->linenr += 2;1605 return offset;1606 }1607 return -1;1608}16091610static void record_ws_error(struct apply_state *state,1611 unsigned result,1612 const char *line,1613 int len,1614 int linenr)1615{1616 char *err;16171618 if (!result)1619 return;16201621 state->whitespace_error++;1622 if (state->squelch_whitespace_errors &&1623 state->squelch_whitespace_errors < state->whitespace_error)1624 return;16251626 err = whitespace_error_string(result);1627 fprintf(stderr, "%s:%d: %s.\n%.*s\n",1628 state->patch_input_file, linenr, err, len, line);1629 free(err);1630}16311632static void check_whitespace(struct apply_state *state,1633 const char *line,1634 int len,1635 unsigned ws_rule)1636{1637 unsigned result = ws_check(line + 1, len - 1, ws_rule);16381639 record_ws_error(state, result, line + 1, len - 2, state->linenr);1640}16411642/*1643 * Parse a unified diff. Note that this really needs to parse each1644 * fragment separately, since the only way to know the difference1645 * between a "---" that is part of a patch, and a "---" that starts1646 * the next patch is to look at the line counts..1647 */1648static int parse_fragment(struct apply_state *state,1649 const char *line,1650 unsigned long size,1651 struct patch *patch,1652 struct fragment *fragment)1653{1654 int added, deleted;1655 int len = linelen(line, size), offset;1656 unsigned long oldlines, newlines;1657 unsigned long leading, trailing;16581659 offset = parse_fragment_header(line, len, fragment);1660 if (offset < 0)1661 return -1;1662 if (offset > 0 && patch->recount)1663 recount_diff(line + offset, size - offset, fragment);1664 oldlines = fragment->oldlines;1665 newlines = fragment->newlines;1666 leading = 0;1667 trailing = 0;16681669 /* Parse the thing.. */1670 line += len;1671 size -= len;1672 state->linenr++;1673 added = deleted = 0;1674 for (offset = len;1675 0 < size;1676 offset += len, size -= len, line += len, state->linenr++) {1677 if (!oldlines && !newlines)1678 break;1679 len = linelen(line, size);1680 if (!len || line[len-1] != '\n')1681 return -1;1682 switch (*line) {1683 default:1684 return -1;1685 case '\n': /* newer GNU diff, an empty context line */1686 case ' ':1687 oldlines--;1688 newlines--;1689 if (!deleted && !added)1690 leading++;1691 trailing++;1692 if (!state->apply_in_reverse &&1693 state->ws_error_action == correct_ws_error)1694 check_whitespace(state, line, len, patch->ws_rule);1695 break;1696 case '-':1697 if (state->apply_in_reverse &&1698 state->ws_error_action != nowarn_ws_error)1699 check_whitespace(state, line, len, patch->ws_rule);1700 deleted++;1701 oldlines--;1702 trailing = 0;1703 break;1704 case '+':1705 if (!state->apply_in_reverse &&1706 state->ws_error_action != nowarn_ws_error)1707 check_whitespace(state, line, len, patch->ws_rule);1708 added++;1709 newlines--;1710 trailing = 0;1711 break;17121713 /*1714 * We allow "\ No newline at end of file". Depending1715 * on locale settings when the patch was produced we1716 * don't know what this line looks like. The only1717 * thing we do know is that it begins with "\ ".1718 * Checking for 12 is just for sanity check -- any1719 * l10n of "\ No newline..." is at least that long.1720 */1721 case '\\':1722 if (len < 12 || memcmp(line, "\\ ", 2))1723 return -1;1724 break;1725 }1726 }1727 if (oldlines || newlines)1728 return -1;1729 if (!deleted && !added)1730 return -1;17311732 fragment->leading = leading;1733 fragment->trailing = trailing;17341735 /*1736 * If a fragment ends with an incomplete line, we failed to include1737 * it in the above loop because we hit oldlines == newlines == 01738 * before seeing it.1739 */1740 if (12 < size && !memcmp(line, "\\ ", 2))1741 offset += linelen(line, size);17421743 patch->lines_added += added;1744 patch->lines_deleted += deleted;17451746 if (0 < patch->is_new && oldlines)1747 return error(_("new file depends on old contents"));1748 if (0 < patch->is_delete && newlines)1749 return error(_("deleted file still has contents"));1750 return offset;1751}17521753/*1754 * We have seen "diff --git a/... b/..." header (or a traditional patch1755 * header). Read hunks that belong to this patch into fragments and hang1756 * them to the given patch structure.1757 *1758 * The (fragment->patch, fragment->size) pair points into the memory given1759 * by the caller, not a copy, when we return.1760 */1761static int parse_single_patch(struct apply_state *state,1762 const char *line,1763 unsigned long size,1764 struct patch *patch)1765{1766 unsigned long offset = 0;1767 unsigned long oldlines = 0, newlines = 0, context = 0;1768 struct fragment **fragp = &patch->fragments;17691770 while (size > 4 && !memcmp(line, "@@ -", 4)) {1771 struct fragment *fragment;1772 int len;17731774 fragment = xcalloc(1, sizeof(*fragment));1775 fragment->linenr = state->linenr;1776 len = parse_fragment(state, line, size, patch, fragment);1777 if (len <= 0)1778 die(_("corrupt patch at line %d"), state->linenr);1779 fragment->patch = line;1780 fragment->size = len;1781 oldlines += fragment->oldlines;1782 newlines += fragment->newlines;1783 context += fragment->leading + fragment->trailing;17841785 *fragp = fragment;1786 fragp = &fragment->next;17871788 offset += len;1789 line += len;1790 size -= len;1791 }17921793 /*1794 * If something was removed (i.e. we have old-lines) it cannot1795 * be creation, and if something was added it cannot be1796 * deletion. However, the reverse is not true; --unified=01797 * patches that only add are not necessarily creation even1798 * though they do not have any old lines, and ones that only1799 * delete are not necessarily deletion.1800 *1801 * Unfortunately, a real creation/deletion patch do _not_ have1802 * any context line by definition, so we cannot safely tell it1803 * apart with --unified=0 insanity. At least if the patch has1804 * more than one hunk it is not creation or deletion.1805 */1806 if (patch->is_new < 0 &&1807 (oldlines || (patch->fragments && patch->fragments->next)))1808 patch->is_new = 0;1809 if (patch->is_delete < 0 &&1810 (newlines || (patch->fragments && patch->fragments->next)))1811 patch->is_delete = 0;18121813 if (0 < patch->is_new && oldlines)1814 die(_("new file %s depends on old contents"), patch->new_name);1815 if (0 < patch->is_delete && newlines)1816 die(_("deleted file %s still has contents"), patch->old_name);1817 if (!patch->is_delete && !newlines && context)1818 fprintf_ln(stderr,1819 _("** warning: "1820 "file %s becomes empty but is not deleted"),1821 patch->new_name);18221823 return offset;1824}18251826static inline int metadata_changes(struct patch *patch)1827{1828 return patch->is_rename > 0 ||1829 patch->is_copy > 0 ||1830 patch->is_new > 0 ||1831 patch->is_delete ||1832 (patch->old_mode && patch->new_mode &&1833 patch->old_mode != patch->new_mode);1834}18351836static char *inflate_it(const void *data, unsigned long size,1837 unsigned long inflated_size)1838{1839 git_zstream stream;1840 void *out;1841 int st;18421843 memset(&stream, 0, sizeof(stream));18441845 stream.next_in = (unsigned char *)data;1846 stream.avail_in = size;1847 stream.next_out = out = xmalloc(inflated_size);1848 stream.avail_out = inflated_size;1849 git_inflate_init(&stream);1850 st = git_inflate(&stream, Z_FINISH);1851 git_inflate_end(&stream);1852 if ((st != Z_STREAM_END) || stream.total_out != inflated_size) {1853 free(out);1854 return NULL;1855 }1856 return out;1857}18581859/*1860 * Read a binary hunk and return a new fragment; fragment->patch1861 * points at an allocated memory that the caller must free, so1862 * it is marked as "->free_patch = 1".1863 */1864static struct fragment *parse_binary_hunk(struct apply_state *state,1865 char **buf_p,1866 unsigned long *sz_p,1867 int *status_p,1868 int *used_p)1869{1870 /*1871 * Expect a line that begins with binary patch method ("literal"1872 * or "delta"), followed by the length of data before deflating.1873 * a sequence of 'length-byte' followed by base-85 encoded data1874 * should follow, terminated by a newline.1875 *1876 * Each 5-byte sequence of base-85 encodes up to 4 bytes,1877 * and we would limit the patch line to 66 characters,1878 * so one line can fit up to 13 groups that would decode1879 * to 52 bytes max. The length byte 'A'-'Z' corresponds1880 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.1881 */1882 int llen, used;1883 unsigned long size = *sz_p;1884 char *buffer = *buf_p;1885 int patch_method;1886 unsigned long origlen;1887 char *data = NULL;1888 int hunk_size = 0;1889 struct fragment *frag;18901891 llen = linelen(buffer, size);1892 used = llen;18931894 *status_p = 0;18951896 if (starts_with(buffer, "delta ")) {1897 patch_method = BINARY_DELTA_DEFLATED;1898 origlen = strtoul(buffer + 6, NULL, 10);1899 }1900 else if (starts_with(buffer, "literal ")) {1901 patch_method = BINARY_LITERAL_DEFLATED;1902 origlen = strtoul(buffer + 8, NULL, 10);1903 }1904 else1905 return NULL;19061907 state->linenr++;1908 buffer += llen;1909 while (1) {1910 int byte_length, max_byte_length, newsize;1911 llen = linelen(buffer, size);1912 used += llen;1913 state->linenr++;1914 if (llen == 1) {1915 /* consume the blank line */1916 buffer++;1917 size--;1918 break;1919 }1920 /*1921 * Minimum line is "A00000\n" which is 7-byte long,1922 * and the line length must be multiple of 5 plus 2.1923 */1924 if ((llen < 7) || (llen-2) % 5)1925 goto corrupt;1926 max_byte_length = (llen - 2) / 5 * 4;1927 byte_length = *buffer;1928 if ('A' <= byte_length && byte_length <= 'Z')1929 byte_length = byte_length - 'A' + 1;1930 else if ('a' <= byte_length && byte_length <= 'z')1931 byte_length = byte_length - 'a' + 27;1932 else1933 goto corrupt;1934 /* if the input length was not multiple of 4, we would1935 * have filler at the end but the filler should never1936 * exceed 3 bytes1937 */1938 if (max_byte_length < byte_length ||1939 byte_length <= max_byte_length - 4)1940 goto corrupt;1941 newsize = hunk_size + byte_length;1942 data = xrealloc(data, newsize);1943 if (decode_85(data + hunk_size, buffer + 1, byte_length))1944 goto corrupt;1945 hunk_size = newsize;1946 buffer += llen;1947 size -= llen;1948 }19491950 frag = xcalloc(1, sizeof(*frag));1951 frag->patch = inflate_it(data, hunk_size, origlen);1952 frag->free_patch = 1;1953 if (!frag->patch)1954 goto corrupt;1955 free(data);1956 frag->size = origlen;1957 *buf_p = buffer;1958 *sz_p = size;1959 *used_p = used;1960 frag->binary_patch_method = patch_method;1961 return frag;19621963 corrupt:1964 free(data);1965 *status_p = -1;1966 error(_("corrupt binary patch at line %d: %.*s"),1967 state->linenr-1, llen-1, buffer);1968 return NULL;1969}19701971/*1972 * Returns:1973 * -1 in case of error,1974 * the length of the parsed binary patch otherwise1975 */1976static int parse_binary(struct apply_state *state,1977 char *buffer,1978 unsigned long size,1979 struct patch *patch)1980{1981 /*1982 * We have read "GIT binary patch\n"; what follows is a line1983 * that says the patch method (currently, either "literal" or1984 * "delta") and the length of data before deflating; a1985 * sequence of 'length-byte' followed by base-85 encoded data1986 * follows.1987 *1988 * When a binary patch is reversible, there is another binary1989 * hunk in the same format, starting with patch method (either1990 * "literal" or "delta") with the length of data, and a sequence1991 * of length-byte + base-85 encoded data, terminated with another1992 * empty line. This data, when applied to the postimage, produces1993 * the preimage.1994 */1995 struct fragment *forward;1996 struct fragment *reverse;1997 int status;1998 int used, used_1;19992000 forward = parse_binary_hunk(state, &buffer, &size, &status, &used);2001 if (!forward && !status)2002 /* there has to be one hunk (forward hunk) */2003 return error(_("unrecognized binary patch at line %d"), state->linenr-1);2004 if (status)2005 /* otherwise we already gave an error message */2006 return status;20072008 reverse = parse_binary_hunk(state, &buffer, &size, &status, &used_1);2009 if (reverse)2010 used += used_1;2011 else if (status) {2012 /*2013 * Not having reverse hunk is not an error, but having2014 * a corrupt reverse hunk is.2015 */2016 free((void*) forward->patch);2017 free(forward);2018 return status;2019 }2020 forward->next = reverse;2021 patch->fragments = forward;2022 patch->is_binary = 1;2023 return used;2024}20252026static void prefix_one(struct apply_state *state, char **name)2027{2028 char *old_name = *name;2029 if (!old_name)2030 return;2031 *name = xstrdup(prefix_filename(state->prefix, state->prefix_length, *name));2032 free(old_name);2033}20342035static void prefix_patch(struct apply_state *state, struct patch *p)2036{2037 if (!state->prefix || p->is_toplevel_relative)2038 return;2039 prefix_one(state, &p->new_name);2040 prefix_one(state, &p->old_name);2041}20422043/*2044 * include/exclude2045 */20462047static void add_name_limit(struct apply_state *state,2048 const char *name,2049 int exclude)2050{2051 struct string_list_item *it;20522053 it = string_list_append(&state->limit_by_name, name);2054 it->util = exclude ? NULL : (void *) 1;2055}20562057static int use_patch(struct apply_state *state, struct patch *p)2058{2059 const char *pathname = p->new_name ? p->new_name : p->old_name;2060 int i;20612062 /* Paths outside are not touched regardless of "--include" */2063 if (0 < state->prefix_length) {2064 int pathlen = strlen(pathname);2065 if (pathlen <= state->prefix_length ||2066 memcmp(state->prefix, pathname, state->prefix_length))2067 return 0;2068 }20692070 /* See if it matches any of exclude/include rule */2071 for (i = 0; i < state->limit_by_name.nr; i++) {2072 struct string_list_item *it = &state->limit_by_name.items[i];2073 if (!wildmatch(it->string, pathname, 0, NULL))2074 return (it->util != NULL);2075 }20762077 /*2078 * If we had any include, a path that does not match any rule is2079 * not used. Otherwise, we saw bunch of exclude rules (or none)2080 * and such a path is used.2081 */2082 return !state->has_include;2083}208420852086/*2087 * Read the patch text in "buffer" that extends for "size" bytes; stop2088 * reading after seeing a single patch (i.e. changes to a single file).2089 * Create fragments (i.e. patch hunks) and hang them to the given patch.2090 * Return the number of bytes consumed, so that the caller can call us2091 * again for the next patch.2092 */2093static int parse_chunk(struct apply_state *state, char *buffer, unsigned long size, struct patch *patch)2094{2095 int hdrsize, patchsize;2096 int offset = find_header(state, buffer, size, &hdrsize, patch);20972098 if (offset < 0)2099 return offset;21002101 prefix_patch(state, patch);21022103 if (!use_patch(state, patch))2104 patch->ws_rule = 0;2105 else2106 patch->ws_rule = whitespace_rule(patch->new_name2107 ? patch->new_name2108 : patch->old_name);21092110 patchsize = parse_single_patch(state,2111 buffer + offset + hdrsize,2112 size - offset - hdrsize,2113 patch);21142115 if (!patchsize) {2116 static const char git_binary[] = "GIT binary patch\n";2117 int hd = hdrsize + offset;2118 unsigned long llen = linelen(buffer + hd, size - hd);21192120 if (llen == sizeof(git_binary) - 1 &&2121 !memcmp(git_binary, buffer + hd, llen)) {2122 int used;2123 state->linenr++;2124 used = parse_binary(state, buffer + hd + llen,2125 size - hd - llen, patch);2126 if (used < 0)2127 return -1;2128 if (used)2129 patchsize = used + llen;2130 else2131 patchsize = 0;2132 }2133 else if (!memcmp(" differ\n", buffer + hd + llen - 8, 8)) {2134 static const char *binhdr[] = {2135 "Binary files ",2136 "Files ",2137 NULL,2138 };2139 int i;2140 for (i = 0; binhdr[i]; i++) {2141 int len = strlen(binhdr[i]);2142 if (len < size - hd &&2143 !memcmp(binhdr[i], buffer + hd, len)) {2144 state->linenr++;2145 patch->is_binary = 1;2146 patchsize = llen;2147 break;2148 }2149 }2150 }21512152 /* Empty patch cannot be applied if it is a text patch2153 * without metadata change. A binary patch appears2154 * empty to us here.2155 */2156 if ((state->apply || state->check) &&2157 (!patch->is_binary && !metadata_changes(patch)))2158 die(_("patch with only garbage at line %d"), state->linenr);2159 }21602161 return offset + hdrsize + patchsize;2162}21632164#define swap(a,b) myswap((a),(b),sizeof(a))21652166#define myswap(a, b, size) do { \2167 unsigned char mytmp[size]; \2168 memcpy(mytmp, &a, size); \2169 memcpy(&a, &b, size); \2170 memcpy(&b, mytmp, size); \2171} while (0)21722173static void reverse_patches(struct patch *p)2174{2175 for (; p; p = p->next) {2176 struct fragment *frag = p->fragments;21772178 swap(p->new_name, p->old_name);2179 swap(p->new_mode, p->old_mode);2180 swap(p->is_new, p->is_delete);2181 swap(p->lines_added, p->lines_deleted);2182 swap(p->old_sha1_prefix, p->new_sha1_prefix);21832184 for (; frag; frag = frag->next) {2185 swap(frag->newpos, frag->oldpos);2186 swap(frag->newlines, frag->oldlines);2187 }2188 }2189}21902191static const char pluses[] =2192"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";2193static const char minuses[]=2194"----------------------------------------------------------------------";21952196static void show_stats(struct apply_state *state, struct patch *patch)2197{2198 struct strbuf qname = STRBUF_INIT;2199 char *cp = patch->new_name ? patch->new_name : patch->old_name;2200 int max, add, del;22012202 quote_c_style(cp, &qname, NULL, 0);22032204 /*2205 * "scale" the filename2206 */2207 max = state->max_len;2208 if (max > 50)2209 max = 50;22102211 if (qname.len > max) {2212 cp = strchr(qname.buf + qname.len + 3 - max, '/');2213 if (!cp)2214 cp = qname.buf + qname.len + 3 - max;2215 strbuf_splice(&qname, 0, cp - qname.buf, "...", 3);2216 }22172218 if (patch->is_binary) {2219 printf(" %-*s | Bin\n", max, qname.buf);2220 strbuf_release(&qname);2221 return;2222 }22232224 printf(" %-*s |", max, qname.buf);2225 strbuf_release(&qname);22262227 /*2228 * scale the add/delete2229 */2230 max = max + state->max_change > 70 ? 70 - max : state->max_change;2231 add = patch->lines_added;2232 del = patch->lines_deleted;22332234 if (state->max_change > 0) {2235 int total = ((add + del) * max + state->max_change / 2) / state->max_change;2236 add = (add * max + state->max_change / 2) / state->max_change;2237 del = total - add;2238 }2239 printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,2240 add, pluses, del, minuses);2241}22422243static int read_old_data(struct stat *st, const char *path, struct strbuf *buf)2244{2245 switch (st->st_mode & S_IFMT) {2246 case S_IFLNK:2247 if (strbuf_readlink(buf, path, st->st_size) < 0)2248 return error(_("unable to read symlink %s"), path);2249 return 0;2250 case S_IFREG:2251 if (strbuf_read_file(buf, path, st->st_size) != st->st_size)2252 return error(_("unable to open or read %s"), path);2253 convert_to_git(path, buf->buf, buf->len, buf, 0);2254 return 0;2255 default:2256 return -1;2257 }2258}22592260/*2261 * Update the preimage, and the common lines in postimage,2262 * from buffer buf of length len. If postlen is 0 the postimage2263 * is updated in place, otherwise it's updated on a new buffer2264 * of length postlen2265 */22662267static void update_pre_post_images(struct image *preimage,2268 struct image *postimage,2269 char *buf,2270 size_t len, size_t postlen)2271{2272 int i, ctx, reduced;2273 char *new, *old, *fixed;2274 struct image fixed_preimage;22752276 /*2277 * Update the preimage with whitespace fixes. Note that we2278 * are not losing preimage->buf -- apply_one_fragment() will2279 * free "oldlines".2280 */2281 prepare_image(&fixed_preimage, buf, len, 1);2282 assert(postlen2283 ? fixed_preimage.nr == preimage->nr2284 : fixed_preimage.nr <= preimage->nr);2285 for (i = 0; i < fixed_preimage.nr; i++)2286 fixed_preimage.line[i].flag = preimage->line[i].flag;2287 free(preimage->line_allocated);2288 *preimage = fixed_preimage;22892290 /*2291 * Adjust the common context lines in postimage. This can be2292 * done in-place when we are shrinking it with whitespace2293 * fixing, but needs a new buffer when ignoring whitespace or2294 * expanding leading tabs to spaces.2295 *2296 * We trust the caller to tell us if the update can be done2297 * in place (postlen==0) or not.2298 */2299 old = postimage->buf;2300 if (postlen)2301 new = postimage->buf = xmalloc(postlen);2302 else2303 new = old;2304 fixed = preimage->buf;23052306 for (i = reduced = ctx = 0; i < postimage->nr; i++) {2307 size_t l_len = postimage->line[i].len;2308 if (!(postimage->line[i].flag & LINE_COMMON)) {2309 /* an added line -- no counterparts in preimage */2310 memmove(new, old, l_len);2311 old += l_len;2312 new += l_len;2313 continue;2314 }23152316 /* a common context -- skip it in the original postimage */2317 old += l_len;23182319 /* and find the corresponding one in the fixed preimage */2320 while (ctx < preimage->nr &&2321 !(preimage->line[ctx].flag & LINE_COMMON)) {2322 fixed += preimage->line[ctx].len;2323 ctx++;2324 }23252326 /*2327 * preimage is expected to run out, if the caller2328 * fixed addition of trailing blank lines.2329 */2330 if (preimage->nr <= ctx) {2331 reduced++;2332 continue;2333 }23342335 /* and copy it in, while fixing the line length */2336 l_len = preimage->line[ctx].len;2337 memcpy(new, fixed, l_len);2338 new += l_len;2339 fixed += l_len;2340 postimage->line[i].len = l_len;2341 ctx++;2342 }23432344 if (postlen2345 ? postlen < new - postimage->buf2346 : postimage->len < new - postimage->buf)2347 die("BUG: caller miscounted postlen: asked %d, orig = %d, used = %d",2348 (int)postlen, (int) postimage->len, (int)(new - postimage->buf));23492350 /* Fix the length of the whole thing */2351 postimage->len = new - postimage->buf;2352 postimage->nr -= reduced;2353}23542355static int line_by_line_fuzzy_match(struct image *img,2356 struct image *preimage,2357 struct image *postimage,2358 unsigned long try,2359 int try_lno,2360 int preimage_limit)2361{2362 int i;2363 size_t imgoff = 0;2364 size_t preoff = 0;2365 size_t postlen = postimage->len;2366 size_t extra_chars;2367 char *buf;2368 char *preimage_eof;2369 char *preimage_end;2370 struct strbuf fixed;2371 char *fixed_buf;2372 size_t fixed_len;23732374 for (i = 0; i < preimage_limit; i++) {2375 size_t prelen = preimage->line[i].len;2376 size_t imglen = img->line[try_lno+i].len;23772378 if (!fuzzy_matchlines(img->buf + try + imgoff, imglen,2379 preimage->buf + preoff, prelen))2380 return 0;2381 if (preimage->line[i].flag & LINE_COMMON)2382 postlen += imglen - prelen;2383 imgoff += imglen;2384 preoff += prelen;2385 }23862387 /*2388 * Ok, the preimage matches with whitespace fuzz.2389 *2390 * imgoff now holds the true length of the target that2391 * matches the preimage before the end of the file.2392 *2393 * Count the number of characters in the preimage that fall2394 * beyond the end of the file and make sure that all of them2395 * are whitespace characters. (This can only happen if2396 * we are removing blank lines at the end of the file.)2397 */2398 buf = preimage_eof = preimage->buf + preoff;2399 for ( ; i < preimage->nr; i++)2400 preoff += preimage->line[i].len;2401 preimage_end = preimage->buf + preoff;2402 for ( ; buf < preimage_end; buf++)2403 if (!isspace(*buf))2404 return 0;24052406 /*2407 * Update the preimage and the common postimage context2408 * lines to use the same whitespace as the target.2409 * If whitespace is missing in the target (i.e.2410 * if the preimage extends beyond the end of the file),2411 * use the whitespace from the preimage.2412 */2413 extra_chars = preimage_end - preimage_eof;2414 strbuf_init(&fixed, imgoff + extra_chars);2415 strbuf_add(&fixed, img->buf + try, imgoff);2416 strbuf_add(&fixed, preimage_eof, extra_chars);2417 fixed_buf = strbuf_detach(&fixed, &fixed_len);2418 update_pre_post_images(preimage, postimage,2419 fixed_buf, fixed_len, postlen);2420 return 1;2421}24222423static int match_fragment(struct apply_state *state,2424 struct image *img,2425 struct image *preimage,2426 struct image *postimage,2427 unsigned long try,2428 int try_lno,2429 unsigned ws_rule,2430 int match_beginning, int match_end)2431{2432 int i;2433 char *fixed_buf, *buf, *orig, *target;2434 struct strbuf fixed;2435 size_t fixed_len, postlen;2436 int preimage_limit;24372438 if (preimage->nr + try_lno <= img->nr) {2439 /*2440 * The hunk falls within the boundaries of img.2441 */2442 preimage_limit = preimage->nr;2443 if (match_end && (preimage->nr + try_lno != img->nr))2444 return 0;2445 } else if (state->ws_error_action == correct_ws_error &&2446 (ws_rule & WS_BLANK_AT_EOF)) {2447 /*2448 * This hunk extends beyond the end of img, and we are2449 * removing blank lines at the end of the file. This2450 * many lines from the beginning of the preimage must2451 * match with img, and the remainder of the preimage2452 * must be blank.2453 */2454 preimage_limit = img->nr - try_lno;2455 } else {2456 /*2457 * The hunk extends beyond the end of the img and2458 * we are not removing blanks at the end, so we2459 * should reject the hunk at this position.2460 */2461 return 0;2462 }24632464 if (match_beginning && try_lno)2465 return 0;24662467 /* Quick hash check */2468 for (i = 0; i < preimage_limit; i++)2469 if ((img->line[try_lno + i].flag & LINE_PATCHED) ||2470 (preimage->line[i].hash != img->line[try_lno + i].hash))2471 return 0;24722473 if (preimage_limit == preimage->nr) {2474 /*2475 * Do we have an exact match? If we were told to match2476 * at the end, size must be exactly at try+fragsize,2477 * otherwise try+fragsize must be still within the preimage,2478 * and either case, the old piece should match the preimage2479 * exactly.2480 */2481 if ((match_end2482 ? (try + preimage->len == img->len)2483 : (try + preimage->len <= img->len)) &&2484 !memcmp(img->buf + try, preimage->buf, preimage->len))2485 return 1;2486 } else {2487 /*2488 * The preimage extends beyond the end of img, so2489 * there cannot be an exact match.2490 *2491 * There must be one non-blank context line that match2492 * a line before the end of img.2493 */2494 char *buf_end;24952496 buf = preimage->buf;2497 buf_end = buf;2498 for (i = 0; i < preimage_limit; i++)2499 buf_end += preimage->line[i].len;25002501 for ( ; buf < buf_end; buf++)2502 if (!isspace(*buf))2503 break;2504 if (buf == buf_end)2505 return 0;2506 }25072508 /*2509 * No exact match. If we are ignoring whitespace, run a line-by-line2510 * fuzzy matching. We collect all the line length information because2511 * we need it to adjust whitespace if we match.2512 */2513 if (state->ws_ignore_action == ignore_ws_change)2514 return line_by_line_fuzzy_match(img, preimage, postimage,2515 try, try_lno, preimage_limit);25162517 if (state->ws_error_action != correct_ws_error)2518 return 0;25192520 /*2521 * The hunk does not apply byte-by-byte, but the hash says2522 * it might with whitespace fuzz. We weren't asked to2523 * ignore whitespace, we were asked to correct whitespace2524 * errors, so let's try matching after whitespace correction.2525 *2526 * While checking the preimage against the target, whitespace2527 * errors in both fixed, we count how large the corresponding2528 * postimage needs to be. The postimage prepared by2529 * apply_one_fragment() has whitespace errors fixed on added2530 * lines already, but the common lines were propagated as-is,2531 * which may become longer when their whitespace errors are2532 * fixed.2533 */25342535 /* First count added lines in postimage */2536 postlen = 0;2537 for (i = 0; i < postimage->nr; i++) {2538 if (!(postimage->line[i].flag & LINE_COMMON))2539 postlen += postimage->line[i].len;2540 }25412542 /*2543 * The preimage may extend beyond the end of the file,2544 * but in this loop we will only handle the part of the2545 * preimage that falls within the file.2546 */2547 strbuf_init(&fixed, preimage->len + 1);2548 orig = preimage->buf;2549 target = img->buf + try;2550 for (i = 0; i < preimage_limit; i++) {2551 size_t oldlen = preimage->line[i].len;2552 size_t tgtlen = img->line[try_lno + i].len;2553 size_t fixstart = fixed.len;2554 struct strbuf tgtfix;2555 int match;25562557 /* Try fixing the line in the preimage */2558 ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);25592560 /* Try fixing the line in the target */2561 strbuf_init(&tgtfix, tgtlen);2562 ws_fix_copy(&tgtfix, target, tgtlen, ws_rule, NULL);25632564 /*2565 * If they match, either the preimage was based on2566 * a version before our tree fixed whitespace breakage,2567 * or we are lacking a whitespace-fix patch the tree2568 * the preimage was based on already had (i.e. target2569 * has whitespace breakage, the preimage doesn't).2570 * In either case, we are fixing the whitespace breakages2571 * so we might as well take the fix together with their2572 * real change.2573 */2574 match = (tgtfix.len == fixed.len - fixstart &&2575 !memcmp(tgtfix.buf, fixed.buf + fixstart,2576 fixed.len - fixstart));25772578 /* Add the length if this is common with the postimage */2579 if (preimage->line[i].flag & LINE_COMMON)2580 postlen += tgtfix.len;25812582 strbuf_release(&tgtfix);2583 if (!match)2584 goto unmatch_exit;25852586 orig += oldlen;2587 target += tgtlen;2588 }258925902591 /*2592 * Now handle the lines in the preimage that falls beyond the2593 * end of the file (if any). They will only match if they are2594 * empty or only contain whitespace (if WS_BLANK_AT_EOL is2595 * false).2596 */2597 for ( ; i < preimage->nr; i++) {2598 size_t fixstart = fixed.len; /* start of the fixed preimage */2599 size_t oldlen = preimage->line[i].len;2600 int j;26012602 /* Try fixing the line in the preimage */2603 ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);26042605 for (j = fixstart; j < fixed.len; j++)2606 if (!isspace(fixed.buf[j]))2607 goto unmatch_exit;26082609 orig += oldlen;2610 }26112612 /*2613 * Yes, the preimage is based on an older version that still2614 * has whitespace breakages unfixed, and fixing them makes the2615 * hunk match. Update the context lines in the postimage.2616 */2617 fixed_buf = strbuf_detach(&fixed, &fixed_len);2618 if (postlen < postimage->len)2619 postlen = 0;2620 update_pre_post_images(preimage, postimage,2621 fixed_buf, fixed_len, postlen);2622 return 1;26232624 unmatch_exit:2625 strbuf_release(&fixed);2626 return 0;2627}26282629static int find_pos(struct apply_state *state,2630 struct image *img,2631 struct image *preimage,2632 struct image *postimage,2633 int line,2634 unsigned ws_rule,2635 int match_beginning, int match_end)2636{2637 int i;2638 unsigned long backwards, forwards, try;2639 int backwards_lno, forwards_lno, try_lno;26402641 /*2642 * If match_beginning or match_end is specified, there is no2643 * point starting from a wrong line that will never match and2644 * wander around and wait for a match at the specified end.2645 */2646 if (match_beginning)2647 line = 0;2648 else if (match_end)2649 line = img->nr - preimage->nr;26502651 /*2652 * Because the comparison is unsigned, the following test2653 * will also take care of a negative line number that can2654 * result when match_end and preimage is larger than the target.2655 */2656 if ((size_t) line > img->nr)2657 line = img->nr;26582659 try = 0;2660 for (i = 0; i < line; i++)2661 try += img->line[i].len;26622663 /*2664 * There's probably some smart way to do this, but I'll leave2665 * that to the smart and beautiful people. I'm simple and stupid.2666 */2667 backwards = try;2668 backwards_lno = line;2669 forwards = try;2670 forwards_lno = line;2671 try_lno = line;26722673 for (i = 0; ; i++) {2674 if (match_fragment(state, img, preimage, postimage,2675 try, try_lno, ws_rule,2676 match_beginning, match_end))2677 return try_lno;26782679 again:2680 if (backwards_lno == 0 && forwards_lno == img->nr)2681 break;26822683 if (i & 1) {2684 if (backwards_lno == 0) {2685 i++;2686 goto again;2687 }2688 backwards_lno--;2689 backwards -= img->line[backwards_lno].len;2690 try = backwards;2691 try_lno = backwards_lno;2692 } else {2693 if (forwards_lno == img->nr) {2694 i++;2695 goto again;2696 }2697 forwards += img->line[forwards_lno].len;2698 forwards_lno++;2699 try = forwards;2700 try_lno = forwards_lno;2701 }27022703 }2704 return -1;2705}27062707static void remove_first_line(struct image *img)2708{2709 img->buf += img->line[0].len;2710 img->len -= img->line[0].len;2711 img->line++;2712 img->nr--;2713}27142715static void remove_last_line(struct image *img)2716{2717 img->len -= img->line[--img->nr].len;2718}27192720/*2721 * The change from "preimage" and "postimage" has been found to2722 * apply at applied_pos (counts in line numbers) in "img".2723 * Update "img" to remove "preimage" and replace it with "postimage".2724 */2725static void update_image(struct apply_state *state,2726 struct image *img,2727 int applied_pos,2728 struct image *preimage,2729 struct image *postimage)2730{2731 /*2732 * remove the copy of preimage at offset in img2733 * and replace it with postimage2734 */2735 int i, nr;2736 size_t remove_count, insert_count, applied_at = 0;2737 char *result;2738 int preimage_limit;27392740 /*2741 * If we are removing blank lines at the end of img,2742 * the preimage may extend beyond the end.2743 * If that is the case, we must be careful only to2744 * remove the part of the preimage that falls within2745 * the boundaries of img. Initialize preimage_limit2746 * to the number of lines in the preimage that falls2747 * within the boundaries.2748 */2749 preimage_limit = preimage->nr;2750 if (preimage_limit > img->nr - applied_pos)2751 preimage_limit = img->nr - applied_pos;27522753 for (i = 0; i < applied_pos; i++)2754 applied_at += img->line[i].len;27552756 remove_count = 0;2757 for (i = 0; i < preimage_limit; i++)2758 remove_count += img->line[applied_pos + i].len;2759 insert_count = postimage->len;27602761 /* Adjust the contents */2762 result = xmalloc(st_add3(st_sub(img->len, remove_count), insert_count, 1));2763 memcpy(result, img->buf, applied_at);2764 memcpy(result + applied_at, postimage->buf, postimage->len);2765 memcpy(result + applied_at + postimage->len,2766 img->buf + (applied_at + remove_count),2767 img->len - (applied_at + remove_count));2768 free(img->buf);2769 img->buf = result;2770 img->len += insert_count - remove_count;2771 result[img->len] = '\0';27722773 /* Adjust the line table */2774 nr = img->nr + postimage->nr - preimage_limit;2775 if (preimage_limit < postimage->nr) {2776 /*2777 * NOTE: this knows that we never call remove_first_line()2778 * on anything other than pre/post image.2779 */2780 REALLOC_ARRAY(img->line, nr);2781 img->line_allocated = img->line;2782 }2783 if (preimage_limit != postimage->nr)2784 memmove(img->line + applied_pos + postimage->nr,2785 img->line + applied_pos + preimage_limit,2786 (img->nr - (applied_pos + preimage_limit)) *2787 sizeof(*img->line));2788 memcpy(img->line + applied_pos,2789 postimage->line,2790 postimage->nr * sizeof(*img->line));2791 if (!state->allow_overlap)2792 for (i = 0; i < postimage->nr; i++)2793 img->line[applied_pos + i].flag |= LINE_PATCHED;2794 img->nr = nr;2795}27962797/*2798 * Use the patch-hunk text in "frag" to prepare two images (preimage and2799 * postimage) for the hunk. Find lines that match "preimage" in "img" and2800 * replace the part of "img" with "postimage" text.2801 */2802static int apply_one_fragment(struct apply_state *state,2803 struct image *img, struct fragment *frag,2804 int inaccurate_eof, unsigned ws_rule,2805 int nth_fragment)2806{2807 int match_beginning, match_end;2808 const char *patch = frag->patch;2809 int size = frag->size;2810 char *old, *oldlines;2811 struct strbuf newlines;2812 int new_blank_lines_at_end = 0;2813 int found_new_blank_lines_at_end = 0;2814 int hunk_linenr = frag->linenr;2815 unsigned long leading, trailing;2816 int pos, applied_pos;2817 struct image preimage;2818 struct image postimage;28192820 memset(&preimage, 0, sizeof(preimage));2821 memset(&postimage, 0, sizeof(postimage));2822 oldlines = xmalloc(size);2823 strbuf_init(&newlines, size);28242825 old = oldlines;2826 while (size > 0) {2827 char first;2828 int len = linelen(patch, size);2829 int plen;2830 int added_blank_line = 0;2831 int is_blank_context = 0;2832 size_t start;28332834 if (!len)2835 break;28362837 /*2838 * "plen" is how much of the line we should use for2839 * the actual patch data. Normally we just remove the2840 * first character on the line, but if the line is2841 * followed by "\ No newline", then we also remove the2842 * last one (which is the newline, of course).2843 */2844 plen = len - 1;2845 if (len < size && patch[len] == '\\')2846 plen--;2847 first = *patch;2848 if (state->apply_in_reverse) {2849 if (first == '-')2850 first = '+';2851 else if (first == '+')2852 first = '-';2853 }28542855 switch (first) {2856 case '\n':2857 /* Newer GNU diff, empty context line */2858 if (plen < 0)2859 /* ... followed by '\No newline'; nothing */2860 break;2861 *old++ = '\n';2862 strbuf_addch(&newlines, '\n');2863 add_line_info(&preimage, "\n", 1, LINE_COMMON);2864 add_line_info(&postimage, "\n", 1, LINE_COMMON);2865 is_blank_context = 1;2866 break;2867 case ' ':2868 if (plen && (ws_rule & WS_BLANK_AT_EOF) &&2869 ws_blank_line(patch + 1, plen, ws_rule))2870 is_blank_context = 1;2871 case '-':2872 memcpy(old, patch + 1, plen);2873 add_line_info(&preimage, old, plen,2874 (first == ' ' ? LINE_COMMON : 0));2875 old += plen;2876 if (first == '-')2877 break;2878 /* Fall-through for ' ' */2879 case '+':2880 /* --no-add does not add new lines */2881 if (first == '+' && state->no_add)2882 break;28832884 start = newlines.len;2885 if (first != '+' ||2886 !state->whitespace_error ||2887 state->ws_error_action != correct_ws_error) {2888 strbuf_add(&newlines, patch + 1, plen);2889 }2890 else {2891 ws_fix_copy(&newlines, patch + 1, plen, ws_rule, &state->applied_after_fixing_ws);2892 }2893 add_line_info(&postimage, newlines.buf + start, newlines.len - start,2894 (first == '+' ? 0 : LINE_COMMON));2895 if (first == '+' &&2896 (ws_rule & WS_BLANK_AT_EOF) &&2897 ws_blank_line(patch + 1, plen, ws_rule))2898 added_blank_line = 1;2899 break;2900 case '@': case '\\':2901 /* Ignore it, we already handled it */2902 break;2903 default:2904 if (state->apply_verbosely)2905 error(_("invalid start of line: '%c'"), first);2906 applied_pos = -1;2907 goto out;2908 }2909 if (added_blank_line) {2910 if (!new_blank_lines_at_end)2911 found_new_blank_lines_at_end = hunk_linenr;2912 new_blank_lines_at_end++;2913 }2914 else if (is_blank_context)2915 ;2916 else2917 new_blank_lines_at_end = 0;2918 patch += len;2919 size -= len;2920 hunk_linenr++;2921 }2922 if (inaccurate_eof &&2923 old > oldlines && old[-1] == '\n' &&2924 newlines.len > 0 && newlines.buf[newlines.len - 1] == '\n') {2925 old--;2926 strbuf_setlen(&newlines, newlines.len - 1);2927 }29282929 leading = frag->leading;2930 trailing = frag->trailing;29312932 /*2933 * A hunk to change lines at the beginning would begin with2934 * @@ -1,L +N,M @@2935 * but we need to be careful. -U0 that inserts before the second2936 * line also has this pattern.2937 *2938 * And a hunk to add to an empty file would begin with2939 * @@ -0,0 +N,M @@2940 *2941 * In other words, a hunk that is (frag->oldpos <= 1) with or2942 * without leading context must match at the beginning.2943 */2944 match_beginning = (!frag->oldpos ||2945 (frag->oldpos == 1 && !state->unidiff_zero));29462947 /*2948 * A hunk without trailing lines must match at the end.2949 * However, we simply cannot tell if a hunk must match end2950 * from the lack of trailing lines if the patch was generated2951 * with unidiff without any context.2952 */2953 match_end = !state->unidiff_zero && !trailing;29542955 pos = frag->newpos ? (frag->newpos - 1) : 0;2956 preimage.buf = oldlines;2957 preimage.len = old - oldlines;2958 postimage.buf = newlines.buf;2959 postimage.len = newlines.len;2960 preimage.line = preimage.line_allocated;2961 postimage.line = postimage.line_allocated;29622963 for (;;) {29642965 applied_pos = find_pos(state, img, &preimage, &postimage, pos,2966 ws_rule, match_beginning, match_end);29672968 if (applied_pos >= 0)2969 break;29702971 /* Am I at my context limits? */2972 if ((leading <= state->p_context) && (trailing <= state->p_context))2973 break;2974 if (match_beginning || match_end) {2975 match_beginning = match_end = 0;2976 continue;2977 }29782979 /*2980 * Reduce the number of context lines; reduce both2981 * leading and trailing if they are equal otherwise2982 * just reduce the larger context.2983 */2984 if (leading >= trailing) {2985 remove_first_line(&preimage);2986 remove_first_line(&postimage);2987 pos--;2988 leading--;2989 }2990 if (trailing > leading) {2991 remove_last_line(&preimage);2992 remove_last_line(&postimage);2993 trailing--;2994 }2995 }29962997 if (applied_pos >= 0) {2998 if (new_blank_lines_at_end &&2999 preimage.nr + applied_pos >= img->nr &&3000 (ws_rule & WS_BLANK_AT_EOF) &&3001 state->ws_error_action != nowarn_ws_error) {3002 record_ws_error(state, WS_BLANK_AT_EOF, "+", 1,3003 found_new_blank_lines_at_end);3004 if (state->ws_error_action == correct_ws_error) {3005 while (new_blank_lines_at_end--)3006 remove_last_line(&postimage);3007 }3008 /*3009 * We would want to prevent write_out_results()3010 * from taking place in apply_patch() that follows3011 * the callchain led us here, which is:3012 * apply_patch->check_patch_list->check_patch->3013 * apply_data->apply_fragments->apply_one_fragment3014 */3015 if (state->ws_error_action == die_on_ws_error)3016 state->apply = 0;3017 }30183019 if (state->apply_verbosely && applied_pos != pos) {3020 int offset = applied_pos - pos;3021 if (state->apply_in_reverse)3022 offset = 0 - offset;3023 fprintf_ln(stderr,3024 Q_("Hunk #%d succeeded at %d (offset %d line).",3025 "Hunk #%d succeeded at %d (offset %d lines).",3026 offset),3027 nth_fragment, applied_pos + 1, offset);3028 }30293030 /*3031 * Warn if it was necessary to reduce the number3032 * of context lines.3033 */3034 if ((leading != frag->leading) ||3035 (trailing != frag->trailing))3036 fprintf_ln(stderr, _("Context reduced to (%ld/%ld)"3037 " to apply fragment at %d"),3038 leading, trailing, applied_pos+1);3039 update_image(state, img, applied_pos, &preimage, &postimage);3040 } else {3041 if (state->apply_verbosely)3042 error(_("while searching for:\n%.*s"),3043 (int)(old - oldlines), oldlines);3044 }30453046out:3047 free(oldlines);3048 strbuf_release(&newlines);3049 free(preimage.line_allocated);3050 free(postimage.line_allocated);30513052 return (applied_pos < 0);3053}30543055static int apply_binary_fragment(struct apply_state *state,3056 struct image *img,3057 struct patch *patch)3058{3059 struct fragment *fragment = patch->fragments;3060 unsigned long len;3061 void *dst;30623063 if (!fragment)3064 return error(_("missing binary patch data for '%s'"),3065 patch->new_name ?3066 patch->new_name :3067 patch->old_name);30683069 /* Binary patch is irreversible without the optional second hunk */3070 if (state->apply_in_reverse) {3071 if (!fragment->next)3072 return error("cannot reverse-apply a binary patch "3073 "without the reverse hunk to '%s'",3074 patch->new_name3075 ? patch->new_name : patch->old_name);3076 fragment = fragment->next;3077 }3078 switch (fragment->binary_patch_method) {3079 case BINARY_DELTA_DEFLATED:3080 dst = patch_delta(img->buf, img->len, fragment->patch,3081 fragment->size, &len);3082 if (!dst)3083 return -1;3084 clear_image(img);3085 img->buf = dst;3086 img->len = len;3087 return 0;3088 case BINARY_LITERAL_DEFLATED:3089 clear_image(img);3090 img->len = fragment->size;3091 img->buf = xmemdupz(fragment->patch, img->len);3092 return 0;3093 }3094 return -1;3095}30963097/*3098 * Replace "img" with the result of applying the binary patch.3099 * The binary patch data itself in patch->fragment is still kept3100 * but the preimage prepared by the caller in "img" is freed here3101 * or in the helper function apply_binary_fragment() this calls.3102 */3103static int apply_binary(struct apply_state *state,3104 struct image *img,3105 struct patch *patch)3106{3107 const char *name = patch->old_name ? patch->old_name : patch->new_name;3108 unsigned char sha1[20];31093110 /*3111 * For safety, we require patch index line to contain3112 * full 40-byte textual SHA1 for old and new, at least for now.3113 */3114 if (strlen(patch->old_sha1_prefix) != 40 ||3115 strlen(patch->new_sha1_prefix) != 40 ||3116 get_sha1_hex(patch->old_sha1_prefix, sha1) ||3117 get_sha1_hex(patch->new_sha1_prefix, sha1))3118 return error("cannot apply binary patch to '%s' "3119 "without full index line", name);31203121 if (patch->old_name) {3122 /*3123 * See if the old one matches what the patch3124 * applies to.3125 */3126 hash_sha1_file(img->buf, img->len, blob_type, sha1);3127 if (strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))3128 return error("the patch applies to '%s' (%s), "3129 "which does not match the "3130 "current contents.",3131 name, sha1_to_hex(sha1));3132 }3133 else {3134 /* Otherwise, the old one must be empty. */3135 if (img->len)3136 return error("the patch applies to an empty "3137 "'%s' but it is not empty", name);3138 }31393140 get_sha1_hex(patch->new_sha1_prefix, sha1);3141 if (is_null_sha1(sha1)) {3142 clear_image(img);3143 return 0; /* deletion patch */3144 }31453146 if (has_sha1_file(sha1)) {3147 /* We already have the postimage */3148 enum object_type type;3149 unsigned long size;3150 char *result;31513152 result = read_sha1_file(sha1, &type, &size);3153 if (!result)3154 return error("the necessary postimage %s for "3155 "'%s' cannot be read",3156 patch->new_sha1_prefix, name);3157 clear_image(img);3158 img->buf = result;3159 img->len = size;3160 } else {3161 /*3162 * We have verified buf matches the preimage;3163 * apply the patch data to it, which is stored3164 * in the patch->fragments->{patch,size}.3165 */3166 if (apply_binary_fragment(state, img, patch))3167 return error(_("binary patch does not apply to '%s'"),3168 name);31693170 /* verify that the result matches */3171 hash_sha1_file(img->buf, img->len, blob_type, sha1);3172 if (strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))3173 return error(_("binary patch to '%s' creates incorrect result (expecting %s, got %s)"),3174 name, patch->new_sha1_prefix, sha1_to_hex(sha1));3175 }31763177 return 0;3178}31793180static int apply_fragments(struct apply_state *state, struct image *img, struct patch *patch)3181{3182 struct fragment *frag = patch->fragments;3183 const char *name = patch->old_name ? patch->old_name : patch->new_name;3184 unsigned ws_rule = patch->ws_rule;3185 unsigned inaccurate_eof = patch->inaccurate_eof;3186 int nth = 0;31873188 if (patch->is_binary)3189 return apply_binary(state, img, patch);31903191 while (frag) {3192 nth++;3193 if (apply_one_fragment(state, img, frag, inaccurate_eof, ws_rule, nth)) {3194 error(_("patch failed: %s:%ld"), name, frag->oldpos);3195 if (!state->apply_with_reject)3196 return -1;3197 frag->rejected = 1;3198 }3199 frag = frag->next;3200 }3201 return 0;3202}32033204static int read_blob_object(struct strbuf *buf, const unsigned char *sha1, unsigned mode)3205{3206 if (S_ISGITLINK(mode)) {3207 strbuf_grow(buf, 100);3208 strbuf_addf(buf, "Subproject commit %s\n", sha1_to_hex(sha1));3209 } else {3210 enum object_type type;3211 unsigned long sz;3212 char *result;32133214 result = read_sha1_file(sha1, &type, &sz);3215 if (!result)3216 return -1;3217 /* XXX read_sha1_file NUL-terminates */3218 strbuf_attach(buf, result, sz, sz + 1);3219 }3220 return 0;3221}32223223static int read_file_or_gitlink(const struct cache_entry *ce, struct strbuf *buf)3224{3225 if (!ce)3226 return 0;3227 return read_blob_object(buf, ce->sha1, ce->ce_mode);3228}32293230static struct patch *in_fn_table(struct apply_state *state, const char *name)3231{3232 struct string_list_item *item;32333234 if (name == NULL)3235 return NULL;32363237 item = string_list_lookup(&state->fn_table, name);3238 if (item != NULL)3239 return (struct patch *)item->util;32403241 return NULL;3242}32433244/*3245 * item->util in the filename table records the status of the path.3246 * Usually it points at a patch (whose result records the contents3247 * of it after applying it), but it could be PATH_WAS_DELETED for a3248 * path that a previously applied patch has already removed, or3249 * PATH_TO_BE_DELETED for a path that a later patch would remove.3250 *3251 * The latter is needed to deal with a case where two paths A and B3252 * are swapped by first renaming A to B and then renaming B to A;3253 * moving A to B should not be prevented due to presence of B as we3254 * will remove it in a later patch.3255 */3256#define PATH_TO_BE_DELETED ((struct patch *) -2)3257#define PATH_WAS_DELETED ((struct patch *) -1)32583259static int to_be_deleted(struct patch *patch)3260{3261 return patch == PATH_TO_BE_DELETED;3262}32633264static int was_deleted(struct patch *patch)3265{3266 return patch == PATH_WAS_DELETED;3267}32683269static void add_to_fn_table(struct apply_state *state, struct patch *patch)3270{3271 struct string_list_item *item;32723273 /*3274 * Always add new_name unless patch is a deletion3275 * This should cover the cases for normal diffs,3276 * file creations and copies3277 */3278 if (patch->new_name != NULL) {3279 item = string_list_insert(&state->fn_table, patch->new_name);3280 item->util = patch;3281 }32823283 /*3284 * store a failure on rename/deletion cases because3285 * later chunks shouldn't patch old names3286 */3287 if ((patch->new_name == NULL) || (patch->is_rename)) {3288 item = string_list_insert(&state->fn_table, patch->old_name);3289 item->util = PATH_WAS_DELETED;3290 }3291}32923293static void prepare_fn_table(struct apply_state *state, struct patch *patch)3294{3295 /*3296 * store information about incoming file deletion3297 */3298 while (patch) {3299 if ((patch->new_name == NULL) || (patch->is_rename)) {3300 struct string_list_item *item;3301 item = string_list_insert(&state->fn_table, patch->old_name);3302 item->util = PATH_TO_BE_DELETED;3303 }3304 patch = patch->next;3305 }3306}33073308static int checkout_target(struct index_state *istate,3309 struct cache_entry *ce, struct stat *st)3310{3311 struct checkout costate;33123313 memset(&costate, 0, sizeof(costate));3314 costate.base_dir = "";3315 costate.refresh_cache = 1;3316 costate.istate = istate;3317 if (checkout_entry(ce, &costate, NULL) || lstat(ce->name, st))3318 return error(_("cannot checkout %s"), ce->name);3319 return 0;3320}33213322static struct patch *previous_patch(struct apply_state *state,3323 struct patch *patch,3324 int *gone)3325{3326 struct patch *previous;33273328 *gone = 0;3329 if (patch->is_copy || patch->is_rename)3330 return NULL; /* "git" patches do not depend on the order */33313332 previous = in_fn_table(state, patch->old_name);3333 if (!previous)3334 return NULL;33353336 if (to_be_deleted(previous))3337 return NULL; /* the deletion hasn't happened yet */33383339 if (was_deleted(previous))3340 *gone = 1;33413342 return previous;3343}33443345static int verify_index_match(const struct cache_entry *ce, struct stat *st)3346{3347 if (S_ISGITLINK(ce->ce_mode)) {3348 if (!S_ISDIR(st->st_mode))3349 return -1;3350 return 0;3351 }3352 return ce_match_stat(ce, st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE);3353}33543355#define SUBMODULE_PATCH_WITHOUT_INDEX 133563357static int load_patch_target(struct apply_state *state,3358 struct strbuf *buf,3359 const struct cache_entry *ce,3360 struct stat *st,3361 const char *name,3362 unsigned expected_mode)3363{3364 if (state->cached || state->check_index) {3365 if (read_file_or_gitlink(ce, buf))3366 return error(_("read of %s failed"), name);3367 } else if (name) {3368 if (S_ISGITLINK(expected_mode)) {3369 if (ce)3370 return read_file_or_gitlink(ce, buf);3371 else3372 return SUBMODULE_PATCH_WITHOUT_INDEX;3373 } else if (has_symlink_leading_path(name, strlen(name))) {3374 return error(_("reading from '%s' beyond a symbolic link"), name);3375 } else {3376 if (read_old_data(st, name, buf))3377 return error(_("read of %s failed"), name);3378 }3379 }3380 return 0;3381}33823383/*3384 * We are about to apply "patch"; populate the "image" with the3385 * current version we have, from the working tree or from the index,3386 * depending on the situation e.g. --cached/--index. If we are3387 * applying a non-git patch that incrementally updates the tree,3388 * we read from the result of a previous diff.3389 */3390static int load_preimage(struct apply_state *state,3391 struct image *image,3392 struct patch *patch, struct stat *st,3393 const struct cache_entry *ce)3394{3395 struct strbuf buf = STRBUF_INIT;3396 size_t len;3397 char *img;3398 struct patch *previous;3399 int status;34003401 previous = previous_patch(state, patch, &status);3402 if (status)3403 return error(_("path %s has been renamed/deleted"),3404 patch->old_name);3405 if (previous) {3406 /* We have a patched copy in memory; use that. */3407 strbuf_add(&buf, previous->result, previous->resultsize);3408 } else {3409 status = load_patch_target(state, &buf, ce, st,3410 patch->old_name, patch->old_mode);3411 if (status < 0)3412 return status;3413 else if (status == SUBMODULE_PATCH_WITHOUT_INDEX) {3414 /*3415 * There is no way to apply subproject3416 * patch without looking at the index.3417 * NEEDSWORK: shouldn't this be flagged3418 * as an error???3419 */3420 free_fragment_list(patch->fragments);3421 patch->fragments = NULL;3422 } else if (status) {3423 return error(_("read of %s failed"), patch->old_name);3424 }3425 }34263427 img = strbuf_detach(&buf, &len);3428 prepare_image(image, img, len, !patch->is_binary);3429 return 0;3430}34313432static int three_way_merge(struct image *image,3433 char *path,3434 const unsigned char *base,3435 const unsigned char *ours,3436 const unsigned char *theirs)3437{3438 mmfile_t base_file, our_file, their_file;3439 mmbuffer_t result = { NULL };3440 int status;34413442 read_mmblob(&base_file, base);3443 read_mmblob(&our_file, ours);3444 read_mmblob(&their_file, theirs);3445 status = ll_merge(&result, path,3446 &base_file, "base",3447 &our_file, "ours",3448 &their_file, "theirs", NULL);3449 free(base_file.ptr);3450 free(our_file.ptr);3451 free(their_file.ptr);3452 if (status < 0 || !result.ptr) {3453 free(result.ptr);3454 return -1;3455 }3456 clear_image(image);3457 image->buf = result.ptr;3458 image->len = result.size;34593460 return status;3461}34623463/*3464 * When directly falling back to add/add three-way merge, we read from3465 * the current contents of the new_name. In no cases other than that3466 * this function will be called.3467 */3468static int load_current(struct apply_state *state,3469 struct image *image,3470 struct patch *patch)3471{3472 struct strbuf buf = STRBUF_INIT;3473 int status, pos;3474 size_t len;3475 char *img;3476 struct stat st;3477 struct cache_entry *ce;3478 char *name = patch->new_name;3479 unsigned mode = patch->new_mode;34803481 if (!patch->is_new)3482 die("BUG: patch to %s is not a creation", patch->old_name);34833484 pos = cache_name_pos(name, strlen(name));3485 if (pos < 0)3486 return error(_("%s: does not exist in index"), name);3487 ce = active_cache[pos];3488 if (lstat(name, &st)) {3489 if (errno != ENOENT)3490 return error(_("%s: %s"), name, strerror(errno));3491 if (checkout_target(&the_index, ce, &st))3492 return -1;3493 }3494 if (verify_index_match(ce, &st))3495 return error(_("%s: does not match index"), name);34963497 status = load_patch_target(state, &buf, ce, &st, name, mode);3498 if (status < 0)3499 return status;3500 else if (status)3501 return -1;3502 img = strbuf_detach(&buf, &len);3503 prepare_image(image, img, len, !patch->is_binary);3504 return 0;3505}35063507static int try_threeway(struct apply_state *state,3508 struct image *image,3509 struct patch *patch,3510 struct stat *st,3511 const struct cache_entry *ce)3512{3513 unsigned char pre_sha1[20], post_sha1[20], our_sha1[20];3514 struct strbuf buf = STRBUF_INIT;3515 size_t len;3516 int status;3517 char *img;3518 struct image tmp_image;35193520 /* No point falling back to 3-way merge in these cases */3521 if (patch->is_delete ||3522 S_ISGITLINK(patch->old_mode) || S_ISGITLINK(patch->new_mode))3523 return -1;35243525 /* Preimage the patch was prepared for */3526 if (patch->is_new)3527 write_sha1_file("", 0, blob_type, pre_sha1);3528 else if (get_sha1(patch->old_sha1_prefix, pre_sha1) ||3529 read_blob_object(&buf, pre_sha1, patch->old_mode))3530 return error("repository lacks the necessary blob to fall back on 3-way merge.");35313532 fprintf(stderr, "Falling back to three-way merge...\n");35333534 img = strbuf_detach(&buf, &len);3535 prepare_image(&tmp_image, img, len, 1);3536 /* Apply the patch to get the post image */3537 if (apply_fragments(state, &tmp_image, patch) < 0) {3538 clear_image(&tmp_image);3539 return -1;3540 }3541 /* post_sha1[] is theirs */3542 write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, post_sha1);3543 clear_image(&tmp_image);35443545 /* our_sha1[] is ours */3546 if (patch->is_new) {3547 if (load_current(state, &tmp_image, patch))3548 return error("cannot read the current contents of '%s'",3549 patch->new_name);3550 } else {3551 if (load_preimage(state, &tmp_image, patch, st, ce))3552 return error("cannot read the current contents of '%s'",3553 patch->old_name);3554 }3555 write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, our_sha1);3556 clear_image(&tmp_image);35573558 /* in-core three-way merge between post and our using pre as base */3559 status = three_way_merge(image, patch->new_name,3560 pre_sha1, our_sha1, post_sha1);3561 if (status < 0) {3562 fprintf(stderr, "Failed to fall back on three-way merge...\n");3563 return status;3564 }35653566 if (status) {3567 patch->conflicted_threeway = 1;3568 if (patch->is_new)3569 oidclr(&patch->threeway_stage[0]);3570 else3571 hashcpy(patch->threeway_stage[0].hash, pre_sha1);3572 hashcpy(patch->threeway_stage[1].hash, our_sha1);3573 hashcpy(patch->threeway_stage[2].hash, post_sha1);3574 fprintf(stderr, "Applied patch to '%s' with conflicts.\n", patch->new_name);3575 } else {3576 fprintf(stderr, "Applied patch to '%s' cleanly.\n", patch->new_name);3577 }3578 return 0;3579}35803581static int apply_data(struct apply_state *state, struct patch *patch,3582 struct stat *st, const struct cache_entry *ce)3583{3584 struct image image;35853586 if (load_preimage(state, &image, patch, st, ce) < 0)3587 return -1;35883589 if (patch->direct_to_threeway ||3590 apply_fragments(state, &image, patch) < 0) {3591 /* Note: with --reject, apply_fragments() returns 0 */3592 if (!state->threeway || try_threeway(state, &image, patch, st, ce) < 0)3593 return -1;3594 }3595 patch->result = image.buf;3596 patch->resultsize = image.len;3597 add_to_fn_table(state, patch);3598 free(image.line_allocated);35993600 if (0 < patch->is_delete && patch->resultsize)3601 return error(_("removal patch leaves file contents"));36023603 return 0;3604}36053606/*3607 * If "patch" that we are looking at modifies or deletes what we have,3608 * we would want it not to lose any local modification we have, either3609 * in the working tree or in the index.3610 *3611 * This also decides if a non-git patch is a creation patch or a3612 * modification to an existing empty file. We do not check the state3613 * of the current tree for a creation patch in this function; the caller3614 * check_patch() separately makes sure (and errors out otherwise) that3615 * the path the patch creates does not exist in the current tree.3616 */3617static int check_preimage(struct apply_state *state,3618 struct patch *patch,3619 struct cache_entry **ce,3620 struct stat *st)3621{3622 const char *old_name = patch->old_name;3623 struct patch *previous = NULL;3624 int stat_ret = 0, status;3625 unsigned st_mode = 0;36263627 if (!old_name)3628 return 0;36293630 assert(patch->is_new <= 0);3631 previous = previous_patch(state, patch, &status);36323633 if (status)3634 return error(_("path %s has been renamed/deleted"), old_name);3635 if (previous) {3636 st_mode = previous->new_mode;3637 } else if (!state->cached) {3638 stat_ret = lstat(old_name, st);3639 if (stat_ret && errno != ENOENT)3640 return error(_("%s: %s"), old_name, strerror(errno));3641 }36423643 if (state->check_index && !previous) {3644 int pos = cache_name_pos(old_name, strlen(old_name));3645 if (pos < 0) {3646 if (patch->is_new < 0)3647 goto is_new;3648 return error(_("%s: does not exist in index"), old_name);3649 }3650 *ce = active_cache[pos];3651 if (stat_ret < 0) {3652 if (checkout_target(&the_index, *ce, st))3653 return -1;3654 }3655 if (!state->cached && verify_index_match(*ce, st))3656 return error(_("%s: does not match index"), old_name);3657 if (state->cached)3658 st_mode = (*ce)->ce_mode;3659 } else if (stat_ret < 0) {3660 if (patch->is_new < 0)3661 goto is_new;3662 return error(_("%s: %s"), old_name, strerror(errno));3663 }36643665 if (!state->cached && !previous)3666 st_mode = ce_mode_from_stat(*ce, st->st_mode);36673668 if (patch->is_new < 0)3669 patch->is_new = 0;3670 if (!patch->old_mode)3671 patch->old_mode = st_mode;3672 if ((st_mode ^ patch->old_mode) & S_IFMT)3673 return error(_("%s: wrong type"), old_name);3674 if (st_mode != patch->old_mode)3675 warning(_("%s has type %o, expected %o"),3676 old_name, st_mode, patch->old_mode);3677 if (!patch->new_mode && !patch->is_delete)3678 patch->new_mode = st_mode;3679 return 0;36803681 is_new:3682 patch->is_new = 1;3683 patch->is_delete = 0;3684 free(patch->old_name);3685 patch->old_name = NULL;3686 return 0;3687}368836893690#define EXISTS_IN_INDEX 13691#define EXISTS_IN_WORKTREE 236923693static int check_to_create(struct apply_state *state,3694 const char *new_name,3695 int ok_if_exists)3696{3697 struct stat nst;36983699 if (state->check_index &&3700 cache_name_pos(new_name, strlen(new_name)) >= 0 &&3701 !ok_if_exists)3702 return EXISTS_IN_INDEX;3703 if (state->cached)3704 return 0;37053706 if (!lstat(new_name, &nst)) {3707 if (S_ISDIR(nst.st_mode) || ok_if_exists)3708 return 0;3709 /*3710 * A leading component of new_name might be a symlink3711 * that is going to be removed with this patch, but3712 * still pointing at somewhere that has the path.3713 * In such a case, path "new_name" does not exist as3714 * far as git is concerned.3715 */3716 if (has_symlink_leading_path(new_name, strlen(new_name)))3717 return 0;37183719 return EXISTS_IN_WORKTREE;3720 } else if ((errno != ENOENT) && (errno != ENOTDIR)) {3721 return error("%s: %s", new_name, strerror(errno));3722 }3723 return 0;3724}37253726static uintptr_t register_symlink_changes(struct apply_state *state,3727 const char *path,3728 uintptr_t what)3729{3730 struct string_list_item *ent;37313732 ent = string_list_lookup(&state->symlink_changes, path);3733 if (!ent) {3734 ent = string_list_insert(&state->symlink_changes, path);3735 ent->util = (void *)0;3736 }3737 ent->util = (void *)(what | ((uintptr_t)ent->util));3738 return (uintptr_t)ent->util;3739}37403741static uintptr_t check_symlink_changes(struct apply_state *state, const char *path)3742{3743 struct string_list_item *ent;37443745 ent = string_list_lookup(&state->symlink_changes, path);3746 if (!ent)3747 return 0;3748 return (uintptr_t)ent->util;3749}37503751static void prepare_symlink_changes(struct apply_state *state, struct patch *patch)3752{3753 for ( ; patch; patch = patch->next) {3754 if ((patch->old_name && S_ISLNK(patch->old_mode)) &&3755 (patch->is_rename || patch->is_delete))3756 /* the symlink at patch->old_name is removed */3757 register_symlink_changes(state, patch->old_name, SYMLINK_GOES_AWAY);37583759 if (patch->new_name && S_ISLNK(patch->new_mode))3760 /* the symlink at patch->new_name is created or remains */3761 register_symlink_changes(state, patch->new_name, SYMLINK_IN_RESULT);3762 }3763}37643765static int path_is_beyond_symlink_1(struct apply_state *state, struct strbuf *name)3766{3767 do {3768 unsigned int change;37693770 while (--name->len && name->buf[name->len] != '/')3771 ; /* scan backwards */3772 if (!name->len)3773 break;3774 name->buf[name->len] = '\0';3775 change = check_symlink_changes(state, name->buf);3776 if (change & SYMLINK_IN_RESULT)3777 return 1;3778 if (change & SYMLINK_GOES_AWAY)3779 /*3780 * This cannot be "return 0", because we may3781 * see a new one created at a higher level.3782 */3783 continue;37843785 /* otherwise, check the preimage */3786 if (state->check_index) {3787 struct cache_entry *ce;37883789 ce = cache_file_exists(name->buf, name->len, ignore_case);3790 if (ce && S_ISLNK(ce->ce_mode))3791 return 1;3792 } else {3793 struct stat st;3794 if (!lstat(name->buf, &st) && S_ISLNK(st.st_mode))3795 return 1;3796 }3797 } while (1);3798 return 0;3799}38003801static int path_is_beyond_symlink(struct apply_state *state, const char *name_)3802{3803 int ret;3804 struct strbuf name = STRBUF_INIT;38053806 assert(*name_ != '\0');3807 strbuf_addstr(&name, name_);3808 ret = path_is_beyond_symlink_1(state, &name);3809 strbuf_release(&name);38103811 return ret;3812}38133814static void die_on_unsafe_path(struct patch *patch)3815{3816 const char *old_name = NULL;3817 const char *new_name = NULL;3818 if (patch->is_delete)3819 old_name = patch->old_name;3820 else if (!patch->is_new && !patch->is_copy)3821 old_name = patch->old_name;3822 if (!patch->is_delete)3823 new_name = patch->new_name;38243825 if (old_name && !verify_path(old_name))3826 die(_("invalid path '%s'"), old_name);3827 if (new_name && !verify_path(new_name))3828 die(_("invalid path '%s'"), new_name);3829}38303831/*3832 * Check and apply the patch in-core; leave the result in patch->result3833 * for the caller to write it out to the final destination.3834 */3835static int check_patch(struct apply_state *state, struct patch *patch)3836{3837 struct stat st;3838 const char *old_name = patch->old_name;3839 const char *new_name = patch->new_name;3840 const char *name = old_name ? old_name : new_name;3841 struct cache_entry *ce = NULL;3842 struct patch *tpatch;3843 int ok_if_exists;3844 int status;38453846 patch->rejected = 1; /* we will drop this after we succeed */38473848 status = check_preimage(state, patch, &ce, &st);3849 if (status)3850 return status;3851 old_name = patch->old_name;38523853 /*3854 * A type-change diff is always split into a patch to delete3855 * old, immediately followed by a patch to create new (see3856 * diff.c::run_diff()); in such a case it is Ok that the entry3857 * to be deleted by the previous patch is still in the working3858 * tree and in the index.3859 *3860 * A patch to swap-rename between A and B would first rename A3861 * to B and then rename B to A. While applying the first one,3862 * the presence of B should not stop A from getting renamed to3863 * B; ask to_be_deleted() about the later rename. Removal of3864 * B and rename from A to B is handled the same way by asking3865 * was_deleted().3866 */3867 if ((tpatch = in_fn_table(state, new_name)) &&3868 (was_deleted(tpatch) || to_be_deleted(tpatch)))3869 ok_if_exists = 1;3870 else3871 ok_if_exists = 0;38723873 if (new_name &&3874 ((0 < patch->is_new) || patch->is_rename || patch->is_copy)) {3875 int err = check_to_create(state, new_name, ok_if_exists);38763877 if (err && state->threeway) {3878 patch->direct_to_threeway = 1;3879 } else switch (err) {3880 case 0:3881 break; /* happy */3882 case EXISTS_IN_INDEX:3883 return error(_("%s: already exists in index"), new_name);3884 break;3885 case EXISTS_IN_WORKTREE:3886 return error(_("%s: already exists in working directory"),3887 new_name);3888 default:3889 return err;3890 }38913892 if (!patch->new_mode) {3893 if (0 < patch->is_new)3894 patch->new_mode = S_IFREG | 0644;3895 else3896 patch->new_mode = patch->old_mode;3897 }3898 }38993900 if (new_name && old_name) {3901 int same = !strcmp(old_name, new_name);3902 if (!patch->new_mode)3903 patch->new_mode = patch->old_mode;3904 if ((patch->old_mode ^ patch->new_mode) & S_IFMT) {3905 if (same)3906 return error(_("new mode (%o) of %s does not "3907 "match old mode (%o)"),3908 patch->new_mode, new_name,3909 patch->old_mode);3910 else3911 return error(_("new mode (%o) of %s does not "3912 "match old mode (%o) of %s"),3913 patch->new_mode, new_name,3914 patch->old_mode, old_name);3915 }3916 }39173918 if (!state->unsafe_paths)3919 die_on_unsafe_path(patch);39203921 /*3922 * An attempt to read from or delete a path that is beyond a3923 * symbolic link will be prevented by load_patch_target() that3924 * is called at the beginning of apply_data() so we do not3925 * have to worry about a patch marked with "is_delete" bit3926 * here. We however need to make sure that the patch result3927 * is not deposited to a path that is beyond a symbolic link3928 * here.3929 */3930 if (!patch->is_delete && path_is_beyond_symlink(state, patch->new_name))3931 return error(_("affected file '%s' is beyond a symbolic link"),3932 patch->new_name);39333934 if (apply_data(state, patch, &st, ce) < 0)3935 return error(_("%s: patch does not apply"), name);3936 patch->rejected = 0;3937 return 0;3938}39393940static int check_patch_list(struct apply_state *state, struct patch *patch)3941{3942 int err = 0;39433944 prepare_symlink_changes(state, patch);3945 prepare_fn_table(state, patch);3946 while (patch) {3947 if (state->apply_verbosely)3948 say_patch_name(stderr,3949 _("Checking patch %s..."), patch);3950 err |= check_patch(state, patch);3951 patch = patch->next;3952 }3953 return err;3954}39553956/* This function tries to read the sha1 from the current index */3957static int get_current_sha1(const char *path, unsigned char *sha1)3958{3959 int pos;39603961 if (read_cache() < 0)3962 return -1;3963 pos = cache_name_pos(path, strlen(path));3964 if (pos < 0)3965 return -1;3966 hashcpy(sha1, active_cache[pos]->sha1);3967 return 0;3968}39693970static int preimage_sha1_in_gitlink_patch(struct patch *p, unsigned char sha1[20])3971{3972 /*3973 * A usable gitlink patch has only one fragment (hunk) that looks like:3974 * @@ -1 +1 @@3975 * -Subproject commit <old sha1>3976 * +Subproject commit <new sha1>3977 * or3978 * @@ -1 +0,0 @@3979 * -Subproject commit <old sha1>3980 * for a removal patch.3981 */3982 struct fragment *hunk = p->fragments;3983 static const char heading[] = "-Subproject commit ";3984 char *preimage;39853986 if (/* does the patch have only one hunk? */3987 hunk && !hunk->next &&3988 /* is its preimage one line? */3989 hunk->oldpos == 1 && hunk->oldlines == 1 &&3990 /* does preimage begin with the heading? */3991 (preimage = memchr(hunk->patch, '\n', hunk->size)) != NULL &&3992 starts_with(++preimage, heading) &&3993 /* does it record full SHA-1? */3994 !get_sha1_hex(preimage + sizeof(heading) - 1, sha1) &&3995 preimage[sizeof(heading) + 40 - 1] == '\n' &&3996 /* does the abbreviated name on the index line agree with it? */3997 starts_with(preimage + sizeof(heading) - 1, p->old_sha1_prefix))3998 return 0; /* it all looks fine */39994000 /* we may have full object name on the index line */4001 return get_sha1_hex(p->old_sha1_prefix, sha1);4002}40034004/* Build an index that contains the just the files needed for a 3way merge */4005static void build_fake_ancestor(struct patch *list, const char *filename)4006{4007 struct patch *patch;4008 struct index_state result = { NULL };4009 static struct lock_file lock;40104011 /* Once we start supporting the reverse patch, it may be4012 * worth showing the new sha1 prefix, but until then...4013 */4014 for (patch = list; patch; patch = patch->next) {4015 unsigned char sha1[20];4016 struct cache_entry *ce;4017 const char *name;40184019 name = patch->old_name ? patch->old_name : patch->new_name;4020 if (0 < patch->is_new)4021 continue;40224023 if (S_ISGITLINK(patch->old_mode)) {4024 if (!preimage_sha1_in_gitlink_patch(patch, sha1))4025 ; /* ok, the textual part looks sane */4026 else4027 die("sha1 information is lacking or useless for submodule %s",4028 name);4029 } else if (!get_sha1_blob(patch->old_sha1_prefix, sha1)) {4030 ; /* ok */4031 } else if (!patch->lines_added && !patch->lines_deleted) {4032 /* mode-only change: update the current */4033 if (get_current_sha1(patch->old_name, sha1))4034 die("mode change for %s, which is not "4035 "in current HEAD", name);4036 } else4037 die("sha1 information is lacking or useless "4038 "(%s).", name);40394040 ce = make_cache_entry(patch->old_mode, sha1, name, 0, 0);4041 if (!ce)4042 die(_("make_cache_entry failed for path '%s'"), name);4043 if (add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD))4044 die ("Could not add %s to temporary index", name);4045 }40464047 hold_lock_file_for_update(&lock, filename, LOCK_DIE_ON_ERROR);4048 if (write_locked_index(&result, &lock, COMMIT_LOCK))4049 die ("Could not write temporary index to %s", filename);40504051 discard_index(&result);4052}40534054static void stat_patch_list(struct apply_state *state, struct patch *patch)4055{4056 int files, adds, dels;40574058 for (files = adds = dels = 0 ; patch ; patch = patch->next) {4059 files++;4060 adds += patch->lines_added;4061 dels += patch->lines_deleted;4062 show_stats(state, patch);4063 }40644065 print_stat_summary(stdout, files, adds, dels);4066}40674068static void numstat_patch_list(struct apply_state *state,4069 struct patch *patch)4070{4071 for ( ; patch; patch = patch->next) {4072 const char *name;4073 name = patch->new_name ? patch->new_name : patch->old_name;4074 if (patch->is_binary)4075 printf("-\t-\t");4076 else4077 printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);4078 write_name_quoted(name, stdout, state->line_termination);4079 }4080}40814082static void show_file_mode_name(const char *newdelete, unsigned int mode, const char *name)4083{4084 if (mode)4085 printf(" %s mode %06o %s\n", newdelete, mode, name);4086 else4087 printf(" %s %s\n", newdelete, name);4088}40894090static void show_mode_change(struct patch *p, int show_name)4091{4092 if (p->old_mode && p->new_mode && p->old_mode != p->new_mode) {4093 if (show_name)4094 printf(" mode change %06o => %06o %s\n",4095 p->old_mode, p->new_mode, p->new_name);4096 else4097 printf(" mode change %06o => %06o\n",4098 p->old_mode, p->new_mode);4099 }4100}41014102static void show_rename_copy(struct patch *p)4103{4104 const char *renamecopy = p->is_rename ? "rename" : "copy";4105 const char *old, *new;41064107 /* Find common prefix */4108 old = p->old_name;4109 new = p->new_name;4110 while (1) {4111 const char *slash_old, *slash_new;4112 slash_old = strchr(old, '/');4113 slash_new = strchr(new, '/');4114 if (!slash_old ||4115 !slash_new ||4116 slash_old - old != slash_new - new ||4117 memcmp(old, new, slash_new - new))4118 break;4119 old = slash_old + 1;4120 new = slash_new + 1;4121 }4122 /* p->old_name thru old is the common prefix, and old and new4123 * through the end of names are renames4124 */4125 if (old != p->old_name)4126 printf(" %s %.*s{%s => %s} (%d%%)\n", renamecopy,4127 (int)(old - p->old_name), p->old_name,4128 old, new, p->score);4129 else4130 printf(" %s %s => %s (%d%%)\n", renamecopy,4131 p->old_name, p->new_name, p->score);4132 show_mode_change(p, 0);4133}41344135static void summary_patch_list(struct patch *patch)4136{4137 struct patch *p;41384139 for (p = patch; p; p = p->next) {4140 if (p->is_new)4141 show_file_mode_name("create", p->new_mode, p->new_name);4142 else if (p->is_delete)4143 show_file_mode_name("delete", p->old_mode, p->old_name);4144 else {4145 if (p->is_rename || p->is_copy)4146 show_rename_copy(p);4147 else {4148 if (p->score) {4149 printf(" rewrite %s (%d%%)\n",4150 p->new_name, p->score);4151 show_mode_change(p, 0);4152 }4153 else4154 show_mode_change(p, 1);4155 }4156 }4157 }4158}41594160static void patch_stats(struct apply_state *state, struct patch *patch)4161{4162 int lines = patch->lines_added + patch->lines_deleted;41634164 if (lines > state->max_change)4165 state->max_change = lines;4166 if (patch->old_name) {4167 int len = quote_c_style(patch->old_name, NULL, NULL, 0);4168 if (!len)4169 len = strlen(patch->old_name);4170 if (len > state->max_len)4171 state->max_len = len;4172 }4173 if (patch->new_name) {4174 int len = quote_c_style(patch->new_name, NULL, NULL, 0);4175 if (!len)4176 len = strlen(patch->new_name);4177 if (len > state->max_len)4178 state->max_len = len;4179 }4180}41814182static void remove_file(struct apply_state *state, struct patch *patch, int rmdir_empty)4183{4184 if (state->update_index) {4185 if (remove_file_from_cache(patch->old_name) < 0)4186 die(_("unable to remove %s from index"), patch->old_name);4187 }4188 if (!state->cached) {4189 if (!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {4190 remove_path(patch->old_name);4191 }4192 }4193}41944195static void add_index_file(struct apply_state *state,4196 const char *path,4197 unsigned mode,4198 void *buf,4199 unsigned long size)4200{4201 struct stat st;4202 struct cache_entry *ce;4203 int namelen = strlen(path);4204 unsigned ce_size = cache_entry_size(namelen);42054206 if (!state->update_index)4207 return;42084209 ce = xcalloc(1, ce_size);4210 memcpy(ce->name, path, namelen);4211 ce->ce_mode = create_ce_mode(mode);4212 ce->ce_flags = create_ce_flags(0);4213 ce->ce_namelen = namelen;4214 if (S_ISGITLINK(mode)) {4215 const char *s;42164217 if (!skip_prefix(buf, "Subproject commit ", &s) ||4218 get_sha1_hex(s, ce->sha1))4219 die(_("corrupt patch for submodule %s"), path);4220 } else {4221 if (!state->cached) {4222 if (lstat(path, &st) < 0)4223 die_errno(_("unable to stat newly created file '%s'"),4224 path);4225 fill_stat_cache_info(ce, &st);4226 }4227 if (write_sha1_file(buf, size, blob_type, ce->sha1) < 0)4228 die(_("unable to create backing store for newly created file %s"), path);4229 }4230 if (add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) < 0)4231 die(_("unable to add cache entry for %s"), path);4232}42334234static int try_create_file(const char *path, unsigned int mode, const char *buf, unsigned long size)4235{4236 int fd;4237 struct strbuf nbuf = STRBUF_INIT;42384239 if (S_ISGITLINK(mode)) {4240 struct stat st;4241 if (!lstat(path, &st) && S_ISDIR(st.st_mode))4242 return 0;4243 return mkdir(path, 0777);4244 }42454246 if (has_symlinks && S_ISLNK(mode))4247 /* Although buf:size is counted string, it also is NUL4248 * terminated.4249 */4250 return symlink(buf, path);42514252 fd = open(path, O_CREAT | O_EXCL | O_WRONLY, (mode & 0100) ? 0777 : 0666);4253 if (fd < 0)4254 return -1;42554256 if (convert_to_working_tree(path, buf, size, &nbuf)) {4257 size = nbuf.len;4258 buf = nbuf.buf;4259 }4260 write_or_die(fd, buf, size);4261 strbuf_release(&nbuf);42624263 if (close(fd) < 0)4264 die_errno(_("closing file '%s'"), path);4265 return 0;4266}42674268/*4269 * We optimistically assume that the directories exist,4270 * which is true 99% of the time anyway. If they don't,4271 * we create them and try again.4272 */4273static void create_one_file(struct apply_state *state,4274 char *path,4275 unsigned mode,4276 const char *buf,4277 unsigned long size)4278{4279 if (state->cached)4280 return;4281 if (!try_create_file(path, mode, buf, size))4282 return;42834284 if (errno == ENOENT) {4285 if (safe_create_leading_directories(path))4286 return;4287 if (!try_create_file(path, mode, buf, size))4288 return;4289 }42904291 if (errno == EEXIST || errno == EACCES) {4292 /* We may be trying to create a file where a directory4293 * used to be.4294 */4295 struct stat st;4296 if (!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))4297 errno = EEXIST;4298 }42994300 if (errno == EEXIST) {4301 unsigned int nr = getpid();43024303 for (;;) {4304 char newpath[PATH_MAX];4305 mksnpath(newpath, sizeof(newpath), "%s~%u", path, nr);4306 if (!try_create_file(newpath, mode, buf, size)) {4307 if (!rename(newpath, path))4308 return;4309 unlink_or_warn(newpath);4310 break;4311 }4312 if (errno != EEXIST)4313 break;4314 ++nr;4315 }4316 }4317 die_errno(_("unable to write file '%s' mode %o"), path, mode);4318}43194320static void add_conflicted_stages_file(struct apply_state *state,4321 struct patch *patch)4322{4323 int stage, namelen;4324 unsigned ce_size, mode;4325 struct cache_entry *ce;43264327 if (!state->update_index)4328 return;4329 namelen = strlen(patch->new_name);4330 ce_size = cache_entry_size(namelen);4331 mode = patch->new_mode ? patch->new_mode : (S_IFREG | 0644);43324333 remove_file_from_cache(patch->new_name);4334 for (stage = 1; stage < 4; stage++) {4335 if (is_null_oid(&patch->threeway_stage[stage - 1]))4336 continue;4337 ce = xcalloc(1, ce_size);4338 memcpy(ce->name, patch->new_name, namelen);4339 ce->ce_mode = create_ce_mode(mode);4340 ce->ce_flags = create_ce_flags(stage);4341 ce->ce_namelen = namelen;4342 hashcpy(ce->sha1, patch->threeway_stage[stage - 1].hash);4343 if (add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) < 0)4344 die(_("unable to add cache entry for %s"), patch->new_name);4345 }4346}43474348static void create_file(struct apply_state *state, struct patch *patch)4349{4350 char *path = patch->new_name;4351 unsigned mode = patch->new_mode;4352 unsigned long size = patch->resultsize;4353 char *buf = patch->result;43544355 if (!mode)4356 mode = S_IFREG | 0644;4357 create_one_file(state, path, mode, buf, size);43584359 if (patch->conflicted_threeway)4360 add_conflicted_stages_file(state, patch);4361 else4362 add_index_file(state, path, mode, buf, size);4363}43644365/* phase zero is to remove, phase one is to create */4366static void write_out_one_result(struct apply_state *state,4367 struct patch *patch,4368 int phase)4369{4370 if (patch->is_delete > 0) {4371 if (phase == 0)4372 remove_file(state, patch, 1);4373 return;4374 }4375 if (patch->is_new > 0 || patch->is_copy) {4376 if (phase == 1)4377 create_file(state, patch);4378 return;4379 }4380 /*4381 * Rename or modification boils down to the same4382 * thing: remove the old, write the new4383 */4384 if (phase == 0)4385 remove_file(state, patch, patch->is_rename);4386 if (phase == 1)4387 create_file(state, patch);4388}43894390static int write_out_one_reject(struct apply_state *state, struct patch *patch)4391{4392 FILE *rej;4393 char namebuf[PATH_MAX];4394 struct fragment *frag;4395 int cnt = 0;4396 struct strbuf sb = STRBUF_INIT;43974398 for (cnt = 0, frag = patch->fragments; frag; frag = frag->next) {4399 if (!frag->rejected)4400 continue;4401 cnt++;4402 }44034404 if (!cnt) {4405 if (state->apply_verbosely)4406 say_patch_name(stderr,4407 _("Applied patch %s cleanly."), patch);4408 return 0;4409 }44104411 /* This should not happen, because a removal patch that leaves4412 * contents are marked "rejected" at the patch level.4413 */4414 if (!patch->new_name)4415 die(_("internal error"));44164417 /* Say this even without --verbose */4418 strbuf_addf(&sb, Q_("Applying patch %%s with %d reject...",4419 "Applying patch %%s with %d rejects...",4420 cnt),4421 cnt);4422 say_patch_name(stderr, sb.buf, patch);4423 strbuf_release(&sb);44244425 cnt = strlen(patch->new_name);4426 if (ARRAY_SIZE(namebuf) <= cnt + 5) {4427 cnt = ARRAY_SIZE(namebuf) - 5;4428 warning(_("truncating .rej filename to %.*s.rej"),4429 cnt - 1, patch->new_name);4430 }4431 memcpy(namebuf, patch->new_name, cnt);4432 memcpy(namebuf + cnt, ".rej", 5);44334434 rej = fopen(namebuf, "w");4435 if (!rej)4436 return error(_("cannot open %s: %s"), namebuf, strerror(errno));44374438 /* Normal git tools never deal with .rej, so do not pretend4439 * this is a git patch by saying --git or giving extended4440 * headers. While at it, maybe please "kompare" that wants4441 * the trailing TAB and some garbage at the end of line ;-).4442 */4443 fprintf(rej, "diff a/%s b/%s\t(rejected hunks)\n",4444 patch->new_name, patch->new_name);4445 for (cnt = 1, frag = patch->fragments;4446 frag;4447 cnt++, frag = frag->next) {4448 if (!frag->rejected) {4449 fprintf_ln(stderr, _("Hunk #%d applied cleanly."), cnt);4450 continue;4451 }4452 fprintf_ln(stderr, _("Rejected hunk #%d."), cnt);4453 fprintf(rej, "%.*s", frag->size, frag->patch);4454 if (frag->patch[frag->size-1] != '\n')4455 fputc('\n', rej);4456 }4457 fclose(rej);4458 return -1;4459}44604461static int write_out_results(struct apply_state *state, struct patch *list)4462{4463 int phase;4464 int errs = 0;4465 struct patch *l;4466 struct string_list cpath = STRING_LIST_INIT_DUP;44674468 for (phase = 0; phase < 2; phase++) {4469 l = list;4470 while (l) {4471 if (l->rejected)4472 errs = 1;4473 else {4474 write_out_one_result(state, l, phase);4475 if (phase == 1) {4476 if (write_out_one_reject(state, l))4477 errs = 1;4478 if (l->conflicted_threeway) {4479 string_list_append(&cpath, l->new_name);4480 errs = 1;4481 }4482 }4483 }4484 l = l->next;4485 }4486 }44874488 if (cpath.nr) {4489 struct string_list_item *item;44904491 string_list_sort(&cpath);4492 for_each_string_list_item(item, &cpath)4493 fprintf(stderr, "U %s\n", item->string);4494 string_list_clear(&cpath, 0);44954496 rerere(0);4497 }44984499 return errs;4500}45014502static struct lock_file lock_file;45034504#define INACCURATE_EOF (1<<0)4505#define RECOUNT (1<<1)45064507static int apply_patch(struct apply_state *state,4508 int fd,4509 const char *filename,4510 int options)4511{4512 size_t offset;4513 struct strbuf buf = STRBUF_INIT; /* owns the patch text */4514 struct patch *list = NULL, **listp = &list;4515 int skipped_patch = 0;45164517 state->patch_input_file = filename;4518 read_patch_file(&buf, fd);4519 offset = 0;4520 while (offset < buf.len) {4521 struct patch *patch;4522 int nr;45234524 patch = xcalloc(1, sizeof(*patch));4525 patch->inaccurate_eof = !!(options & INACCURATE_EOF);4526 patch->recount = !!(options & RECOUNT);4527 nr = parse_chunk(state, buf.buf + offset, buf.len - offset, patch);4528 if (nr < 0) {4529 free_patch(patch);4530 break;4531 }4532 if (state->apply_in_reverse)4533 reverse_patches(patch);4534 if (use_patch(state, patch)) {4535 patch_stats(state, patch);4536 *listp = patch;4537 listp = &patch->next;4538 }4539 else {4540 if (state->apply_verbosely)4541 say_patch_name(stderr, _("Skipped patch '%s'."), patch);4542 free_patch(patch);4543 skipped_patch++;4544 }4545 offset += nr;4546 }45474548 if (!list && !skipped_patch)4549 die(_("unrecognized input"));45504551 if (state->whitespace_error && (state->ws_error_action == die_on_ws_error))4552 state->apply = 0;45534554 state->update_index = state->check_index && state->apply;4555 if (state->update_index && newfd < 0)4556 newfd = hold_locked_index(state->lock_file, 1);45574558 if (state->check_index) {4559 if (read_cache() < 0)4560 die(_("unable to read index file"));4561 }45624563 if ((state->check || state->apply) &&4564 check_patch_list(state, list) < 0 &&4565 !state->apply_with_reject)4566 exit(1);45674568 if (state->apply && write_out_results(state, list)) {4569 if (state->apply_with_reject)4570 exit(1);4571 /* with --3way, we still need to write the index out */4572 return 1;4573 }45744575 if (state->fake_ancestor)4576 build_fake_ancestor(list, state->fake_ancestor);45774578 if (state->diffstat)4579 stat_patch_list(state, list);45804581 if (state->numstat)4582 numstat_patch_list(state, list);45834584 if (state->summary)4585 summary_patch_list(list);45864587 free_patch_list(list);4588 strbuf_release(&buf);4589 string_list_clear(&state->fn_table, 0);4590 return 0;4591}45924593static void git_apply_config(void)4594{4595 git_config_get_string_const("apply.whitespace", &apply_default_whitespace);4596 git_config_get_string_const("apply.ignorewhitespace", &apply_default_ignorewhitespace);4597 git_config(git_default_config, NULL);4598}45994600static int option_parse_exclude(const struct option *opt,4601 const char *arg, int unset)4602{4603 struct apply_state *state = opt->value;4604 add_name_limit(state, arg, 1);4605 return 0;4606}46074608static int option_parse_include(const struct option *opt,4609 const char *arg, int unset)4610{4611 struct apply_state *state = opt->value;4612 add_name_limit(state, arg, 0);4613 state->has_include = 1;4614 return 0;4615}46164617static int option_parse_p(const struct option *opt,4618 const char *arg,4619 int unset)4620{4621 struct apply_state *state = opt->value;4622 state->p_value = atoi(arg);4623 state->p_value_known = 1;4624 return 0;4625}46264627static int option_parse_space_change(const struct option *opt,4628 const char *arg, int unset)4629{4630 struct apply_state *state = opt->value;4631 if (unset)4632 state->ws_ignore_action = ignore_ws_none;4633 else4634 state->ws_ignore_action = ignore_ws_change;4635 return 0;4636}46374638static int option_parse_whitespace(const struct option *opt,4639 const char *arg, int unset)4640{4641 struct apply_state *state = opt->value;4642 state->whitespace_option = arg;4643 parse_whitespace_option(state, arg);4644 return 0;4645}46464647static int option_parse_directory(const struct option *opt,4648 const char *arg, int unset)4649{4650 struct apply_state *state = opt->value;4651 strbuf_reset(&state->root);4652 strbuf_addstr(&state->root, arg);4653 strbuf_complete(&state->root, '/');4654 return 0;4655}46564657static void init_apply_state(struct apply_state *state,4658 const char *prefix,4659 struct lock_file *lock_file)4660{4661 memset(state, 0, sizeof(*state));4662 state->prefix = prefix;4663 state->prefix_length = state->prefix ? strlen(state->prefix) : 0;4664 state->lock_file = lock_file;4665 state->apply = 1;4666 state->line_termination = '\n';4667 state->p_value = 1;4668 state->p_context = UINT_MAX;4669 state->squelch_whitespace_errors = 5;4670 state->ws_error_action = warn_on_ws_error;4671 state->ws_ignore_action = ignore_ws_none;4672 state->linenr = 1;4673 strbuf_init(&state->root, 0);46744675 git_apply_config();4676 if (apply_default_whitespace)4677 parse_whitespace_option(state, apply_default_whitespace);4678 if (apply_default_ignorewhitespace)4679 parse_ignorewhitespace_option(state, apply_default_ignorewhitespace);4680}46814682static void clear_apply_state(struct apply_state *state)4683{4684 string_list_clear(&state->limit_by_name, 0);4685 string_list_clear(&state->symlink_changes, 0);4686 strbuf_release(&state->root);46874688 /* &state->fn_table is cleared at the end of apply_patch() */4689}46904691static void check_apply_state(struct apply_state *state, int force_apply)4692{4693 int is_not_gitdir = !startup_info->have_repository;46944695 if (state->apply_with_reject && state->threeway)4696 die("--reject and --3way cannot be used together.");4697 if (state->cached && state->threeway)4698 die("--cached and --3way cannot be used together.");4699 if (state->threeway) {4700 if (is_not_gitdir)4701 die(_("--3way outside a repository"));4702 state->check_index = 1;4703 }4704 if (state->apply_with_reject)4705 state->apply = state->apply_verbosely = 1;4706 if (!force_apply && (state->diffstat || state->numstat || state->summary || state->check || state->fake_ancestor))4707 state->apply = 0;4708 if (state->check_index && is_not_gitdir)4709 die(_("--index outside a repository"));4710 if (state->cached) {4711 if (is_not_gitdir)4712 die(_("--cached outside a repository"));4713 state->check_index = 1;4714 }4715 if (state->check_index)4716 state->unsafe_paths = 0;4717 if (!state->lock_file)4718 die("BUG: state->lock_file should not be NULL");4719}47204721static int apply_all_patches(struct apply_state *state,4722 int argc,4723 const char **argv,4724 int options)4725{4726 int i;4727 int errs = 0;4728 int read_stdin = 1;47294730 for (i = 0; i < argc; i++) {4731 const char *arg = argv[i];4732 int fd;47334734 if (!strcmp(arg, "-")) {4735 errs |= apply_patch(state, 0, "<stdin>", options);4736 read_stdin = 0;4737 continue;4738 } else if (0 < state->prefix_length)4739 arg = prefix_filename(state->prefix,4740 state->prefix_length,4741 arg);47424743 fd = open(arg, O_RDONLY);4744 if (fd < 0)4745 die_errno(_("can't open patch '%s'"), arg);4746 read_stdin = 0;4747 set_default_whitespace_mode(state);4748 errs |= apply_patch(state, fd, arg, options);4749 close(fd);4750 }4751 set_default_whitespace_mode(state);4752 if (read_stdin)4753 errs |= apply_patch(state, 0, "<stdin>", options);47544755 if (state->whitespace_error) {4756 if (state->squelch_whitespace_errors &&4757 state->squelch_whitespace_errors < state->whitespace_error) {4758 int squelched =4759 state->whitespace_error - state->squelch_whitespace_errors;4760 warning(Q_("squelched %d whitespace error",4761 "squelched %d whitespace errors",4762 squelched),4763 squelched);4764 }4765 if (state->ws_error_action == die_on_ws_error)4766 die(Q_("%d line adds whitespace errors.",4767 "%d lines add whitespace errors.",4768 state->whitespace_error),4769 state->whitespace_error);4770 if (state->applied_after_fixing_ws && state->apply)4771 warning("%d line%s applied after"4772 " fixing whitespace errors.",4773 state->applied_after_fixing_ws,4774 state->applied_after_fixing_ws == 1 ? "" : "s");4775 else if (state->whitespace_error)4776 warning(Q_("%d line adds whitespace errors.",4777 "%d lines add whitespace errors.",4778 state->whitespace_error),4779 state->whitespace_error);4780 }47814782 if (state->update_index) {4783 if (write_locked_index(&the_index, state->lock_file, COMMIT_LOCK))4784 die(_("Unable to write new index file"));4785 }47864787 return !!errs;4788}47894790int cmd_apply(int argc, const char **argv, const char *prefix)4791{4792 int force_apply = 0;4793 int options = 0;4794 int ret;4795 struct apply_state state;47964797 struct option builtin_apply_options[] = {4798 { OPTION_CALLBACK, 0, "exclude", &state, N_("path"),4799 N_("don't apply changes matching the given path"),4800 0, option_parse_exclude },4801 { OPTION_CALLBACK, 0, "include", &state, N_("path"),4802 N_("apply changes matching the given path"),4803 0, option_parse_include },4804 { OPTION_CALLBACK, 'p', NULL, &state, N_("num"),4805 N_("remove <num> leading slashes from traditional diff paths"),4806 0, option_parse_p },4807 OPT_BOOL(0, "no-add", &state.no_add,4808 N_("ignore additions made by the patch")),4809 OPT_BOOL(0, "stat", &state.diffstat,4810 N_("instead of applying the patch, output diffstat for the input")),4811 OPT_NOOP_NOARG(0, "allow-binary-replacement"),4812 OPT_NOOP_NOARG(0, "binary"),4813 OPT_BOOL(0, "numstat", &state.numstat,4814 N_("show number of added and deleted lines in decimal notation")),4815 OPT_BOOL(0, "summary", &state.summary,4816 N_("instead of applying the patch, output a summary for the input")),4817 OPT_BOOL(0, "check", &state.check,4818 N_("instead of applying the patch, see if the patch is applicable")),4819 OPT_BOOL(0, "index", &state.check_index,4820 N_("make sure the patch is applicable to the current index")),4821 OPT_BOOL(0, "cached", &state.cached,4822 N_("apply a patch without touching the working tree")),4823 OPT_BOOL(0, "unsafe-paths", &state.unsafe_paths,4824 N_("accept a patch that touches outside the working area")),4825 OPT_BOOL(0, "apply", &force_apply,4826 N_("also apply the patch (use with --stat/--summary/--check)")),4827 OPT_BOOL('3', "3way", &state.threeway,4828 N_( "attempt three-way merge if a patch does not apply")),4829 OPT_FILENAME(0, "build-fake-ancestor", &state.fake_ancestor,4830 N_("build a temporary index based on embedded index information")),4831 /* Think twice before adding "--nul" synonym to this */4832 OPT_SET_INT('z', NULL, &state.line_termination,4833 N_("paths are separated with NUL character"), '\0'),4834 OPT_INTEGER('C', NULL, &state.p_context,4835 N_("ensure at least <n> lines of context match")),4836 { OPTION_CALLBACK, 0, "whitespace", &state, N_("action"),4837 N_("detect new or modified lines that have whitespace errors"),4838 0, option_parse_whitespace },4839 { OPTION_CALLBACK, 0, "ignore-space-change", &state, NULL,4840 N_("ignore changes in whitespace when finding context"),4841 PARSE_OPT_NOARG, option_parse_space_change },4842 { OPTION_CALLBACK, 0, "ignore-whitespace", &state, NULL,4843 N_("ignore changes in whitespace when finding context"),4844 PARSE_OPT_NOARG, option_parse_space_change },4845 OPT_BOOL('R', "reverse", &state.apply_in_reverse,4846 N_("apply the patch in reverse")),4847 OPT_BOOL(0, "unidiff-zero", &state.unidiff_zero,4848 N_("don't expect at least one line of context")),4849 OPT_BOOL(0, "reject", &state.apply_with_reject,4850 N_("leave the rejected hunks in corresponding *.rej files")),4851 OPT_BOOL(0, "allow-overlap", &state.allow_overlap,4852 N_("allow overlapping hunks")),4853 OPT__VERBOSE(&state.apply_verbosely, N_("be verbose")),4854 OPT_BIT(0, "inaccurate-eof", &options,4855 N_("tolerate incorrectly detected missing new-line at the end of file"),4856 INACCURATE_EOF),4857 OPT_BIT(0, "recount", &options,4858 N_("do not trust the line counts in the hunk headers"),4859 RECOUNT),4860 { OPTION_CALLBACK, 0, "directory", &state, N_("root"),4861 N_("prepend <root> to all filenames"),4862 0, option_parse_directory },4863 OPT_END()4864 };48654866 init_apply_state(&state, prefix, &lock_file);48674868 argc = parse_options(argc, argv, state.prefix, builtin_apply_options,4869 apply_usage, 0);48704871 check_apply_state(&state, force_apply);48724873 ret = apply_all_patches(&state, argc, argv, options);48744875 clear_apply_state(&state);48764877 return ret;4878}