1/* 2 * apply.c 3 * 4 * Copyright (C) Linus Torvalds, 2005 5 * 6 * This applies patches on top of some (arbitrary) version of the SCM. 7 * 8 */ 9#include "cache.h" 10#include "lockfile.h" 11#include "cache-tree.h" 12#include "quote.h" 13#include "blob.h" 14#include "delta.h" 15#include "builtin.h" 16#include "string-list.h" 17#include "dir.h" 18#include "diff.h" 19#include "parse-options.h" 20#include "xdiff-interface.h" 21#include "ll-merge.h" 22#include "rerere.h" 23 24struct apply_state { 25 const char *prefix; 26 int prefix_length; 27 28 /* These control what gets looked at and modified */ 29 int apply; /* this is not a dry-run */ 30 int cached; /* apply to the index only */ 31 int check; /* preimage must match working tree, don't actually apply */ 32 int check_index; /* preimage must match the indexed version */ 33 int update_index; /* check_index && apply */ 34 35 /* These control cosmetic aspect of the output */ 36 int diffstat; /* just show a diffstat, and don't actually apply */ 37 int numstat; /* just show a numeric diffstat, and don't actually apply */ 38 int summary; /* just report creation, deletion, etc, and don't actually apply */ 39 40 /* These boolean parameters control how the apply is done */ 41 int allow_overlap; 42 int apply_in_reverse; 43 int apply_with_reject; 44 int apply_verbosely; 45 int no_add; 46 int threeway; 47 int unidiff_zero; 48 int unsafe_paths; 49 50 /* Other non boolean parameters */ 51 const char *fake_ancestor; 52 const char *patch_input_file; 53 int line_termination; 54 struct strbuf root; 55 int p_value; 56 int p_value_known; 57 unsigned int p_context; 58 59 /* Exclude and include path parameters */ 60 struct string_list limit_by_name; 61 int has_include; 62 63 /* These control whitespace errors */ 64 const char *whitespace_option; 65 int whitespace_error; 66}; 67 68static int newfd = -1; 69 70static const char * const apply_usage[] = { 71 N_("git apply [<options>] [<patch>...]"), 72 NULL 73}; 74 75static enum ws_error_action { 76 nowarn_ws_error, 77 warn_on_ws_error, 78 die_on_ws_error, 79 correct_ws_error 80} ws_error_action = warn_on_ws_error; 81static int squelch_whitespace_errors = 5; 82static int applied_after_fixing_ws; 83 84static enum ws_ignore { 85 ignore_ws_none, 86 ignore_ws_change 87} ws_ignore_action = ignore_ws_none; 88 89 90static void parse_whitespace_option(const char *option) 91{ 92 if (!option) { 93 ws_error_action = warn_on_ws_error; 94 return; 95 } 96 if (!strcmp(option, "warn")) { 97 ws_error_action = warn_on_ws_error; 98 return; 99 } 100 if (!strcmp(option, "nowarn")) { 101 ws_error_action = nowarn_ws_error; 102 return; 103 } 104 if (!strcmp(option, "error")) { 105 ws_error_action = die_on_ws_error; 106 return; 107 } 108 if (!strcmp(option, "error-all")) { 109 ws_error_action = die_on_ws_error; 110 squelch_whitespace_errors = 0; 111 return; 112 } 113 if (!strcmp(option, "strip") || !strcmp(option, "fix")) { 114 ws_error_action = correct_ws_error; 115 return; 116 } 117 die(_("unrecognized whitespace option '%s'"), option); 118} 119 120static void parse_ignorewhitespace_option(const char *option) 121{ 122 if (!option || !strcmp(option, "no") || 123 !strcmp(option, "false") || !strcmp(option, "never") || 124 !strcmp(option, "none")) { 125 ws_ignore_action = ignore_ws_none; 126 return; 127 } 128 if (!strcmp(option, "change")) { 129 ws_ignore_action = ignore_ws_change; 130 return; 131 } 132 die(_("unrecognized whitespace ignore option '%s'"), option); 133} 134 135static void set_default_whitespace_mode(struct apply_state *state, 136 const char *whitespace_option) 137{ 138 if (!whitespace_option && !apply_default_whitespace) 139 ws_error_action = (state->apply ? warn_on_ws_error : nowarn_ws_error); 140} 141 142/* 143 * For "diff-stat" like behaviour, we keep track of the biggest change 144 * we've seen, and the longest filename. That allows us to do simple 145 * scaling. 146 */ 147static int max_change, max_len; 148 149/* 150 * Various "current state", notably line numbers and what 151 * file (and how) we're patching right now.. The "is_xxxx" 152 * things are flags, where -1 means "don't know yet". 153 */ 154static int state_linenr = 1; 155 156/* 157 * This represents one "hunk" from a patch, starting with 158 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The 159 * patch text is pointed at by patch, and its byte length 160 * is stored in size. leading and trailing are the number 161 * of context lines. 162 */ 163struct fragment { 164 unsigned long leading, trailing; 165 unsigned long oldpos, oldlines; 166 unsigned long newpos, newlines; 167 /* 168 * 'patch' is usually borrowed from buf in apply_patch(), 169 * but some codepaths store an allocated buffer. 170 */ 171 const char *patch; 172 unsigned free_patch:1, 173 rejected:1; 174 int size; 175 int linenr; 176 struct fragment *next; 177}; 178 179/* 180 * When dealing with a binary patch, we reuse "leading" field 181 * to store the type of the binary hunk, either deflated "delta" 182 * or deflated "literal". 183 */ 184#define binary_patch_method leading 185#define BINARY_DELTA_DEFLATED 1 186#define BINARY_LITERAL_DEFLATED 2 187 188/* 189 * This represents a "patch" to a file, both metainfo changes 190 * such as creation/deletion, filemode and content changes represented 191 * as a series of fragments. 192 */ 193struct patch { 194 char *new_name, *old_name, *def_name; 195 unsigned int old_mode, new_mode; 196 int is_new, is_delete; /* -1 = unknown, 0 = false, 1 = true */ 197 int rejected; 198 unsigned ws_rule; 199 int lines_added, lines_deleted; 200 int score; 201 unsigned int is_toplevel_relative:1; 202 unsigned int inaccurate_eof:1; 203 unsigned int is_binary:1; 204 unsigned int is_copy:1; 205 unsigned int is_rename:1; 206 unsigned int recount:1; 207 unsigned int conflicted_threeway:1; 208 unsigned int direct_to_threeway:1; 209 struct fragment *fragments; 210 char *result; 211 size_t resultsize; 212 char old_sha1_prefix[41]; 213 char new_sha1_prefix[41]; 214 struct patch *next; 215 216 /* three-way fallback result */ 217 struct object_id threeway_stage[3]; 218}; 219 220static void free_fragment_list(struct fragment *list) 221{ 222 while (list) { 223 struct fragment *next = list->next; 224 if (list->free_patch) 225 free((char *)list->patch); 226 free(list); 227 list = next; 228 } 229} 230 231static void free_patch(struct patch *patch) 232{ 233 free_fragment_list(patch->fragments); 234 free(patch->def_name); 235 free(patch->old_name); 236 free(patch->new_name); 237 free(patch->result); 238 free(patch); 239} 240 241static void free_patch_list(struct patch *list) 242{ 243 while (list) { 244 struct patch *next = list->next; 245 free_patch(list); 246 list = next; 247 } 248} 249 250/* 251 * A line in a file, len-bytes long (includes the terminating LF, 252 * except for an incomplete line at the end if the file ends with 253 * one), and its contents hashes to 'hash'. 254 */ 255struct line { 256 size_t len; 257 unsigned hash : 24; 258 unsigned flag : 8; 259#define LINE_COMMON 1 260#define LINE_PATCHED 2 261}; 262 263/* 264 * This represents a "file", which is an array of "lines". 265 */ 266struct image { 267 char *buf; 268 size_t len; 269 size_t nr; 270 size_t alloc; 271 struct line *line_allocated; 272 struct line *line; 273}; 274 275/* 276 * Records filenames that have been touched, in order to handle 277 * the case where more than one patches touch the same file. 278 */ 279 280static struct string_list fn_table; 281 282static uint32_t hash_line(const char *cp, size_t len) 283{ 284 size_t i; 285 uint32_t h; 286 for (i = 0, h = 0; i < len; i++) { 287 if (!isspace(cp[i])) { 288 h = h * 3 + (cp[i] & 0xff); 289 } 290 } 291 return h; 292} 293 294/* 295 * Compare lines s1 of length n1 and s2 of length n2, ignoring 296 * whitespace difference. Returns 1 if they match, 0 otherwise 297 */ 298static int fuzzy_matchlines(const char *s1, size_t n1, 299 const char *s2, size_t n2) 300{ 301 const char *last1 = s1 + n1 - 1; 302 const char *last2 = s2 + n2 - 1; 303 int result = 0; 304 305 /* ignore line endings */ 306 while ((*last1 == '\r') || (*last1 == '\n')) 307 last1--; 308 while ((*last2 == '\r') || (*last2 == '\n')) 309 last2--; 310 311 /* skip leading whitespaces, if both begin with whitespace */ 312 if (s1 <= last1 && s2 <= last2 && isspace(*s1) && isspace(*s2)) { 313 while (isspace(*s1) && (s1 <= last1)) 314 s1++; 315 while (isspace(*s2) && (s2 <= last2)) 316 s2++; 317 } 318 /* early return if both lines are empty */ 319 if ((s1 > last1) && (s2 > last2)) 320 return 1; 321 while (!result) { 322 result = *s1++ - *s2++; 323 /* 324 * Skip whitespace inside. We check for whitespace on 325 * both buffers because we don't want "a b" to match 326 * "ab" 327 */ 328 if (isspace(*s1) && isspace(*s2)) { 329 while (isspace(*s1) && s1 <= last1) 330 s1++; 331 while (isspace(*s2) && s2 <= last2) 332 s2++; 333 } 334 /* 335 * If we reached the end on one side only, 336 * lines don't match 337 */ 338 if ( 339 ((s2 > last2) && (s1 <= last1)) || 340 ((s1 > last1) && (s2 <= last2))) 341 return 0; 342 if ((s1 > last1) && (s2 > last2)) 343 break; 344 } 345 346 return !result; 347} 348 349static void add_line_info(struct image *img, const char *bol, size_t len, unsigned flag) 350{ 351 ALLOC_GROW(img->line_allocated, img->nr + 1, img->alloc); 352 img->line_allocated[img->nr].len = len; 353 img->line_allocated[img->nr].hash = hash_line(bol, len); 354 img->line_allocated[img->nr].flag = flag; 355 img->nr++; 356} 357 358/* 359 * "buf" has the file contents to be patched (read from various sources). 360 * attach it to "image" and add line-based index to it. 361 * "image" now owns the "buf". 362 */ 363static void prepare_image(struct image *image, char *buf, size_t len, 364 int prepare_linetable) 365{ 366 const char *cp, *ep; 367 368 memset(image, 0, sizeof(*image)); 369 image->buf = buf; 370 image->len = len; 371 372 if (!prepare_linetable) 373 return; 374 375 ep = image->buf + image->len; 376 cp = image->buf; 377 while (cp < ep) { 378 const char *next; 379 for (next = cp; next < ep && *next != '\n'; next++) 380 ; 381 if (next < ep) 382 next++; 383 add_line_info(image, cp, next - cp, 0); 384 cp = next; 385 } 386 image->line = image->line_allocated; 387} 388 389static void clear_image(struct image *image) 390{ 391 free(image->buf); 392 free(image->line_allocated); 393 memset(image, 0, sizeof(*image)); 394} 395 396/* fmt must contain _one_ %s and no other substitution */ 397static void say_patch_name(FILE *output, const char *fmt, struct patch *patch) 398{ 399 struct strbuf sb = STRBUF_INIT; 400 401 if (patch->old_name && patch->new_name && 402 strcmp(patch->old_name, patch->new_name)) { 403 quote_c_style(patch->old_name, &sb, NULL, 0); 404 strbuf_addstr(&sb, " => "); 405 quote_c_style(patch->new_name, &sb, NULL, 0); 406 } else { 407 const char *n = patch->new_name; 408 if (!n) 409 n = patch->old_name; 410 quote_c_style(n, &sb, NULL, 0); 411 } 412 fprintf(output, fmt, sb.buf); 413 fputc('\n', output); 414 strbuf_release(&sb); 415} 416 417#define SLOP (16) 418 419static void read_patch_file(struct strbuf *sb, int fd) 420{ 421 if (strbuf_read(sb, fd, 0) < 0) 422 die_errno("git apply: failed to read"); 423 424 /* 425 * Make sure that we have some slop in the buffer 426 * so that we can do speculative "memcmp" etc, and 427 * see to it that it is NUL-filled. 428 */ 429 strbuf_grow(sb, SLOP); 430 memset(sb->buf + sb->len, 0, SLOP); 431} 432 433static unsigned long linelen(const char *buffer, unsigned long size) 434{ 435 unsigned long len = 0; 436 while (size--) { 437 len++; 438 if (*buffer++ == '\n') 439 break; 440 } 441 return len; 442} 443 444static int is_dev_null(const char *str) 445{ 446 return skip_prefix(str, "/dev/null", &str) && isspace(*str); 447} 448 449#define TERM_SPACE 1 450#define TERM_TAB 2 451 452static int name_terminate(const char *name, int namelen, int c, int terminate) 453{ 454 if (c == ' ' && !(terminate & TERM_SPACE)) 455 return 0; 456 if (c == '\t' && !(terminate & TERM_TAB)) 457 return 0; 458 459 return 1; 460} 461 462/* remove double slashes to make --index work with such filenames */ 463static char *squash_slash(char *name) 464{ 465 int i = 0, j = 0; 466 467 if (!name) 468 return NULL; 469 470 while (name[i]) { 471 if ((name[j++] = name[i++]) == '/') 472 while (name[i] == '/') 473 i++; 474 } 475 name[j] = '\0'; 476 return name; 477} 478 479static char *find_name_gnu(struct apply_state *state, 480 const char *line, 481 const char *def, 482 int p_value) 483{ 484 struct strbuf name = STRBUF_INIT; 485 char *cp; 486 487 /* 488 * Proposed "new-style" GNU patch/diff format; see 489 * http://marc.info/?l=git&m=112927316408690&w=2 490 */ 491 if (unquote_c_style(&name, line, NULL)) { 492 strbuf_release(&name); 493 return NULL; 494 } 495 496 for (cp = name.buf; p_value; p_value--) { 497 cp = strchr(cp, '/'); 498 if (!cp) { 499 strbuf_release(&name); 500 return NULL; 501 } 502 cp++; 503 } 504 505 strbuf_remove(&name, 0, cp - name.buf); 506 if (state->root.len) 507 strbuf_insert(&name, 0, state->root.buf, state->root.len); 508 return squash_slash(strbuf_detach(&name, NULL)); 509} 510 511static size_t sane_tz_len(const char *line, size_t len) 512{ 513 const char *tz, *p; 514 515 if (len < strlen(" +0500") || line[len-strlen(" +0500")] != ' ') 516 return 0; 517 tz = line + len - strlen(" +0500"); 518 519 if (tz[1] != '+' && tz[1] != '-') 520 return 0; 521 522 for (p = tz + 2; p != line + len; p++) 523 if (!isdigit(*p)) 524 return 0; 525 526 return line + len - tz; 527} 528 529static size_t tz_with_colon_len(const char *line, size_t len) 530{ 531 const char *tz, *p; 532 533 if (len < strlen(" +08:00") || line[len - strlen(":00")] != ':') 534 return 0; 535 tz = line + len - strlen(" +08:00"); 536 537 if (tz[0] != ' ' || (tz[1] != '+' && tz[1] != '-')) 538 return 0; 539 p = tz + 2; 540 if (!isdigit(*p++) || !isdigit(*p++) || *p++ != ':' || 541 !isdigit(*p++) || !isdigit(*p++)) 542 return 0; 543 544 return line + len - tz; 545} 546 547static size_t date_len(const char *line, size_t len) 548{ 549 const char *date, *p; 550 551 if (len < strlen("72-02-05") || line[len-strlen("-05")] != '-') 552 return 0; 553 p = date = line + len - strlen("72-02-05"); 554 555 if (!isdigit(*p++) || !isdigit(*p++) || *p++ != '-' || 556 !isdigit(*p++) || !isdigit(*p++) || *p++ != '-' || 557 !isdigit(*p++) || !isdigit(*p++)) /* Not a date. */ 558 return 0; 559 560 if (date - line >= strlen("19") && 561 isdigit(date[-1]) && isdigit(date[-2])) /* 4-digit year */ 562 date -= strlen("19"); 563 564 return line + len - date; 565} 566 567static size_t short_time_len(const char *line, size_t len) 568{ 569 const char *time, *p; 570 571 if (len < strlen(" 07:01:32") || line[len-strlen(":32")] != ':') 572 return 0; 573 p = time = line + len - strlen(" 07:01:32"); 574 575 /* Permit 1-digit hours? */ 576 if (*p++ != ' ' || 577 !isdigit(*p++) || !isdigit(*p++) || *p++ != ':' || 578 !isdigit(*p++) || !isdigit(*p++) || *p++ != ':' || 579 !isdigit(*p++) || !isdigit(*p++)) /* Not a time. */ 580 return 0; 581 582 return line + len - time; 583} 584 585static size_t fractional_time_len(const char *line, size_t len) 586{ 587 const char *p; 588 size_t n; 589 590 /* Expected format: 19:41:17.620000023 */ 591 if (!len || !isdigit(line[len - 1])) 592 return 0; 593 p = line + len - 1; 594 595 /* Fractional seconds. */ 596 while (p > line && isdigit(*p)) 597 p--; 598 if (*p != '.') 599 return 0; 600 601 /* Hours, minutes, and whole seconds. */ 602 n = short_time_len(line, p - line); 603 if (!n) 604 return 0; 605 606 return line + len - p + n; 607} 608 609static size_t trailing_spaces_len(const char *line, size_t len) 610{ 611 const char *p; 612 613 /* Expected format: ' ' x (1 or more) */ 614 if (!len || line[len - 1] != ' ') 615 return 0; 616 617 p = line + len; 618 while (p != line) { 619 p--; 620 if (*p != ' ') 621 return line + len - (p + 1); 622 } 623 624 /* All spaces! */ 625 return len; 626} 627 628static size_t diff_timestamp_len(const char *line, size_t len) 629{ 630 const char *end = line + len; 631 size_t n; 632 633 /* 634 * Posix: 2010-07-05 19:41:17 635 * GNU: 2010-07-05 19:41:17.620000023 -0500 636 */ 637 638 if (!isdigit(end[-1])) 639 return 0; 640 641 n = sane_tz_len(line, end - line); 642 if (!n) 643 n = tz_with_colon_len(line, end - line); 644 end -= n; 645 646 n = short_time_len(line, end - line); 647 if (!n) 648 n = fractional_time_len(line, end - line); 649 end -= n; 650 651 n = date_len(line, end - line); 652 if (!n) /* No date. Too bad. */ 653 return 0; 654 end -= n; 655 656 if (end == line) /* No space before date. */ 657 return 0; 658 if (end[-1] == '\t') { /* Success! */ 659 end--; 660 return line + len - end; 661 } 662 if (end[-1] != ' ') /* No space before date. */ 663 return 0; 664 665 /* Whitespace damage. */ 666 end -= trailing_spaces_len(line, end - line); 667 return line + len - end; 668} 669 670static char *find_name_common(struct apply_state *state, 671 const char *line, 672 const char *def, 673 int p_value, 674 const char *end, 675 int terminate) 676{ 677 int len; 678 const char *start = NULL; 679 680 if (p_value == 0) 681 start = line; 682 while (line != end) { 683 char c = *line; 684 685 if (!end && isspace(c)) { 686 if (c == '\n') 687 break; 688 if (name_terminate(start, line-start, c, terminate)) 689 break; 690 } 691 line++; 692 if (c == '/' && !--p_value) 693 start = line; 694 } 695 if (!start) 696 return squash_slash(xstrdup_or_null(def)); 697 len = line - start; 698 if (!len) 699 return squash_slash(xstrdup_or_null(def)); 700 701 /* 702 * Generally we prefer the shorter name, especially 703 * if the other one is just a variation of that with 704 * something else tacked on to the end (ie "file.orig" 705 * or "file~"). 706 */ 707 if (def) { 708 int deflen = strlen(def); 709 if (deflen < len && !strncmp(start, def, deflen)) 710 return squash_slash(xstrdup(def)); 711 } 712 713 if (state->root.len) { 714 char *ret = xstrfmt("%s%.*s", state->root.buf, len, start); 715 return squash_slash(ret); 716 } 717 718 return squash_slash(xmemdupz(start, len)); 719} 720 721static char *find_name(struct apply_state *state, 722 const char *line, 723 char *def, 724 int p_value, 725 int terminate) 726{ 727 if (*line == '"') { 728 char *name = find_name_gnu(state, line, def, p_value); 729 if (name) 730 return name; 731 } 732 733 return find_name_common(state, line, def, p_value, NULL, terminate); 734} 735 736static char *find_name_traditional(struct apply_state *state, 737 const char *line, 738 char *def, 739 int p_value) 740{ 741 size_t len; 742 size_t date_len; 743 744 if (*line == '"') { 745 char *name = find_name_gnu(state, line, def, p_value); 746 if (name) 747 return name; 748 } 749 750 len = strchrnul(line, '\n') - line; 751 date_len = diff_timestamp_len(line, len); 752 if (!date_len) 753 return find_name_common(state, line, def, p_value, NULL, TERM_TAB); 754 len -= date_len; 755 756 return find_name_common(state, line, def, p_value, line + len, 0); 757} 758 759static int count_slashes(const char *cp) 760{ 761 int cnt = 0; 762 char ch; 763 764 while ((ch = *cp++)) 765 if (ch == '/') 766 cnt++; 767 return cnt; 768} 769 770/* 771 * Given the string after "--- " or "+++ ", guess the appropriate 772 * p_value for the given patch. 773 */ 774static int guess_p_value(struct apply_state *state, const char *nameline) 775{ 776 char *name, *cp; 777 int val = -1; 778 779 if (is_dev_null(nameline)) 780 return -1; 781 name = find_name_traditional(state, nameline, NULL, 0); 782 if (!name) 783 return -1; 784 cp = strchr(name, '/'); 785 if (!cp) 786 val = 0; 787 else if (state->prefix) { 788 /* 789 * Does it begin with "a/$our-prefix" and such? Then this is 790 * very likely to apply to our directory. 791 */ 792 if (!strncmp(name, state->prefix, state->prefix_length)) 793 val = count_slashes(state->prefix); 794 else { 795 cp++; 796 if (!strncmp(cp, state->prefix, state->prefix_length)) 797 val = count_slashes(state->prefix) + 1; 798 } 799 } 800 free(name); 801 return val; 802} 803 804/* 805 * Does the ---/+++ line have the POSIX timestamp after the last HT? 806 * GNU diff puts epoch there to signal a creation/deletion event. Is 807 * this such a timestamp? 808 */ 809static int has_epoch_timestamp(const char *nameline) 810{ 811 /* 812 * We are only interested in epoch timestamp; any non-zero 813 * fraction cannot be one, hence "(\.0+)?" in the regexp below. 814 * For the same reason, the date must be either 1969-12-31 or 815 * 1970-01-01, and the seconds part must be "00". 816 */ 817 const char stamp_regexp[] = 818 "^(1969-12-31|1970-01-01)" 819 " " 820 "[0-2][0-9]:[0-5][0-9]:00(\\.0+)?" 821 " " 822 "([-+][0-2][0-9]:?[0-5][0-9])\n"; 823 const char *timestamp = NULL, *cp, *colon; 824 static regex_t *stamp; 825 regmatch_t m[10]; 826 int zoneoffset; 827 int hourminute; 828 int status; 829 830 for (cp = nameline; *cp != '\n'; cp++) { 831 if (*cp == '\t') 832 timestamp = cp + 1; 833 } 834 if (!timestamp) 835 return 0; 836 if (!stamp) { 837 stamp = xmalloc(sizeof(*stamp)); 838 if (regcomp(stamp, stamp_regexp, REG_EXTENDED)) { 839 warning(_("Cannot prepare timestamp regexp %s"), 840 stamp_regexp); 841 return 0; 842 } 843 } 844 845 status = regexec(stamp, timestamp, ARRAY_SIZE(m), m, 0); 846 if (status) { 847 if (status != REG_NOMATCH) 848 warning(_("regexec returned %d for input: %s"), 849 status, timestamp); 850 return 0; 851 } 852 853 zoneoffset = strtol(timestamp + m[3].rm_so + 1, (char **) &colon, 10); 854 if (*colon == ':') 855 zoneoffset = zoneoffset * 60 + strtol(colon + 1, NULL, 10); 856 else 857 zoneoffset = (zoneoffset / 100) * 60 + (zoneoffset % 100); 858 if (timestamp[m[3].rm_so] == '-') 859 zoneoffset = -zoneoffset; 860 861 /* 862 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31 863 * (west of GMT) or 1970-01-01 (east of GMT) 864 */ 865 if ((zoneoffset < 0 && memcmp(timestamp, "1969-12-31", 10)) || 866 (0 <= zoneoffset && memcmp(timestamp, "1970-01-01", 10))) 867 return 0; 868 869 hourminute = (strtol(timestamp + 11, NULL, 10) * 60 + 870 strtol(timestamp + 14, NULL, 10) - 871 zoneoffset); 872 873 return ((zoneoffset < 0 && hourminute == 1440) || 874 (0 <= zoneoffset && !hourminute)); 875} 876 877/* 878 * Get the name etc info from the ---/+++ lines of a traditional patch header 879 * 880 * FIXME! The end-of-filename heuristics are kind of screwy. For existing 881 * files, we can happily check the index for a match, but for creating a 882 * new file we should try to match whatever "patch" does. I have no idea. 883 */ 884static void parse_traditional_patch(struct apply_state *state, 885 const char *first, 886 const char *second, 887 struct patch *patch) 888{ 889 char *name; 890 891 first += 4; /* skip "--- " */ 892 second += 4; /* skip "+++ " */ 893 if (!state->p_value_known) { 894 int p, q; 895 p = guess_p_value(state, first); 896 q = guess_p_value(state, second); 897 if (p < 0) p = q; 898 if (0 <= p && p == q) { 899 state->p_value = p; 900 state->p_value_known = 1; 901 } 902 } 903 if (is_dev_null(first)) { 904 patch->is_new = 1; 905 patch->is_delete = 0; 906 name = find_name_traditional(state, second, NULL, state->p_value); 907 patch->new_name = name; 908 } else if (is_dev_null(second)) { 909 patch->is_new = 0; 910 patch->is_delete = 1; 911 name = find_name_traditional(state, first, NULL, state->p_value); 912 patch->old_name = name; 913 } else { 914 char *first_name; 915 first_name = find_name_traditional(state, first, NULL, state->p_value); 916 name = find_name_traditional(state, second, first_name, state->p_value); 917 free(first_name); 918 if (has_epoch_timestamp(first)) { 919 patch->is_new = 1; 920 patch->is_delete = 0; 921 patch->new_name = name; 922 } else if (has_epoch_timestamp(second)) { 923 patch->is_new = 0; 924 patch->is_delete = 1; 925 patch->old_name = name; 926 } else { 927 patch->old_name = name; 928 patch->new_name = xstrdup_or_null(name); 929 } 930 } 931 if (!name) 932 die(_("unable to find filename in patch at line %d"), state_linenr); 933} 934 935static int gitdiff_hdrend(struct apply_state *state, 936 const char *line, 937 struct patch *patch) 938{ 939 return -1; 940} 941 942/* 943 * We're anal about diff header consistency, to make 944 * sure that we don't end up having strange ambiguous 945 * patches floating around. 946 * 947 * As a result, gitdiff_{old|new}name() will check 948 * their names against any previous information, just 949 * to make sure.. 950 */ 951#define DIFF_OLD_NAME 0 952#define DIFF_NEW_NAME 1 953 954static void gitdiff_verify_name(struct apply_state *state, 955 const char *line, 956 int isnull, 957 char **name, 958 int side) 959{ 960 if (!*name && !isnull) { 961 *name = find_name(state, line, NULL, state->p_value, TERM_TAB); 962 return; 963 } 964 965 if (*name) { 966 int len = strlen(*name); 967 char *another; 968 if (isnull) 969 die(_("git apply: bad git-diff - expected /dev/null, got %s on line %d"), 970 *name, state_linenr); 971 another = find_name(state, line, NULL, state->p_value, TERM_TAB); 972 if (!another || memcmp(another, *name, len + 1)) 973 die((side == DIFF_NEW_NAME) ? 974 _("git apply: bad git-diff - inconsistent new filename on line %d") : 975 _("git apply: bad git-diff - inconsistent old filename on line %d"), state_linenr); 976 free(another); 977 } else { 978 /* expect "/dev/null" */ 979 if (memcmp("/dev/null", line, 9) || line[9] != '\n') 980 die(_("git apply: bad git-diff - expected /dev/null on line %d"), state_linenr); 981 } 982} 983 984static int gitdiff_oldname(struct apply_state *state, 985 const char *line, 986 struct patch *patch) 987{ 988 gitdiff_verify_name(state, line, 989 patch->is_new, &patch->old_name, 990 DIFF_OLD_NAME); 991 return 0; 992} 993 994static int gitdiff_newname(struct apply_state *state, 995 const char *line, 996 struct patch *patch) 997{ 998 gitdiff_verify_name(state, line, 999 patch->is_delete, &patch->new_name,1000 DIFF_NEW_NAME);1001 return 0;1002}10031004static int gitdiff_oldmode(struct apply_state *state,1005 const char *line,1006 struct patch *patch)1007{1008 patch->old_mode = strtoul(line, NULL, 8);1009 return 0;1010}10111012static int gitdiff_newmode(struct apply_state *state,1013 const char *line,1014 struct patch *patch)1015{1016 patch->new_mode = strtoul(line, NULL, 8);1017 return 0;1018}10191020static int gitdiff_delete(struct apply_state *state,1021 const char *line,1022 struct patch *patch)1023{1024 patch->is_delete = 1;1025 free(patch->old_name);1026 patch->old_name = xstrdup_or_null(patch->def_name);1027 return gitdiff_oldmode(state, line, patch);1028}10291030static int gitdiff_newfile(struct apply_state *state,1031 const char *line,1032 struct patch *patch)1033{1034 patch->is_new = 1;1035 free(patch->new_name);1036 patch->new_name = xstrdup_or_null(patch->def_name);1037 return gitdiff_newmode(state, line, patch);1038}10391040static int gitdiff_copysrc(struct apply_state *state,1041 const char *line,1042 struct patch *patch)1043{1044 patch->is_copy = 1;1045 free(patch->old_name);1046 patch->old_name = find_name(state, line, NULL, state->p_value ? state->p_value - 1 : 0, 0);1047 return 0;1048}10491050static int gitdiff_copydst(struct apply_state *state,1051 const char *line,1052 struct patch *patch)1053{1054 patch->is_copy = 1;1055 free(patch->new_name);1056 patch->new_name = find_name(state, line, NULL, state->p_value ? state->p_value - 1 : 0, 0);1057 return 0;1058}10591060static int gitdiff_renamesrc(struct apply_state *state,1061 const char *line,1062 struct patch *patch)1063{1064 patch->is_rename = 1;1065 free(patch->old_name);1066 patch->old_name = find_name(state, line, NULL, state->p_value ? state->p_value - 1 : 0, 0);1067 return 0;1068}10691070static int gitdiff_renamedst(struct apply_state *state,1071 const char *line,1072 struct patch *patch)1073{1074 patch->is_rename = 1;1075 free(patch->new_name);1076 patch->new_name = find_name(state, line, NULL, state->p_value ? state->p_value - 1 : 0, 0);1077 return 0;1078}10791080static int gitdiff_similarity(struct apply_state *state,1081 const char *line,1082 struct patch *patch)1083{1084 unsigned long val = strtoul(line, NULL, 10);1085 if (val <= 100)1086 patch->score = val;1087 return 0;1088}10891090static int gitdiff_dissimilarity(struct apply_state *state,1091 const char *line,1092 struct patch *patch)1093{1094 unsigned long val = strtoul(line, NULL, 10);1095 if (val <= 100)1096 patch->score = val;1097 return 0;1098}10991100static int gitdiff_index(struct apply_state *state,1101 const char *line,1102 struct patch *patch)1103{1104 /*1105 * index line is N hexadecimal, "..", N hexadecimal,1106 * and optional space with octal mode.1107 */1108 const char *ptr, *eol;1109 int len;11101111 ptr = strchr(line, '.');1112 if (!ptr || ptr[1] != '.' || 40 < ptr - line)1113 return 0;1114 len = ptr - line;1115 memcpy(patch->old_sha1_prefix, line, len);1116 patch->old_sha1_prefix[len] = 0;11171118 line = ptr + 2;1119 ptr = strchr(line, ' ');1120 eol = strchrnul(line, '\n');11211122 if (!ptr || eol < ptr)1123 ptr = eol;1124 len = ptr - line;11251126 if (40 < len)1127 return 0;1128 memcpy(patch->new_sha1_prefix, line, len);1129 patch->new_sha1_prefix[len] = 0;1130 if (*ptr == ' ')1131 patch->old_mode = strtoul(ptr+1, NULL, 8);1132 return 0;1133}11341135/*1136 * This is normal for a diff that doesn't change anything: we'll fall through1137 * into the next diff. Tell the parser to break out.1138 */1139static int gitdiff_unrecognized(struct apply_state *state,1140 const char *line,1141 struct patch *patch)1142{1143 return -1;1144}11451146/*1147 * Skip p_value leading components from "line"; as we do not accept1148 * absolute paths, return NULL in that case.1149 */1150static const char *skip_tree_prefix(struct apply_state *state,1151 const char *line,1152 int llen)1153{1154 int nslash;1155 int i;11561157 if (!state->p_value)1158 return (llen && line[0] == '/') ? NULL : line;11591160 nslash = state->p_value;1161 for (i = 0; i < llen; i++) {1162 int ch = line[i];1163 if (ch == '/' && --nslash <= 0)1164 return (i == 0) ? NULL : &line[i + 1];1165 }1166 return NULL;1167}11681169/*1170 * This is to extract the same name that appears on "diff --git"1171 * line. We do not find and return anything if it is a rename1172 * patch, and it is OK because we will find the name elsewhere.1173 * We need to reliably find name only when it is mode-change only,1174 * creation or deletion of an empty file. In any of these cases,1175 * both sides are the same name under a/ and b/ respectively.1176 */1177static char *git_header_name(struct apply_state *state,1178 const char *line,1179 int llen)1180{1181 const char *name;1182 const char *second = NULL;1183 size_t len, line_len;11841185 line += strlen("diff --git ");1186 llen -= strlen("diff --git ");11871188 if (*line == '"') {1189 const char *cp;1190 struct strbuf first = STRBUF_INIT;1191 struct strbuf sp = STRBUF_INIT;11921193 if (unquote_c_style(&first, line, &second))1194 goto free_and_fail1;11951196 /* strip the a/b prefix including trailing slash */1197 cp = skip_tree_prefix(state, first.buf, first.len);1198 if (!cp)1199 goto free_and_fail1;1200 strbuf_remove(&first, 0, cp - first.buf);12011202 /*1203 * second points at one past closing dq of name.1204 * find the second name.1205 */1206 while ((second < line + llen) && isspace(*second))1207 second++;12081209 if (line + llen <= second)1210 goto free_and_fail1;1211 if (*second == '"') {1212 if (unquote_c_style(&sp, second, NULL))1213 goto free_and_fail1;1214 cp = skip_tree_prefix(state, sp.buf, sp.len);1215 if (!cp)1216 goto free_and_fail1;1217 /* They must match, otherwise ignore */1218 if (strcmp(cp, first.buf))1219 goto free_and_fail1;1220 strbuf_release(&sp);1221 return strbuf_detach(&first, NULL);1222 }12231224 /* unquoted second */1225 cp = skip_tree_prefix(state, second, line + llen - second);1226 if (!cp)1227 goto free_and_fail1;1228 if (line + llen - cp != first.len ||1229 memcmp(first.buf, cp, first.len))1230 goto free_and_fail1;1231 return strbuf_detach(&first, NULL);12321233 free_and_fail1:1234 strbuf_release(&first);1235 strbuf_release(&sp);1236 return NULL;1237 }12381239 /* unquoted first name */1240 name = skip_tree_prefix(state, line, llen);1241 if (!name)1242 return NULL;12431244 /*1245 * since the first name is unquoted, a dq if exists must be1246 * the beginning of the second name.1247 */1248 for (second = name; second < line + llen; second++) {1249 if (*second == '"') {1250 struct strbuf sp = STRBUF_INIT;1251 const char *np;12521253 if (unquote_c_style(&sp, second, NULL))1254 goto free_and_fail2;12551256 np = skip_tree_prefix(state, sp.buf, sp.len);1257 if (!np)1258 goto free_and_fail2;12591260 len = sp.buf + sp.len - np;1261 if (len < second - name &&1262 !strncmp(np, name, len) &&1263 isspace(name[len])) {1264 /* Good */1265 strbuf_remove(&sp, 0, np - sp.buf);1266 return strbuf_detach(&sp, NULL);1267 }12681269 free_and_fail2:1270 strbuf_release(&sp);1271 return NULL;1272 }1273 }12741275 /*1276 * Accept a name only if it shows up twice, exactly the same1277 * form.1278 */1279 second = strchr(name, '\n');1280 if (!second)1281 return NULL;1282 line_len = second - name;1283 for (len = 0 ; ; len++) {1284 switch (name[len]) {1285 default:1286 continue;1287 case '\n':1288 return NULL;1289 case '\t': case ' ':1290 /*1291 * Is this the separator between the preimage1292 * and the postimage pathname? Again, we are1293 * only interested in the case where there is1294 * no rename, as this is only to set def_name1295 * and a rename patch has the names elsewhere1296 * in an unambiguous form.1297 */1298 if (!name[len + 1])1299 return NULL; /* no postimage name */1300 second = skip_tree_prefix(state, name + len + 1,1301 line_len - (len + 1));1302 if (!second)1303 return NULL;1304 /*1305 * Does len bytes starting at "name" and "second"1306 * (that are separated by one HT or SP we just1307 * found) exactly match?1308 */1309 if (second[len] == '\n' && !strncmp(name, second, len))1310 return xmemdupz(name, len);1311 }1312 }1313}13141315/* Verify that we recognize the lines following a git header */1316static int parse_git_header(struct apply_state *state,1317 const char *line,1318 int len,1319 unsigned int size,1320 struct patch *patch)1321{1322 unsigned long offset;13231324 /* A git diff has explicit new/delete information, so we don't guess */1325 patch->is_new = 0;1326 patch->is_delete = 0;13271328 /*1329 * Some things may not have the old name in the1330 * rest of the headers anywhere (pure mode changes,1331 * or removing or adding empty files), so we get1332 * the default name from the header.1333 */1334 patch->def_name = git_header_name(state, line, len);1335 if (patch->def_name && state->root.len) {1336 char *s = xstrfmt("%s%s", state->root.buf, patch->def_name);1337 free(patch->def_name);1338 patch->def_name = s;1339 }13401341 line += len;1342 size -= len;1343 state_linenr++;1344 for (offset = len ; size > 0 ; offset += len, size -= len, line += len, state_linenr++) {1345 static const struct opentry {1346 const char *str;1347 int (*fn)(struct apply_state *, const char *, struct patch *);1348 } optable[] = {1349 { "@@ -", gitdiff_hdrend },1350 { "--- ", gitdiff_oldname },1351 { "+++ ", gitdiff_newname },1352 { "old mode ", gitdiff_oldmode },1353 { "new mode ", gitdiff_newmode },1354 { "deleted file mode ", gitdiff_delete },1355 { "new file mode ", gitdiff_newfile },1356 { "copy from ", gitdiff_copysrc },1357 { "copy to ", gitdiff_copydst },1358 { "rename old ", gitdiff_renamesrc },1359 { "rename new ", gitdiff_renamedst },1360 { "rename from ", gitdiff_renamesrc },1361 { "rename to ", gitdiff_renamedst },1362 { "similarity index ", gitdiff_similarity },1363 { "dissimilarity index ", gitdiff_dissimilarity },1364 { "index ", gitdiff_index },1365 { "", gitdiff_unrecognized },1366 };1367 int i;13681369 len = linelen(line, size);1370 if (!len || line[len-1] != '\n')1371 break;1372 for (i = 0; i < ARRAY_SIZE(optable); i++) {1373 const struct opentry *p = optable + i;1374 int oplen = strlen(p->str);1375 if (len < oplen || memcmp(p->str, line, oplen))1376 continue;1377 if (p->fn(state, line + oplen, patch) < 0)1378 return offset;1379 break;1380 }1381 }13821383 return offset;1384}13851386static int parse_num(const char *line, unsigned long *p)1387{1388 char *ptr;13891390 if (!isdigit(*line))1391 return 0;1392 *p = strtoul(line, &ptr, 10);1393 return ptr - line;1394}13951396static int parse_range(const char *line, int len, int offset, const char *expect,1397 unsigned long *p1, unsigned long *p2)1398{1399 int digits, ex;14001401 if (offset < 0 || offset >= len)1402 return -1;1403 line += offset;1404 len -= offset;14051406 digits = parse_num(line, p1);1407 if (!digits)1408 return -1;14091410 offset += digits;1411 line += digits;1412 len -= digits;14131414 *p2 = 1;1415 if (*line == ',') {1416 digits = parse_num(line+1, p2);1417 if (!digits)1418 return -1;14191420 offset += digits+1;1421 line += digits+1;1422 len -= digits+1;1423 }14241425 ex = strlen(expect);1426 if (ex > len)1427 return -1;1428 if (memcmp(line, expect, ex))1429 return -1;14301431 return offset + ex;1432}14331434static void recount_diff(const char *line, int size, struct fragment *fragment)1435{1436 int oldlines = 0, newlines = 0, ret = 0;14371438 if (size < 1) {1439 warning("recount: ignore empty hunk");1440 return;1441 }14421443 for (;;) {1444 int len = linelen(line, size);1445 size -= len;1446 line += len;14471448 if (size < 1)1449 break;14501451 switch (*line) {1452 case ' ': case '\n':1453 newlines++;1454 /* fall through */1455 case '-':1456 oldlines++;1457 continue;1458 case '+':1459 newlines++;1460 continue;1461 case '\\':1462 continue;1463 case '@':1464 ret = size < 3 || !starts_with(line, "@@ ");1465 break;1466 case 'd':1467 ret = size < 5 || !starts_with(line, "diff ");1468 break;1469 default:1470 ret = -1;1471 break;1472 }1473 if (ret) {1474 warning(_("recount: unexpected line: %.*s"),1475 (int)linelen(line, size), line);1476 return;1477 }1478 break;1479 }1480 fragment->oldlines = oldlines;1481 fragment->newlines = newlines;1482}14831484/*1485 * Parse a unified diff fragment header of the1486 * form "@@ -a,b +c,d @@"1487 */1488static int parse_fragment_header(const char *line, int len, struct fragment *fragment)1489{1490 int offset;14911492 if (!len || line[len-1] != '\n')1493 return -1;14941495 /* Figure out the number of lines in a fragment */1496 offset = parse_range(line, len, 4, " +", &fragment->oldpos, &fragment->oldlines);1497 offset = parse_range(line, len, offset, " @@", &fragment->newpos, &fragment->newlines);14981499 return offset;1500}15011502static int find_header(struct apply_state *state,1503 const char *line,1504 unsigned long size,1505 int *hdrsize,1506 struct patch *patch)1507{1508 unsigned long offset, len;15091510 patch->is_toplevel_relative = 0;1511 patch->is_rename = patch->is_copy = 0;1512 patch->is_new = patch->is_delete = -1;1513 patch->old_mode = patch->new_mode = 0;1514 patch->old_name = patch->new_name = NULL;1515 for (offset = 0; size > 0; offset += len, size -= len, line += len, state_linenr++) {1516 unsigned long nextlen;15171518 len = linelen(line, size);1519 if (!len)1520 break;15211522 /* Testing this early allows us to take a few shortcuts.. */1523 if (len < 6)1524 continue;15251526 /*1527 * Make sure we don't find any unconnected patch fragments.1528 * That's a sign that we didn't find a header, and that a1529 * patch has become corrupted/broken up.1530 */1531 if (!memcmp("@@ -", line, 4)) {1532 struct fragment dummy;1533 if (parse_fragment_header(line, len, &dummy) < 0)1534 continue;1535 die(_("patch fragment without header at line %d: %.*s"),1536 state_linenr, (int)len-1, line);1537 }15381539 if (size < len + 6)1540 break;15411542 /*1543 * Git patch? It might not have a real patch, just a rename1544 * or mode change, so we handle that specially1545 */1546 if (!memcmp("diff --git ", line, 11)) {1547 int git_hdr_len = parse_git_header(state, line, len, size, patch);1548 if (git_hdr_len <= len)1549 continue;1550 if (!patch->old_name && !patch->new_name) {1551 if (!patch->def_name)1552 die(Q_("git diff header lacks filename information when removing "1553 "%d leading pathname component (line %d)",1554 "git diff header lacks filename information when removing "1555 "%d leading pathname components (line %d)",1556 state->p_value),1557 state->p_value, state_linenr);1558 patch->old_name = xstrdup(patch->def_name);1559 patch->new_name = xstrdup(patch->def_name);1560 }1561 if (!patch->is_delete && !patch->new_name)1562 die("git diff header lacks filename information "1563 "(line %d)", state_linenr);1564 patch->is_toplevel_relative = 1;1565 *hdrsize = git_hdr_len;1566 return offset;1567 }15681569 /* --- followed by +++ ? */1570 if (memcmp("--- ", line, 4) || memcmp("+++ ", line + len, 4))1571 continue;15721573 /*1574 * We only accept unified patches, so we want it to1575 * at least have "@@ -a,b +c,d @@\n", which is 14 chars1576 * minimum ("@@ -0,0 +1 @@\n" is the shortest).1577 */1578 nextlen = linelen(line + len, size - len);1579 if (size < nextlen + 14 || memcmp("@@ -", line + len + nextlen, 4))1580 continue;15811582 /* Ok, we'll consider it a patch */1583 parse_traditional_patch(state, line, line+len, patch);1584 *hdrsize = len + nextlen;1585 state_linenr += 2;1586 return offset;1587 }1588 return -1;1589}15901591static void record_ws_error(struct apply_state *state,1592 unsigned result,1593 const char *line,1594 int len,1595 int linenr)1596{1597 char *err;15981599 if (!result)1600 return;16011602 state->whitespace_error++;1603 if (squelch_whitespace_errors &&1604 squelch_whitespace_errors < state->whitespace_error)1605 return;16061607 err = whitespace_error_string(result);1608 fprintf(stderr, "%s:%d: %s.\n%.*s\n",1609 state->patch_input_file, linenr, err, len, line);1610 free(err);1611}16121613static void check_whitespace(struct apply_state *state,1614 const char *line,1615 int len,1616 unsigned ws_rule)1617{1618 unsigned result = ws_check(line + 1, len - 1, ws_rule);16191620 record_ws_error(state, result, line + 1, len - 2, state_linenr);1621}16221623/*1624 * Parse a unified diff. Note that this really needs to parse each1625 * fragment separately, since the only way to know the difference1626 * between a "---" that is part of a patch, and a "---" that starts1627 * the next patch is to look at the line counts..1628 */1629static int parse_fragment(struct apply_state *state,1630 const char *line,1631 unsigned long size,1632 struct patch *patch,1633 struct fragment *fragment)1634{1635 int added, deleted;1636 int len = linelen(line, size), offset;1637 unsigned long oldlines, newlines;1638 unsigned long leading, trailing;16391640 offset = parse_fragment_header(line, len, fragment);1641 if (offset < 0)1642 return -1;1643 if (offset > 0 && patch->recount)1644 recount_diff(line + offset, size - offset, fragment);1645 oldlines = fragment->oldlines;1646 newlines = fragment->newlines;1647 leading = 0;1648 trailing = 0;16491650 /* Parse the thing.. */1651 line += len;1652 size -= len;1653 state_linenr++;1654 added = deleted = 0;1655 for (offset = len;1656 0 < size;1657 offset += len, size -= len, line += len, state_linenr++) {1658 if (!oldlines && !newlines)1659 break;1660 len = linelen(line, size);1661 if (!len || line[len-1] != '\n')1662 return -1;1663 switch (*line) {1664 default:1665 return -1;1666 case '\n': /* newer GNU diff, an empty context line */1667 case ' ':1668 oldlines--;1669 newlines--;1670 if (!deleted && !added)1671 leading++;1672 trailing++;1673 if (!state->apply_in_reverse &&1674 ws_error_action == correct_ws_error)1675 check_whitespace(state, line, len, patch->ws_rule);1676 break;1677 case '-':1678 if (state->apply_in_reverse &&1679 ws_error_action != nowarn_ws_error)1680 check_whitespace(state, line, len, patch->ws_rule);1681 deleted++;1682 oldlines--;1683 trailing = 0;1684 break;1685 case '+':1686 if (!state->apply_in_reverse &&1687 ws_error_action != nowarn_ws_error)1688 check_whitespace(state, line, len, patch->ws_rule);1689 added++;1690 newlines--;1691 trailing = 0;1692 break;16931694 /*1695 * We allow "\ No newline at end of file". Depending1696 * on locale settings when the patch was produced we1697 * don't know what this line looks like. The only1698 * thing we do know is that it begins with "\ ".1699 * Checking for 12 is just for sanity check -- any1700 * l10n of "\ No newline..." is at least that long.1701 */1702 case '\\':1703 if (len < 12 || memcmp(line, "\\ ", 2))1704 return -1;1705 break;1706 }1707 }1708 if (oldlines || newlines)1709 return -1;1710 if (!deleted && !added)1711 return -1;17121713 fragment->leading = leading;1714 fragment->trailing = trailing;17151716 /*1717 * If a fragment ends with an incomplete line, we failed to include1718 * it in the above loop because we hit oldlines == newlines == 01719 * before seeing it.1720 */1721 if (12 < size && !memcmp(line, "\\ ", 2))1722 offset += linelen(line, size);17231724 patch->lines_added += added;1725 patch->lines_deleted += deleted;17261727 if (0 < patch->is_new && oldlines)1728 return error(_("new file depends on old contents"));1729 if (0 < patch->is_delete && newlines)1730 return error(_("deleted file still has contents"));1731 return offset;1732}17331734/*1735 * We have seen "diff --git a/... b/..." header (or a traditional patch1736 * header). Read hunks that belong to this patch into fragments and hang1737 * them to the given patch structure.1738 *1739 * The (fragment->patch, fragment->size) pair points into the memory given1740 * by the caller, not a copy, when we return.1741 */1742static int parse_single_patch(struct apply_state *state,1743 const char *line,1744 unsigned long size,1745 struct patch *patch)1746{1747 unsigned long offset = 0;1748 unsigned long oldlines = 0, newlines = 0, context = 0;1749 struct fragment **fragp = &patch->fragments;17501751 while (size > 4 && !memcmp(line, "@@ -", 4)) {1752 struct fragment *fragment;1753 int len;17541755 fragment = xcalloc(1, sizeof(*fragment));1756 fragment->linenr = state_linenr;1757 len = parse_fragment(state, line, size, patch, fragment);1758 if (len <= 0)1759 die(_("corrupt patch at line %d"), state_linenr);1760 fragment->patch = line;1761 fragment->size = len;1762 oldlines += fragment->oldlines;1763 newlines += fragment->newlines;1764 context += fragment->leading + fragment->trailing;17651766 *fragp = fragment;1767 fragp = &fragment->next;17681769 offset += len;1770 line += len;1771 size -= len;1772 }17731774 /*1775 * If something was removed (i.e. we have old-lines) it cannot1776 * be creation, and if something was added it cannot be1777 * deletion. However, the reverse is not true; --unified=01778 * patches that only add are not necessarily creation even1779 * though they do not have any old lines, and ones that only1780 * delete are not necessarily deletion.1781 *1782 * Unfortunately, a real creation/deletion patch do _not_ have1783 * any context line by definition, so we cannot safely tell it1784 * apart with --unified=0 insanity. At least if the patch has1785 * more than one hunk it is not creation or deletion.1786 */1787 if (patch->is_new < 0 &&1788 (oldlines || (patch->fragments && patch->fragments->next)))1789 patch->is_new = 0;1790 if (patch->is_delete < 0 &&1791 (newlines || (patch->fragments && patch->fragments->next)))1792 patch->is_delete = 0;17931794 if (0 < patch->is_new && oldlines)1795 die(_("new file %s depends on old contents"), patch->new_name);1796 if (0 < patch->is_delete && newlines)1797 die(_("deleted file %s still has contents"), patch->old_name);1798 if (!patch->is_delete && !newlines && context)1799 fprintf_ln(stderr,1800 _("** warning: "1801 "file %s becomes empty but is not deleted"),1802 patch->new_name);18031804 return offset;1805}18061807static inline int metadata_changes(struct patch *patch)1808{1809 return patch->is_rename > 0 ||1810 patch->is_copy > 0 ||1811 patch->is_new > 0 ||1812 patch->is_delete ||1813 (patch->old_mode && patch->new_mode &&1814 patch->old_mode != patch->new_mode);1815}18161817static char *inflate_it(const void *data, unsigned long size,1818 unsigned long inflated_size)1819{1820 git_zstream stream;1821 void *out;1822 int st;18231824 memset(&stream, 0, sizeof(stream));18251826 stream.next_in = (unsigned char *)data;1827 stream.avail_in = size;1828 stream.next_out = out = xmalloc(inflated_size);1829 stream.avail_out = inflated_size;1830 git_inflate_init(&stream);1831 st = git_inflate(&stream, Z_FINISH);1832 git_inflate_end(&stream);1833 if ((st != Z_STREAM_END) || stream.total_out != inflated_size) {1834 free(out);1835 return NULL;1836 }1837 return out;1838}18391840/*1841 * Read a binary hunk and return a new fragment; fragment->patch1842 * points at an allocated memory that the caller must free, so1843 * it is marked as "->free_patch = 1".1844 */1845static struct fragment *parse_binary_hunk(char **buf_p,1846 unsigned long *sz_p,1847 int *status_p,1848 int *used_p)1849{1850 /*1851 * Expect a line that begins with binary patch method ("literal"1852 * or "delta"), followed by the length of data before deflating.1853 * a sequence of 'length-byte' followed by base-85 encoded data1854 * should follow, terminated by a newline.1855 *1856 * Each 5-byte sequence of base-85 encodes up to 4 bytes,1857 * and we would limit the patch line to 66 characters,1858 * so one line can fit up to 13 groups that would decode1859 * to 52 bytes max. The length byte 'A'-'Z' corresponds1860 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.1861 */1862 int llen, used;1863 unsigned long size = *sz_p;1864 char *buffer = *buf_p;1865 int patch_method;1866 unsigned long origlen;1867 char *data = NULL;1868 int hunk_size = 0;1869 struct fragment *frag;18701871 llen = linelen(buffer, size);1872 used = llen;18731874 *status_p = 0;18751876 if (starts_with(buffer, "delta ")) {1877 patch_method = BINARY_DELTA_DEFLATED;1878 origlen = strtoul(buffer + 6, NULL, 10);1879 }1880 else if (starts_with(buffer, "literal ")) {1881 patch_method = BINARY_LITERAL_DEFLATED;1882 origlen = strtoul(buffer + 8, NULL, 10);1883 }1884 else1885 return NULL;18861887 state_linenr++;1888 buffer += llen;1889 while (1) {1890 int byte_length, max_byte_length, newsize;1891 llen = linelen(buffer, size);1892 used += llen;1893 state_linenr++;1894 if (llen == 1) {1895 /* consume the blank line */1896 buffer++;1897 size--;1898 break;1899 }1900 /*1901 * Minimum line is "A00000\n" which is 7-byte long,1902 * and the line length must be multiple of 5 plus 2.1903 */1904 if ((llen < 7) || (llen-2) % 5)1905 goto corrupt;1906 max_byte_length = (llen - 2) / 5 * 4;1907 byte_length = *buffer;1908 if ('A' <= byte_length && byte_length <= 'Z')1909 byte_length = byte_length - 'A' + 1;1910 else if ('a' <= byte_length && byte_length <= 'z')1911 byte_length = byte_length - 'a' + 27;1912 else1913 goto corrupt;1914 /* if the input length was not multiple of 4, we would1915 * have filler at the end but the filler should never1916 * exceed 3 bytes1917 */1918 if (max_byte_length < byte_length ||1919 byte_length <= max_byte_length - 4)1920 goto corrupt;1921 newsize = hunk_size + byte_length;1922 data = xrealloc(data, newsize);1923 if (decode_85(data + hunk_size, buffer + 1, byte_length))1924 goto corrupt;1925 hunk_size = newsize;1926 buffer += llen;1927 size -= llen;1928 }19291930 frag = xcalloc(1, sizeof(*frag));1931 frag->patch = inflate_it(data, hunk_size, origlen);1932 frag->free_patch = 1;1933 if (!frag->patch)1934 goto corrupt;1935 free(data);1936 frag->size = origlen;1937 *buf_p = buffer;1938 *sz_p = size;1939 *used_p = used;1940 frag->binary_patch_method = patch_method;1941 return frag;19421943 corrupt:1944 free(data);1945 *status_p = -1;1946 error(_("corrupt binary patch at line %d: %.*s"),1947 state_linenr-1, llen-1, buffer);1948 return NULL;1949}19501951/*1952 * Returns:1953 * -1 in case of error,1954 * the length of the parsed binary patch otherwise1955 */1956static int parse_binary(char *buffer, unsigned long size, struct patch *patch)1957{1958 /*1959 * We have read "GIT binary patch\n"; what follows is a line1960 * that says the patch method (currently, either "literal" or1961 * "delta") and the length of data before deflating; a1962 * sequence of 'length-byte' followed by base-85 encoded data1963 * follows.1964 *1965 * When a binary patch is reversible, there is another binary1966 * hunk in the same format, starting with patch method (either1967 * "literal" or "delta") with the length of data, and a sequence1968 * of length-byte + base-85 encoded data, terminated with another1969 * empty line. This data, when applied to the postimage, produces1970 * the preimage.1971 */1972 struct fragment *forward;1973 struct fragment *reverse;1974 int status;1975 int used, used_1;19761977 forward = parse_binary_hunk(&buffer, &size, &status, &used);1978 if (!forward && !status)1979 /* there has to be one hunk (forward hunk) */1980 return error(_("unrecognized binary patch at line %d"), state_linenr-1);1981 if (status)1982 /* otherwise we already gave an error message */1983 return status;19841985 reverse = parse_binary_hunk(&buffer, &size, &status, &used_1);1986 if (reverse)1987 used += used_1;1988 else if (status) {1989 /*1990 * Not having reverse hunk is not an error, but having1991 * a corrupt reverse hunk is.1992 */1993 free((void*) forward->patch);1994 free(forward);1995 return status;1996 }1997 forward->next = reverse;1998 patch->fragments = forward;1999 patch->is_binary = 1;2000 return used;2001}20022003static void prefix_one(struct apply_state *state, char **name)2004{2005 char *old_name = *name;2006 if (!old_name)2007 return;2008 *name = xstrdup(prefix_filename(state->prefix, state->prefix_length, *name));2009 free(old_name);2010}20112012static void prefix_patch(struct apply_state *state, struct patch *p)2013{2014 if (!state->prefix || p->is_toplevel_relative)2015 return;2016 prefix_one(state, &p->new_name);2017 prefix_one(state, &p->old_name);2018}20192020/*2021 * include/exclude2022 */20232024static void add_name_limit(struct apply_state *state,2025 const char *name,2026 int exclude)2027{2028 struct string_list_item *it;20292030 it = string_list_append(&state->limit_by_name, name);2031 it->util = exclude ? NULL : (void *) 1;2032}20332034static int use_patch(struct apply_state *state, struct patch *p)2035{2036 const char *pathname = p->new_name ? p->new_name : p->old_name;2037 int i;20382039 /* Paths outside are not touched regardless of "--include" */2040 if (0 < state->prefix_length) {2041 int pathlen = strlen(pathname);2042 if (pathlen <= state->prefix_length ||2043 memcmp(state->prefix, pathname, state->prefix_length))2044 return 0;2045 }20462047 /* See if it matches any of exclude/include rule */2048 for (i = 0; i < state->limit_by_name.nr; i++) {2049 struct string_list_item *it = &state->limit_by_name.items[i];2050 if (!wildmatch(it->string, pathname, 0, NULL))2051 return (it->util != NULL);2052 }20532054 /*2055 * If we had any include, a path that does not match any rule is2056 * not used. Otherwise, we saw bunch of exclude rules (or none)2057 * and such a path is used.2058 */2059 return !state->has_include;2060}206120622063/*2064 * Read the patch text in "buffer" that extends for "size" bytes; stop2065 * reading after seeing a single patch (i.e. changes to a single file).2066 * Create fragments (i.e. patch hunks) and hang them to the given patch.2067 * Return the number of bytes consumed, so that the caller can call us2068 * again for the next patch.2069 */2070static int parse_chunk(struct apply_state *state, char *buffer, unsigned long size, struct patch *patch)2071{2072 int hdrsize, patchsize;2073 int offset = find_header(state, buffer, size, &hdrsize, patch);20742075 if (offset < 0)2076 return offset;20772078 prefix_patch(state, patch);20792080 if (!use_patch(state, patch))2081 patch->ws_rule = 0;2082 else2083 patch->ws_rule = whitespace_rule(patch->new_name2084 ? patch->new_name2085 : patch->old_name);20862087 patchsize = parse_single_patch(state,2088 buffer + offset + hdrsize,2089 size - offset - hdrsize,2090 patch);20912092 if (!patchsize) {2093 static const char git_binary[] = "GIT binary patch\n";2094 int hd = hdrsize + offset;2095 unsigned long llen = linelen(buffer + hd, size - hd);20962097 if (llen == sizeof(git_binary) - 1 &&2098 !memcmp(git_binary, buffer + hd, llen)) {2099 int used;2100 state_linenr++;2101 used = parse_binary(buffer + hd + llen,2102 size - hd - llen, patch);2103 if (used < 0)2104 return -1;2105 if (used)2106 patchsize = used + llen;2107 else2108 patchsize = 0;2109 }2110 else if (!memcmp(" differ\n", buffer + hd + llen - 8, 8)) {2111 static const char *binhdr[] = {2112 "Binary files ",2113 "Files ",2114 NULL,2115 };2116 int i;2117 for (i = 0; binhdr[i]; i++) {2118 int len = strlen(binhdr[i]);2119 if (len < size - hd &&2120 !memcmp(binhdr[i], buffer + hd, len)) {2121 state_linenr++;2122 patch->is_binary = 1;2123 patchsize = llen;2124 break;2125 }2126 }2127 }21282129 /* Empty patch cannot be applied if it is a text patch2130 * without metadata change. A binary patch appears2131 * empty to us here.2132 */2133 if ((state->apply || state->check) &&2134 (!patch->is_binary && !metadata_changes(patch)))2135 die(_("patch with only garbage at line %d"), state_linenr);2136 }21372138 return offset + hdrsize + patchsize;2139}21402141#define swap(a,b) myswap((a),(b),sizeof(a))21422143#define myswap(a, b, size) do { \2144 unsigned char mytmp[size]; \2145 memcpy(mytmp, &a, size); \2146 memcpy(&a, &b, size); \2147 memcpy(&b, mytmp, size); \2148} while (0)21492150static void reverse_patches(struct patch *p)2151{2152 for (; p; p = p->next) {2153 struct fragment *frag = p->fragments;21542155 swap(p->new_name, p->old_name);2156 swap(p->new_mode, p->old_mode);2157 swap(p->is_new, p->is_delete);2158 swap(p->lines_added, p->lines_deleted);2159 swap(p->old_sha1_prefix, p->new_sha1_prefix);21602161 for (; frag; frag = frag->next) {2162 swap(frag->newpos, frag->oldpos);2163 swap(frag->newlines, frag->oldlines);2164 }2165 }2166}21672168static const char pluses[] =2169"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";2170static const char minuses[]=2171"----------------------------------------------------------------------";21722173static void show_stats(struct patch *patch)2174{2175 struct strbuf qname = STRBUF_INIT;2176 char *cp = patch->new_name ? patch->new_name : patch->old_name;2177 int max, add, del;21782179 quote_c_style(cp, &qname, NULL, 0);21802181 /*2182 * "scale" the filename2183 */2184 max = max_len;2185 if (max > 50)2186 max = 50;21872188 if (qname.len > max) {2189 cp = strchr(qname.buf + qname.len + 3 - max, '/');2190 if (!cp)2191 cp = qname.buf + qname.len + 3 - max;2192 strbuf_splice(&qname, 0, cp - qname.buf, "...", 3);2193 }21942195 if (patch->is_binary) {2196 printf(" %-*s | Bin\n", max, qname.buf);2197 strbuf_release(&qname);2198 return;2199 }22002201 printf(" %-*s |", max, qname.buf);2202 strbuf_release(&qname);22032204 /*2205 * scale the add/delete2206 */2207 max = max + max_change > 70 ? 70 - max : max_change;2208 add = patch->lines_added;2209 del = patch->lines_deleted;22102211 if (max_change > 0) {2212 int total = ((add + del) * max + max_change / 2) / max_change;2213 add = (add * max + max_change / 2) / max_change;2214 del = total - add;2215 }2216 printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,2217 add, pluses, del, minuses);2218}22192220static int read_old_data(struct stat *st, const char *path, struct strbuf *buf)2221{2222 switch (st->st_mode & S_IFMT) {2223 case S_IFLNK:2224 if (strbuf_readlink(buf, path, st->st_size) < 0)2225 return error(_("unable to read symlink %s"), path);2226 return 0;2227 case S_IFREG:2228 if (strbuf_read_file(buf, path, st->st_size) != st->st_size)2229 return error(_("unable to open or read %s"), path);2230 convert_to_git(path, buf->buf, buf->len, buf, 0);2231 return 0;2232 default:2233 return -1;2234 }2235}22362237/*2238 * Update the preimage, and the common lines in postimage,2239 * from buffer buf of length len. If postlen is 0 the postimage2240 * is updated in place, otherwise it's updated on a new buffer2241 * of length postlen2242 */22432244static void update_pre_post_images(struct image *preimage,2245 struct image *postimage,2246 char *buf,2247 size_t len, size_t postlen)2248{2249 int i, ctx, reduced;2250 char *new, *old, *fixed;2251 struct image fixed_preimage;22522253 /*2254 * Update the preimage with whitespace fixes. Note that we2255 * are not losing preimage->buf -- apply_one_fragment() will2256 * free "oldlines".2257 */2258 prepare_image(&fixed_preimage, buf, len, 1);2259 assert(postlen2260 ? fixed_preimage.nr == preimage->nr2261 : fixed_preimage.nr <= preimage->nr);2262 for (i = 0; i < fixed_preimage.nr; i++)2263 fixed_preimage.line[i].flag = preimage->line[i].flag;2264 free(preimage->line_allocated);2265 *preimage = fixed_preimage;22662267 /*2268 * Adjust the common context lines in postimage. This can be2269 * done in-place when we are shrinking it with whitespace2270 * fixing, but needs a new buffer when ignoring whitespace or2271 * expanding leading tabs to spaces.2272 *2273 * We trust the caller to tell us if the update can be done2274 * in place (postlen==0) or not.2275 */2276 old = postimage->buf;2277 if (postlen)2278 new = postimage->buf = xmalloc(postlen);2279 else2280 new = old;2281 fixed = preimage->buf;22822283 for (i = reduced = ctx = 0; i < postimage->nr; i++) {2284 size_t l_len = postimage->line[i].len;2285 if (!(postimage->line[i].flag & LINE_COMMON)) {2286 /* an added line -- no counterparts in preimage */2287 memmove(new, old, l_len);2288 old += l_len;2289 new += l_len;2290 continue;2291 }22922293 /* a common context -- skip it in the original postimage */2294 old += l_len;22952296 /* and find the corresponding one in the fixed preimage */2297 while (ctx < preimage->nr &&2298 !(preimage->line[ctx].flag & LINE_COMMON)) {2299 fixed += preimage->line[ctx].len;2300 ctx++;2301 }23022303 /*2304 * preimage is expected to run out, if the caller2305 * fixed addition of trailing blank lines.2306 */2307 if (preimage->nr <= ctx) {2308 reduced++;2309 continue;2310 }23112312 /* and copy it in, while fixing the line length */2313 l_len = preimage->line[ctx].len;2314 memcpy(new, fixed, l_len);2315 new += l_len;2316 fixed += l_len;2317 postimage->line[i].len = l_len;2318 ctx++;2319 }23202321 if (postlen2322 ? postlen < new - postimage->buf2323 : postimage->len < new - postimage->buf)2324 die("BUG: caller miscounted postlen: asked %d, orig = %d, used = %d",2325 (int)postlen, (int) postimage->len, (int)(new - postimage->buf));23262327 /* Fix the length of the whole thing */2328 postimage->len = new - postimage->buf;2329 postimage->nr -= reduced;2330}23312332static int line_by_line_fuzzy_match(struct image *img,2333 struct image *preimage,2334 struct image *postimage,2335 unsigned long try,2336 int try_lno,2337 int preimage_limit)2338{2339 int i;2340 size_t imgoff = 0;2341 size_t preoff = 0;2342 size_t postlen = postimage->len;2343 size_t extra_chars;2344 char *buf;2345 char *preimage_eof;2346 char *preimage_end;2347 struct strbuf fixed;2348 char *fixed_buf;2349 size_t fixed_len;23502351 for (i = 0; i < preimage_limit; i++) {2352 size_t prelen = preimage->line[i].len;2353 size_t imglen = img->line[try_lno+i].len;23542355 if (!fuzzy_matchlines(img->buf + try + imgoff, imglen,2356 preimage->buf + preoff, prelen))2357 return 0;2358 if (preimage->line[i].flag & LINE_COMMON)2359 postlen += imglen - prelen;2360 imgoff += imglen;2361 preoff += prelen;2362 }23632364 /*2365 * Ok, the preimage matches with whitespace fuzz.2366 *2367 * imgoff now holds the true length of the target that2368 * matches the preimage before the end of the file.2369 *2370 * Count the number of characters in the preimage that fall2371 * beyond the end of the file and make sure that all of them2372 * are whitespace characters. (This can only happen if2373 * we are removing blank lines at the end of the file.)2374 */2375 buf = preimage_eof = preimage->buf + preoff;2376 for ( ; i < preimage->nr; i++)2377 preoff += preimage->line[i].len;2378 preimage_end = preimage->buf + preoff;2379 for ( ; buf < preimage_end; buf++)2380 if (!isspace(*buf))2381 return 0;23822383 /*2384 * Update the preimage and the common postimage context2385 * lines to use the same whitespace as the target.2386 * If whitespace is missing in the target (i.e.2387 * if the preimage extends beyond the end of the file),2388 * use the whitespace from the preimage.2389 */2390 extra_chars = preimage_end - preimage_eof;2391 strbuf_init(&fixed, imgoff + extra_chars);2392 strbuf_add(&fixed, img->buf + try, imgoff);2393 strbuf_add(&fixed, preimage_eof, extra_chars);2394 fixed_buf = strbuf_detach(&fixed, &fixed_len);2395 update_pre_post_images(preimage, postimage,2396 fixed_buf, fixed_len, postlen);2397 return 1;2398}23992400static int match_fragment(struct image *img,2401 struct image *preimage,2402 struct image *postimage,2403 unsigned long try,2404 int try_lno,2405 unsigned ws_rule,2406 int match_beginning, int match_end)2407{2408 int i;2409 char *fixed_buf, *buf, *orig, *target;2410 struct strbuf fixed;2411 size_t fixed_len, postlen;2412 int preimage_limit;24132414 if (preimage->nr + try_lno <= img->nr) {2415 /*2416 * The hunk falls within the boundaries of img.2417 */2418 preimage_limit = preimage->nr;2419 if (match_end && (preimage->nr + try_lno != img->nr))2420 return 0;2421 } else if (ws_error_action == correct_ws_error &&2422 (ws_rule & WS_BLANK_AT_EOF)) {2423 /*2424 * This hunk extends beyond the end of img, and we are2425 * removing blank lines at the end of the file. This2426 * many lines from the beginning of the preimage must2427 * match with img, and the remainder of the preimage2428 * must be blank.2429 */2430 preimage_limit = img->nr - try_lno;2431 } else {2432 /*2433 * The hunk extends beyond the end of the img and2434 * we are not removing blanks at the end, so we2435 * should reject the hunk at this position.2436 */2437 return 0;2438 }24392440 if (match_beginning && try_lno)2441 return 0;24422443 /* Quick hash check */2444 for (i = 0; i < preimage_limit; i++)2445 if ((img->line[try_lno + i].flag & LINE_PATCHED) ||2446 (preimage->line[i].hash != img->line[try_lno + i].hash))2447 return 0;24482449 if (preimage_limit == preimage->nr) {2450 /*2451 * Do we have an exact match? If we were told to match2452 * at the end, size must be exactly at try+fragsize,2453 * otherwise try+fragsize must be still within the preimage,2454 * and either case, the old piece should match the preimage2455 * exactly.2456 */2457 if ((match_end2458 ? (try + preimage->len == img->len)2459 : (try + preimage->len <= img->len)) &&2460 !memcmp(img->buf + try, preimage->buf, preimage->len))2461 return 1;2462 } else {2463 /*2464 * The preimage extends beyond the end of img, so2465 * there cannot be an exact match.2466 *2467 * There must be one non-blank context line that match2468 * a line before the end of img.2469 */2470 char *buf_end;24712472 buf = preimage->buf;2473 buf_end = buf;2474 for (i = 0; i < preimage_limit; i++)2475 buf_end += preimage->line[i].len;24762477 for ( ; buf < buf_end; buf++)2478 if (!isspace(*buf))2479 break;2480 if (buf == buf_end)2481 return 0;2482 }24832484 /*2485 * No exact match. If we are ignoring whitespace, run a line-by-line2486 * fuzzy matching. We collect all the line length information because2487 * we need it to adjust whitespace if we match.2488 */2489 if (ws_ignore_action == ignore_ws_change)2490 return line_by_line_fuzzy_match(img, preimage, postimage,2491 try, try_lno, preimage_limit);24922493 if (ws_error_action != correct_ws_error)2494 return 0;24952496 /*2497 * The hunk does not apply byte-by-byte, but the hash says2498 * it might with whitespace fuzz. We weren't asked to2499 * ignore whitespace, we were asked to correct whitespace2500 * errors, so let's try matching after whitespace correction.2501 *2502 * While checking the preimage against the target, whitespace2503 * errors in both fixed, we count how large the corresponding2504 * postimage needs to be. The postimage prepared by2505 * apply_one_fragment() has whitespace errors fixed on added2506 * lines already, but the common lines were propagated as-is,2507 * which may become longer when their whitespace errors are2508 * fixed.2509 */25102511 /* First count added lines in postimage */2512 postlen = 0;2513 for (i = 0; i < postimage->nr; i++) {2514 if (!(postimage->line[i].flag & LINE_COMMON))2515 postlen += postimage->line[i].len;2516 }25172518 /*2519 * The preimage may extend beyond the end of the file,2520 * but in this loop we will only handle the part of the2521 * preimage that falls within the file.2522 */2523 strbuf_init(&fixed, preimage->len + 1);2524 orig = preimage->buf;2525 target = img->buf + try;2526 for (i = 0; i < preimage_limit; i++) {2527 size_t oldlen = preimage->line[i].len;2528 size_t tgtlen = img->line[try_lno + i].len;2529 size_t fixstart = fixed.len;2530 struct strbuf tgtfix;2531 int match;25322533 /* Try fixing the line in the preimage */2534 ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);25352536 /* Try fixing the line in the target */2537 strbuf_init(&tgtfix, tgtlen);2538 ws_fix_copy(&tgtfix, target, tgtlen, ws_rule, NULL);25392540 /*2541 * If they match, either the preimage was based on2542 * a version before our tree fixed whitespace breakage,2543 * or we are lacking a whitespace-fix patch the tree2544 * the preimage was based on already had (i.e. target2545 * has whitespace breakage, the preimage doesn't).2546 * In either case, we are fixing the whitespace breakages2547 * so we might as well take the fix together with their2548 * real change.2549 */2550 match = (tgtfix.len == fixed.len - fixstart &&2551 !memcmp(tgtfix.buf, fixed.buf + fixstart,2552 fixed.len - fixstart));25532554 /* Add the length if this is common with the postimage */2555 if (preimage->line[i].flag & LINE_COMMON)2556 postlen += tgtfix.len;25572558 strbuf_release(&tgtfix);2559 if (!match)2560 goto unmatch_exit;25612562 orig += oldlen;2563 target += tgtlen;2564 }256525662567 /*2568 * Now handle the lines in the preimage that falls beyond the2569 * end of the file (if any). They will only match if they are2570 * empty or only contain whitespace (if WS_BLANK_AT_EOL is2571 * false).2572 */2573 for ( ; i < preimage->nr; i++) {2574 size_t fixstart = fixed.len; /* start of the fixed preimage */2575 size_t oldlen = preimage->line[i].len;2576 int j;25772578 /* Try fixing the line in the preimage */2579 ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);25802581 for (j = fixstart; j < fixed.len; j++)2582 if (!isspace(fixed.buf[j]))2583 goto unmatch_exit;25842585 orig += oldlen;2586 }25872588 /*2589 * Yes, the preimage is based on an older version that still2590 * has whitespace breakages unfixed, and fixing them makes the2591 * hunk match. Update the context lines in the postimage.2592 */2593 fixed_buf = strbuf_detach(&fixed, &fixed_len);2594 if (postlen < postimage->len)2595 postlen = 0;2596 update_pre_post_images(preimage, postimage,2597 fixed_buf, fixed_len, postlen);2598 return 1;25992600 unmatch_exit:2601 strbuf_release(&fixed);2602 return 0;2603}26042605static int find_pos(struct image *img,2606 struct image *preimage,2607 struct image *postimage,2608 int line,2609 unsigned ws_rule,2610 int match_beginning, int match_end)2611{2612 int i;2613 unsigned long backwards, forwards, try;2614 int backwards_lno, forwards_lno, try_lno;26152616 /*2617 * If match_beginning or match_end is specified, there is no2618 * point starting from a wrong line that will never match and2619 * wander around and wait for a match at the specified end.2620 */2621 if (match_beginning)2622 line = 0;2623 else if (match_end)2624 line = img->nr - preimage->nr;26252626 /*2627 * Because the comparison is unsigned, the following test2628 * will also take care of a negative line number that can2629 * result when match_end and preimage is larger than the target.2630 */2631 if ((size_t) line > img->nr)2632 line = img->nr;26332634 try = 0;2635 for (i = 0; i < line; i++)2636 try += img->line[i].len;26372638 /*2639 * There's probably some smart way to do this, but I'll leave2640 * that to the smart and beautiful people. I'm simple and stupid.2641 */2642 backwards = try;2643 backwards_lno = line;2644 forwards = try;2645 forwards_lno = line;2646 try_lno = line;26472648 for (i = 0; ; i++) {2649 if (match_fragment(img, preimage, postimage,2650 try, try_lno, ws_rule,2651 match_beginning, match_end))2652 return try_lno;26532654 again:2655 if (backwards_lno == 0 && forwards_lno == img->nr)2656 break;26572658 if (i & 1) {2659 if (backwards_lno == 0) {2660 i++;2661 goto again;2662 }2663 backwards_lno--;2664 backwards -= img->line[backwards_lno].len;2665 try = backwards;2666 try_lno = backwards_lno;2667 } else {2668 if (forwards_lno == img->nr) {2669 i++;2670 goto again;2671 }2672 forwards += img->line[forwards_lno].len;2673 forwards_lno++;2674 try = forwards;2675 try_lno = forwards_lno;2676 }26772678 }2679 return -1;2680}26812682static void remove_first_line(struct image *img)2683{2684 img->buf += img->line[0].len;2685 img->len -= img->line[0].len;2686 img->line++;2687 img->nr--;2688}26892690static void remove_last_line(struct image *img)2691{2692 img->len -= img->line[--img->nr].len;2693}26942695/*2696 * The change from "preimage" and "postimage" has been found to2697 * apply at applied_pos (counts in line numbers) in "img".2698 * Update "img" to remove "preimage" and replace it with "postimage".2699 */2700static void update_image(struct apply_state *state,2701 struct image *img,2702 int applied_pos,2703 struct image *preimage,2704 struct image *postimage)2705{2706 /*2707 * remove the copy of preimage at offset in img2708 * and replace it with postimage2709 */2710 int i, nr;2711 size_t remove_count, insert_count, applied_at = 0;2712 char *result;2713 int preimage_limit;27142715 /*2716 * If we are removing blank lines at the end of img,2717 * the preimage may extend beyond the end.2718 * If that is the case, we must be careful only to2719 * remove the part of the preimage that falls within2720 * the boundaries of img. Initialize preimage_limit2721 * to the number of lines in the preimage that falls2722 * within the boundaries.2723 */2724 preimage_limit = preimage->nr;2725 if (preimage_limit > img->nr - applied_pos)2726 preimage_limit = img->nr - applied_pos;27272728 for (i = 0; i < applied_pos; i++)2729 applied_at += img->line[i].len;27302731 remove_count = 0;2732 for (i = 0; i < preimage_limit; i++)2733 remove_count += img->line[applied_pos + i].len;2734 insert_count = postimage->len;27352736 /* Adjust the contents */2737 result = xmalloc(st_add3(st_sub(img->len, remove_count), insert_count, 1));2738 memcpy(result, img->buf, applied_at);2739 memcpy(result + applied_at, postimage->buf, postimage->len);2740 memcpy(result + applied_at + postimage->len,2741 img->buf + (applied_at + remove_count),2742 img->len - (applied_at + remove_count));2743 free(img->buf);2744 img->buf = result;2745 img->len += insert_count - remove_count;2746 result[img->len] = '\0';27472748 /* Adjust the line table */2749 nr = img->nr + postimage->nr - preimage_limit;2750 if (preimage_limit < postimage->nr) {2751 /*2752 * NOTE: this knows that we never call remove_first_line()2753 * on anything other than pre/post image.2754 */2755 REALLOC_ARRAY(img->line, nr);2756 img->line_allocated = img->line;2757 }2758 if (preimage_limit != postimage->nr)2759 memmove(img->line + applied_pos + postimage->nr,2760 img->line + applied_pos + preimage_limit,2761 (img->nr - (applied_pos + preimage_limit)) *2762 sizeof(*img->line));2763 memcpy(img->line + applied_pos,2764 postimage->line,2765 postimage->nr * sizeof(*img->line));2766 if (!state->allow_overlap)2767 for (i = 0; i < postimage->nr; i++)2768 img->line[applied_pos + i].flag |= LINE_PATCHED;2769 img->nr = nr;2770}27712772/*2773 * Use the patch-hunk text in "frag" to prepare two images (preimage and2774 * postimage) for the hunk. Find lines that match "preimage" in "img" and2775 * replace the part of "img" with "postimage" text.2776 */2777static int apply_one_fragment(struct apply_state *state,2778 struct image *img, struct fragment *frag,2779 int inaccurate_eof, unsigned ws_rule,2780 int nth_fragment)2781{2782 int match_beginning, match_end;2783 const char *patch = frag->patch;2784 int size = frag->size;2785 char *old, *oldlines;2786 struct strbuf newlines;2787 int new_blank_lines_at_end = 0;2788 int found_new_blank_lines_at_end = 0;2789 int hunk_linenr = frag->linenr;2790 unsigned long leading, trailing;2791 int pos, applied_pos;2792 struct image preimage;2793 struct image postimage;27942795 memset(&preimage, 0, sizeof(preimage));2796 memset(&postimage, 0, sizeof(postimage));2797 oldlines = xmalloc(size);2798 strbuf_init(&newlines, size);27992800 old = oldlines;2801 while (size > 0) {2802 char first;2803 int len = linelen(patch, size);2804 int plen;2805 int added_blank_line = 0;2806 int is_blank_context = 0;2807 size_t start;28082809 if (!len)2810 break;28112812 /*2813 * "plen" is how much of the line we should use for2814 * the actual patch data. Normally we just remove the2815 * first character on the line, but if the line is2816 * followed by "\ No newline", then we also remove the2817 * last one (which is the newline, of course).2818 */2819 plen = len - 1;2820 if (len < size && patch[len] == '\\')2821 plen--;2822 first = *patch;2823 if (state->apply_in_reverse) {2824 if (first == '-')2825 first = '+';2826 else if (first == '+')2827 first = '-';2828 }28292830 switch (first) {2831 case '\n':2832 /* Newer GNU diff, empty context line */2833 if (plen < 0)2834 /* ... followed by '\No newline'; nothing */2835 break;2836 *old++ = '\n';2837 strbuf_addch(&newlines, '\n');2838 add_line_info(&preimage, "\n", 1, LINE_COMMON);2839 add_line_info(&postimage, "\n", 1, LINE_COMMON);2840 is_blank_context = 1;2841 break;2842 case ' ':2843 if (plen && (ws_rule & WS_BLANK_AT_EOF) &&2844 ws_blank_line(patch + 1, plen, ws_rule))2845 is_blank_context = 1;2846 case '-':2847 memcpy(old, patch + 1, plen);2848 add_line_info(&preimage, old, plen,2849 (first == ' ' ? LINE_COMMON : 0));2850 old += plen;2851 if (first == '-')2852 break;2853 /* Fall-through for ' ' */2854 case '+':2855 /* --no-add does not add new lines */2856 if (first == '+' && state->no_add)2857 break;28582859 start = newlines.len;2860 if (first != '+' ||2861 !state->whitespace_error ||2862 ws_error_action != correct_ws_error) {2863 strbuf_add(&newlines, patch + 1, plen);2864 }2865 else {2866 ws_fix_copy(&newlines, patch + 1, plen, ws_rule, &applied_after_fixing_ws);2867 }2868 add_line_info(&postimage, newlines.buf + start, newlines.len - start,2869 (first == '+' ? 0 : LINE_COMMON));2870 if (first == '+' &&2871 (ws_rule & WS_BLANK_AT_EOF) &&2872 ws_blank_line(patch + 1, plen, ws_rule))2873 added_blank_line = 1;2874 break;2875 case '@': case '\\':2876 /* Ignore it, we already handled it */2877 break;2878 default:2879 if (state->apply_verbosely)2880 error(_("invalid start of line: '%c'"), first);2881 applied_pos = -1;2882 goto out;2883 }2884 if (added_blank_line) {2885 if (!new_blank_lines_at_end)2886 found_new_blank_lines_at_end = hunk_linenr;2887 new_blank_lines_at_end++;2888 }2889 else if (is_blank_context)2890 ;2891 else2892 new_blank_lines_at_end = 0;2893 patch += len;2894 size -= len;2895 hunk_linenr++;2896 }2897 if (inaccurate_eof &&2898 old > oldlines && old[-1] == '\n' &&2899 newlines.len > 0 && newlines.buf[newlines.len - 1] == '\n') {2900 old--;2901 strbuf_setlen(&newlines, newlines.len - 1);2902 }29032904 leading = frag->leading;2905 trailing = frag->trailing;29062907 /*2908 * A hunk to change lines at the beginning would begin with2909 * @@ -1,L +N,M @@2910 * but we need to be careful. -U0 that inserts before the second2911 * line also has this pattern.2912 *2913 * And a hunk to add to an empty file would begin with2914 * @@ -0,0 +N,M @@2915 *2916 * In other words, a hunk that is (frag->oldpos <= 1) with or2917 * without leading context must match at the beginning.2918 */2919 match_beginning = (!frag->oldpos ||2920 (frag->oldpos == 1 && !state->unidiff_zero));29212922 /*2923 * A hunk without trailing lines must match at the end.2924 * However, we simply cannot tell if a hunk must match end2925 * from the lack of trailing lines if the patch was generated2926 * with unidiff without any context.2927 */2928 match_end = !state->unidiff_zero && !trailing;29292930 pos = frag->newpos ? (frag->newpos - 1) : 0;2931 preimage.buf = oldlines;2932 preimage.len = old - oldlines;2933 postimage.buf = newlines.buf;2934 postimage.len = newlines.len;2935 preimage.line = preimage.line_allocated;2936 postimage.line = postimage.line_allocated;29372938 for (;;) {29392940 applied_pos = find_pos(img, &preimage, &postimage, pos,2941 ws_rule, match_beginning, match_end);29422943 if (applied_pos >= 0)2944 break;29452946 /* Am I at my context limits? */2947 if ((leading <= state->p_context) && (trailing <= state->p_context))2948 break;2949 if (match_beginning || match_end) {2950 match_beginning = match_end = 0;2951 continue;2952 }29532954 /*2955 * Reduce the number of context lines; reduce both2956 * leading and trailing if they are equal otherwise2957 * just reduce the larger context.2958 */2959 if (leading >= trailing) {2960 remove_first_line(&preimage);2961 remove_first_line(&postimage);2962 pos--;2963 leading--;2964 }2965 if (trailing > leading) {2966 remove_last_line(&preimage);2967 remove_last_line(&postimage);2968 trailing--;2969 }2970 }29712972 if (applied_pos >= 0) {2973 if (new_blank_lines_at_end &&2974 preimage.nr + applied_pos >= img->nr &&2975 (ws_rule & WS_BLANK_AT_EOF) &&2976 ws_error_action != nowarn_ws_error) {2977 record_ws_error(state, WS_BLANK_AT_EOF, "+", 1,2978 found_new_blank_lines_at_end);2979 if (ws_error_action == correct_ws_error) {2980 while (new_blank_lines_at_end--)2981 remove_last_line(&postimage);2982 }2983 /*2984 * We would want to prevent write_out_results()2985 * from taking place in apply_patch() that follows2986 * the callchain led us here, which is:2987 * apply_patch->check_patch_list->check_patch->2988 * apply_data->apply_fragments->apply_one_fragment2989 */2990 if (ws_error_action == die_on_ws_error)2991 state->apply = 0;2992 }29932994 if (state->apply_verbosely && applied_pos != pos) {2995 int offset = applied_pos - pos;2996 if (state->apply_in_reverse)2997 offset = 0 - offset;2998 fprintf_ln(stderr,2999 Q_("Hunk #%d succeeded at %d (offset %d line).",3000 "Hunk #%d succeeded at %d (offset %d lines).",3001 offset),3002 nth_fragment, applied_pos + 1, offset);3003 }30043005 /*3006 * Warn if it was necessary to reduce the number3007 * of context lines.3008 */3009 if ((leading != frag->leading) ||3010 (trailing != frag->trailing))3011 fprintf_ln(stderr, _("Context reduced to (%ld/%ld)"3012 " to apply fragment at %d"),3013 leading, trailing, applied_pos+1);3014 update_image(state, img, applied_pos, &preimage, &postimage);3015 } else {3016 if (state->apply_verbosely)3017 error(_("while searching for:\n%.*s"),3018 (int)(old - oldlines), oldlines);3019 }30203021out:3022 free(oldlines);3023 strbuf_release(&newlines);3024 free(preimage.line_allocated);3025 free(postimage.line_allocated);30263027 return (applied_pos < 0);3028}30293030static int apply_binary_fragment(struct apply_state *state,3031 struct image *img,3032 struct patch *patch)3033{3034 struct fragment *fragment = patch->fragments;3035 unsigned long len;3036 void *dst;30373038 if (!fragment)3039 return error(_("missing binary patch data for '%s'"),3040 patch->new_name ?3041 patch->new_name :3042 patch->old_name);30433044 /* Binary patch is irreversible without the optional second hunk */3045 if (state->apply_in_reverse) {3046 if (!fragment->next)3047 return error("cannot reverse-apply a binary patch "3048 "without the reverse hunk to '%s'",3049 patch->new_name3050 ? patch->new_name : patch->old_name);3051 fragment = fragment->next;3052 }3053 switch (fragment->binary_patch_method) {3054 case BINARY_DELTA_DEFLATED:3055 dst = patch_delta(img->buf, img->len, fragment->patch,3056 fragment->size, &len);3057 if (!dst)3058 return -1;3059 clear_image(img);3060 img->buf = dst;3061 img->len = len;3062 return 0;3063 case BINARY_LITERAL_DEFLATED:3064 clear_image(img);3065 img->len = fragment->size;3066 img->buf = xmemdupz(fragment->patch, img->len);3067 return 0;3068 }3069 return -1;3070}30713072/*3073 * Replace "img" with the result of applying the binary patch.3074 * The binary patch data itself in patch->fragment is still kept3075 * but the preimage prepared by the caller in "img" is freed here3076 * or in the helper function apply_binary_fragment() this calls.3077 */3078static int apply_binary(struct apply_state *state,3079 struct image *img,3080 struct patch *patch)3081{3082 const char *name = patch->old_name ? patch->old_name : patch->new_name;3083 unsigned char sha1[20];30843085 /*3086 * For safety, we require patch index line to contain3087 * full 40-byte textual SHA1 for old and new, at least for now.3088 */3089 if (strlen(patch->old_sha1_prefix) != 40 ||3090 strlen(patch->new_sha1_prefix) != 40 ||3091 get_sha1_hex(patch->old_sha1_prefix, sha1) ||3092 get_sha1_hex(patch->new_sha1_prefix, sha1))3093 return error("cannot apply binary patch to '%s' "3094 "without full index line", name);30953096 if (patch->old_name) {3097 /*3098 * See if the old one matches what the patch3099 * applies to.3100 */3101 hash_sha1_file(img->buf, img->len, blob_type, sha1);3102 if (strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))3103 return error("the patch applies to '%s' (%s), "3104 "which does not match the "3105 "current contents.",3106 name, sha1_to_hex(sha1));3107 }3108 else {3109 /* Otherwise, the old one must be empty. */3110 if (img->len)3111 return error("the patch applies to an empty "3112 "'%s' but it is not empty", name);3113 }31143115 get_sha1_hex(patch->new_sha1_prefix, sha1);3116 if (is_null_sha1(sha1)) {3117 clear_image(img);3118 return 0; /* deletion patch */3119 }31203121 if (has_sha1_file(sha1)) {3122 /* We already have the postimage */3123 enum object_type type;3124 unsigned long size;3125 char *result;31263127 result = read_sha1_file(sha1, &type, &size);3128 if (!result)3129 return error("the necessary postimage %s for "3130 "'%s' cannot be read",3131 patch->new_sha1_prefix, name);3132 clear_image(img);3133 img->buf = result;3134 img->len = size;3135 } else {3136 /*3137 * We have verified buf matches the preimage;3138 * apply the patch data to it, which is stored3139 * in the patch->fragments->{patch,size}.3140 */3141 if (apply_binary_fragment(state, img, patch))3142 return error(_("binary patch does not apply to '%s'"),3143 name);31443145 /* verify that the result matches */3146 hash_sha1_file(img->buf, img->len, blob_type, sha1);3147 if (strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))3148 return error(_("binary patch to '%s' creates incorrect result (expecting %s, got %s)"),3149 name, patch->new_sha1_prefix, sha1_to_hex(sha1));3150 }31513152 return 0;3153}31543155static int apply_fragments(struct apply_state *state, struct image *img, struct patch *patch)3156{3157 struct fragment *frag = patch->fragments;3158 const char *name = patch->old_name ? patch->old_name : patch->new_name;3159 unsigned ws_rule = patch->ws_rule;3160 unsigned inaccurate_eof = patch->inaccurate_eof;3161 int nth = 0;31623163 if (patch->is_binary)3164 return apply_binary(state, img, patch);31653166 while (frag) {3167 nth++;3168 if (apply_one_fragment(state, img, frag, inaccurate_eof, ws_rule, nth)) {3169 error(_("patch failed: %s:%ld"), name, frag->oldpos);3170 if (!state->apply_with_reject)3171 return -1;3172 frag->rejected = 1;3173 }3174 frag = frag->next;3175 }3176 return 0;3177}31783179static int read_blob_object(struct strbuf *buf, const unsigned char *sha1, unsigned mode)3180{3181 if (S_ISGITLINK(mode)) {3182 strbuf_grow(buf, 100);3183 strbuf_addf(buf, "Subproject commit %s\n", sha1_to_hex(sha1));3184 } else {3185 enum object_type type;3186 unsigned long sz;3187 char *result;31883189 result = read_sha1_file(sha1, &type, &sz);3190 if (!result)3191 return -1;3192 /* XXX read_sha1_file NUL-terminates */3193 strbuf_attach(buf, result, sz, sz + 1);3194 }3195 return 0;3196}31973198static int read_file_or_gitlink(const struct cache_entry *ce, struct strbuf *buf)3199{3200 if (!ce)3201 return 0;3202 return read_blob_object(buf, ce->sha1, ce->ce_mode);3203}32043205static struct patch *in_fn_table(const char *name)3206{3207 struct string_list_item *item;32083209 if (name == NULL)3210 return NULL;32113212 item = string_list_lookup(&fn_table, name);3213 if (item != NULL)3214 return (struct patch *)item->util;32153216 return NULL;3217}32183219/*3220 * item->util in the filename table records the status of the path.3221 * Usually it points at a patch (whose result records the contents3222 * of it after applying it), but it could be PATH_WAS_DELETED for a3223 * path that a previously applied patch has already removed, or3224 * PATH_TO_BE_DELETED for a path that a later patch would remove.3225 *3226 * The latter is needed to deal with a case where two paths A and B3227 * are swapped by first renaming A to B and then renaming B to A;3228 * moving A to B should not be prevented due to presence of B as we3229 * will remove it in a later patch.3230 */3231#define PATH_TO_BE_DELETED ((struct patch *) -2)3232#define PATH_WAS_DELETED ((struct patch *) -1)32333234static int to_be_deleted(struct patch *patch)3235{3236 return patch == PATH_TO_BE_DELETED;3237}32383239static int was_deleted(struct patch *patch)3240{3241 return patch == PATH_WAS_DELETED;3242}32433244static void add_to_fn_table(struct patch *patch)3245{3246 struct string_list_item *item;32473248 /*3249 * Always add new_name unless patch is a deletion3250 * This should cover the cases for normal diffs,3251 * file creations and copies3252 */3253 if (patch->new_name != NULL) {3254 item = string_list_insert(&fn_table, patch->new_name);3255 item->util = patch;3256 }32573258 /*3259 * store a failure on rename/deletion cases because3260 * later chunks shouldn't patch old names3261 */3262 if ((patch->new_name == NULL) || (patch->is_rename)) {3263 item = string_list_insert(&fn_table, patch->old_name);3264 item->util = PATH_WAS_DELETED;3265 }3266}32673268static void prepare_fn_table(struct patch *patch)3269{3270 /*3271 * store information about incoming file deletion3272 */3273 while (patch) {3274 if ((patch->new_name == NULL) || (patch->is_rename)) {3275 struct string_list_item *item;3276 item = string_list_insert(&fn_table, patch->old_name);3277 item->util = PATH_TO_BE_DELETED;3278 }3279 patch = patch->next;3280 }3281}32823283static int checkout_target(struct index_state *istate,3284 struct cache_entry *ce, struct stat *st)3285{3286 struct checkout costate;32873288 memset(&costate, 0, sizeof(costate));3289 costate.base_dir = "";3290 costate.refresh_cache = 1;3291 costate.istate = istate;3292 if (checkout_entry(ce, &costate, NULL) || lstat(ce->name, st))3293 return error(_("cannot checkout %s"), ce->name);3294 return 0;3295}32963297static struct patch *previous_patch(struct patch *patch, int *gone)3298{3299 struct patch *previous;33003301 *gone = 0;3302 if (patch->is_copy || patch->is_rename)3303 return NULL; /* "git" patches do not depend on the order */33043305 previous = in_fn_table(patch->old_name);3306 if (!previous)3307 return NULL;33083309 if (to_be_deleted(previous))3310 return NULL; /* the deletion hasn't happened yet */33113312 if (was_deleted(previous))3313 *gone = 1;33143315 return previous;3316}33173318static int verify_index_match(const struct cache_entry *ce, struct stat *st)3319{3320 if (S_ISGITLINK(ce->ce_mode)) {3321 if (!S_ISDIR(st->st_mode))3322 return -1;3323 return 0;3324 }3325 return ce_match_stat(ce, st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE);3326}33273328#define SUBMODULE_PATCH_WITHOUT_INDEX 133293330static int load_patch_target(struct apply_state *state,3331 struct strbuf *buf,3332 const struct cache_entry *ce,3333 struct stat *st,3334 const char *name,3335 unsigned expected_mode)3336{3337 if (state->cached || state->check_index) {3338 if (read_file_or_gitlink(ce, buf))3339 return error(_("read of %s failed"), name);3340 } else if (name) {3341 if (S_ISGITLINK(expected_mode)) {3342 if (ce)3343 return read_file_or_gitlink(ce, buf);3344 else3345 return SUBMODULE_PATCH_WITHOUT_INDEX;3346 } else if (has_symlink_leading_path(name, strlen(name))) {3347 return error(_("reading from '%s' beyond a symbolic link"), name);3348 } else {3349 if (read_old_data(st, name, buf))3350 return error(_("read of %s failed"), name);3351 }3352 }3353 return 0;3354}33553356/*3357 * We are about to apply "patch"; populate the "image" with the3358 * current version we have, from the working tree or from the index,3359 * depending on the situation e.g. --cached/--index. If we are3360 * applying a non-git patch that incrementally updates the tree,3361 * we read from the result of a previous diff.3362 */3363static int load_preimage(struct apply_state *state,3364 struct image *image,3365 struct patch *patch, struct stat *st,3366 const struct cache_entry *ce)3367{3368 struct strbuf buf = STRBUF_INIT;3369 size_t len;3370 char *img;3371 struct patch *previous;3372 int status;33733374 previous = previous_patch(patch, &status);3375 if (status)3376 return error(_("path %s has been renamed/deleted"),3377 patch->old_name);3378 if (previous) {3379 /* We have a patched copy in memory; use that. */3380 strbuf_add(&buf, previous->result, previous->resultsize);3381 } else {3382 status = load_patch_target(state, &buf, ce, st,3383 patch->old_name, patch->old_mode);3384 if (status < 0)3385 return status;3386 else if (status == SUBMODULE_PATCH_WITHOUT_INDEX) {3387 /*3388 * There is no way to apply subproject3389 * patch without looking at the index.3390 * NEEDSWORK: shouldn't this be flagged3391 * as an error???3392 */3393 free_fragment_list(patch->fragments);3394 patch->fragments = NULL;3395 } else if (status) {3396 return error(_("read of %s failed"), patch->old_name);3397 }3398 }33993400 img = strbuf_detach(&buf, &len);3401 prepare_image(image, img, len, !patch->is_binary);3402 return 0;3403}34043405static int three_way_merge(struct image *image,3406 char *path,3407 const unsigned char *base,3408 const unsigned char *ours,3409 const unsigned char *theirs)3410{3411 mmfile_t base_file, our_file, their_file;3412 mmbuffer_t result = { NULL };3413 int status;34143415 read_mmblob(&base_file, base);3416 read_mmblob(&our_file, ours);3417 read_mmblob(&their_file, theirs);3418 status = ll_merge(&result, path,3419 &base_file, "base",3420 &our_file, "ours",3421 &their_file, "theirs", NULL);3422 free(base_file.ptr);3423 free(our_file.ptr);3424 free(their_file.ptr);3425 if (status < 0 || !result.ptr) {3426 free(result.ptr);3427 return -1;3428 }3429 clear_image(image);3430 image->buf = result.ptr;3431 image->len = result.size;34323433 return status;3434}34353436/*3437 * When directly falling back to add/add three-way merge, we read from3438 * the current contents of the new_name. In no cases other than that3439 * this function will be called.3440 */3441static int load_current(struct apply_state *state,3442 struct image *image,3443 struct patch *patch)3444{3445 struct strbuf buf = STRBUF_INIT;3446 int status, pos;3447 size_t len;3448 char *img;3449 struct stat st;3450 struct cache_entry *ce;3451 char *name = patch->new_name;3452 unsigned mode = patch->new_mode;34533454 if (!patch->is_new)3455 die("BUG: patch to %s is not a creation", patch->old_name);34563457 pos = cache_name_pos(name, strlen(name));3458 if (pos < 0)3459 return error(_("%s: does not exist in index"), name);3460 ce = active_cache[pos];3461 if (lstat(name, &st)) {3462 if (errno != ENOENT)3463 return error(_("%s: %s"), name, strerror(errno));3464 if (checkout_target(&the_index, ce, &st))3465 return -1;3466 }3467 if (verify_index_match(ce, &st))3468 return error(_("%s: does not match index"), name);34693470 status = load_patch_target(state, &buf, ce, &st, name, mode);3471 if (status < 0)3472 return status;3473 else if (status)3474 return -1;3475 img = strbuf_detach(&buf, &len);3476 prepare_image(image, img, len, !patch->is_binary);3477 return 0;3478}34793480static int try_threeway(struct apply_state *state,3481 struct image *image,3482 struct patch *patch,3483 struct stat *st,3484 const struct cache_entry *ce)3485{3486 unsigned char pre_sha1[20], post_sha1[20], our_sha1[20];3487 struct strbuf buf = STRBUF_INIT;3488 size_t len;3489 int status;3490 char *img;3491 struct image tmp_image;34923493 /* No point falling back to 3-way merge in these cases */3494 if (patch->is_delete ||3495 S_ISGITLINK(patch->old_mode) || S_ISGITLINK(patch->new_mode))3496 return -1;34973498 /* Preimage the patch was prepared for */3499 if (patch->is_new)3500 write_sha1_file("", 0, blob_type, pre_sha1);3501 else if (get_sha1(patch->old_sha1_prefix, pre_sha1) ||3502 read_blob_object(&buf, pre_sha1, patch->old_mode))3503 return error("repository lacks the necessary blob to fall back on 3-way merge.");35043505 fprintf(stderr, "Falling back to three-way merge...\n");35063507 img = strbuf_detach(&buf, &len);3508 prepare_image(&tmp_image, img, len, 1);3509 /* Apply the patch to get the post image */3510 if (apply_fragments(state, &tmp_image, patch) < 0) {3511 clear_image(&tmp_image);3512 return -1;3513 }3514 /* post_sha1[] is theirs */3515 write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, post_sha1);3516 clear_image(&tmp_image);35173518 /* our_sha1[] is ours */3519 if (patch->is_new) {3520 if (load_current(state, &tmp_image, patch))3521 return error("cannot read the current contents of '%s'",3522 patch->new_name);3523 } else {3524 if (load_preimage(state, &tmp_image, patch, st, ce))3525 return error("cannot read the current contents of '%s'",3526 patch->old_name);3527 }3528 write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, our_sha1);3529 clear_image(&tmp_image);35303531 /* in-core three-way merge between post and our using pre as base */3532 status = three_way_merge(image, patch->new_name,3533 pre_sha1, our_sha1, post_sha1);3534 if (status < 0) {3535 fprintf(stderr, "Failed to fall back on three-way merge...\n");3536 return status;3537 }35383539 if (status) {3540 patch->conflicted_threeway = 1;3541 if (patch->is_new)3542 oidclr(&patch->threeway_stage[0]);3543 else3544 hashcpy(patch->threeway_stage[0].hash, pre_sha1);3545 hashcpy(patch->threeway_stage[1].hash, our_sha1);3546 hashcpy(patch->threeway_stage[2].hash, post_sha1);3547 fprintf(stderr, "Applied patch to '%s' with conflicts.\n", patch->new_name);3548 } else {3549 fprintf(stderr, "Applied patch to '%s' cleanly.\n", patch->new_name);3550 }3551 return 0;3552}35533554static int apply_data(struct apply_state *state, struct patch *patch,3555 struct stat *st, const struct cache_entry *ce)3556{3557 struct image image;35583559 if (load_preimage(state, &image, patch, st, ce) < 0)3560 return -1;35613562 if (patch->direct_to_threeway ||3563 apply_fragments(state, &image, patch) < 0) {3564 /* Note: with --reject, apply_fragments() returns 0 */3565 if (!state->threeway || try_threeway(state, &image, patch, st, ce) < 0)3566 return -1;3567 }3568 patch->result = image.buf;3569 patch->resultsize = image.len;3570 add_to_fn_table(patch);3571 free(image.line_allocated);35723573 if (0 < patch->is_delete && patch->resultsize)3574 return error(_("removal patch leaves file contents"));35753576 return 0;3577}35783579/*3580 * If "patch" that we are looking at modifies or deletes what we have,3581 * we would want it not to lose any local modification we have, either3582 * in the working tree or in the index.3583 *3584 * This also decides if a non-git patch is a creation patch or a3585 * modification to an existing empty file. We do not check the state3586 * of the current tree for a creation patch in this function; the caller3587 * check_patch() separately makes sure (and errors out otherwise) that3588 * the path the patch creates does not exist in the current tree.3589 */3590static int check_preimage(struct apply_state *state,3591 struct patch *patch,3592 struct cache_entry **ce,3593 struct stat *st)3594{3595 const char *old_name = patch->old_name;3596 struct patch *previous = NULL;3597 int stat_ret = 0, status;3598 unsigned st_mode = 0;35993600 if (!old_name)3601 return 0;36023603 assert(patch->is_new <= 0);3604 previous = previous_patch(patch, &status);36053606 if (status)3607 return error(_("path %s has been renamed/deleted"), old_name);3608 if (previous) {3609 st_mode = previous->new_mode;3610 } else if (!state->cached) {3611 stat_ret = lstat(old_name, st);3612 if (stat_ret && errno != ENOENT)3613 return error(_("%s: %s"), old_name, strerror(errno));3614 }36153616 if (state->check_index && !previous) {3617 int pos = cache_name_pos(old_name, strlen(old_name));3618 if (pos < 0) {3619 if (patch->is_new < 0)3620 goto is_new;3621 return error(_("%s: does not exist in index"), old_name);3622 }3623 *ce = active_cache[pos];3624 if (stat_ret < 0) {3625 if (checkout_target(&the_index, *ce, st))3626 return -1;3627 }3628 if (!state->cached && verify_index_match(*ce, st))3629 return error(_("%s: does not match index"), old_name);3630 if (state->cached)3631 st_mode = (*ce)->ce_mode;3632 } else if (stat_ret < 0) {3633 if (patch->is_new < 0)3634 goto is_new;3635 return error(_("%s: %s"), old_name, strerror(errno));3636 }36373638 if (!state->cached && !previous)3639 st_mode = ce_mode_from_stat(*ce, st->st_mode);36403641 if (patch->is_new < 0)3642 patch->is_new = 0;3643 if (!patch->old_mode)3644 patch->old_mode = st_mode;3645 if ((st_mode ^ patch->old_mode) & S_IFMT)3646 return error(_("%s: wrong type"), old_name);3647 if (st_mode != patch->old_mode)3648 warning(_("%s has type %o, expected %o"),3649 old_name, st_mode, patch->old_mode);3650 if (!patch->new_mode && !patch->is_delete)3651 patch->new_mode = st_mode;3652 return 0;36533654 is_new:3655 patch->is_new = 1;3656 patch->is_delete = 0;3657 free(patch->old_name);3658 patch->old_name = NULL;3659 return 0;3660}366136623663#define EXISTS_IN_INDEX 13664#define EXISTS_IN_WORKTREE 236653666static int check_to_create(struct apply_state *state,3667 const char *new_name,3668 int ok_if_exists)3669{3670 struct stat nst;36713672 if (state->check_index &&3673 cache_name_pos(new_name, strlen(new_name)) >= 0 &&3674 !ok_if_exists)3675 return EXISTS_IN_INDEX;3676 if (state->cached)3677 return 0;36783679 if (!lstat(new_name, &nst)) {3680 if (S_ISDIR(nst.st_mode) || ok_if_exists)3681 return 0;3682 /*3683 * A leading component of new_name might be a symlink3684 * that is going to be removed with this patch, but3685 * still pointing at somewhere that has the path.3686 * In such a case, path "new_name" does not exist as3687 * far as git is concerned.3688 */3689 if (has_symlink_leading_path(new_name, strlen(new_name)))3690 return 0;36913692 return EXISTS_IN_WORKTREE;3693 } else if ((errno != ENOENT) && (errno != ENOTDIR)) {3694 return error("%s: %s", new_name, strerror(errno));3695 }3696 return 0;3697}36983699/*3700 * We need to keep track of how symlinks in the preimage are3701 * manipulated by the patches. A patch to add a/b/c where a/b3702 * is a symlink should not be allowed to affect the directory3703 * the symlink points at, but if the same patch removes a/b,3704 * it is perfectly fine, as the patch removes a/b to make room3705 * to create a directory a/b so that a/b/c can be created.3706 */3707static struct string_list symlink_changes;3708#define SYMLINK_GOES_AWAY 013709#define SYMLINK_IN_RESULT 0237103711static uintptr_t register_symlink_changes(const char *path, uintptr_t what)3712{3713 struct string_list_item *ent;37143715 ent = string_list_lookup(&symlink_changes, path);3716 if (!ent) {3717 ent = string_list_insert(&symlink_changes, path);3718 ent->util = (void *)0;3719 }3720 ent->util = (void *)(what | ((uintptr_t)ent->util));3721 return (uintptr_t)ent->util;3722}37233724static uintptr_t check_symlink_changes(const char *path)3725{3726 struct string_list_item *ent;37273728 ent = string_list_lookup(&symlink_changes, path);3729 if (!ent)3730 return 0;3731 return (uintptr_t)ent->util;3732}37333734static void prepare_symlink_changes(struct patch *patch)3735{3736 for ( ; patch; patch = patch->next) {3737 if ((patch->old_name && S_ISLNK(patch->old_mode)) &&3738 (patch->is_rename || patch->is_delete))3739 /* the symlink at patch->old_name is removed */3740 register_symlink_changes(patch->old_name, SYMLINK_GOES_AWAY);37413742 if (patch->new_name && S_ISLNK(patch->new_mode))3743 /* the symlink at patch->new_name is created or remains */3744 register_symlink_changes(patch->new_name, SYMLINK_IN_RESULT);3745 }3746}37473748static int path_is_beyond_symlink_1(struct apply_state *state, struct strbuf *name)3749{3750 do {3751 unsigned int change;37523753 while (--name->len && name->buf[name->len] != '/')3754 ; /* scan backwards */3755 if (!name->len)3756 break;3757 name->buf[name->len] = '\0';3758 change = check_symlink_changes(name->buf);3759 if (change & SYMLINK_IN_RESULT)3760 return 1;3761 if (change & SYMLINK_GOES_AWAY)3762 /*3763 * This cannot be "return 0", because we may3764 * see a new one created at a higher level.3765 */3766 continue;37673768 /* otherwise, check the preimage */3769 if (state->check_index) {3770 struct cache_entry *ce;37713772 ce = cache_file_exists(name->buf, name->len, ignore_case);3773 if (ce && S_ISLNK(ce->ce_mode))3774 return 1;3775 } else {3776 struct stat st;3777 if (!lstat(name->buf, &st) && S_ISLNK(st.st_mode))3778 return 1;3779 }3780 } while (1);3781 return 0;3782}37833784static int path_is_beyond_symlink(struct apply_state *state, const char *name_)3785{3786 int ret;3787 struct strbuf name = STRBUF_INIT;37883789 assert(*name_ != '\0');3790 strbuf_addstr(&name, name_);3791 ret = path_is_beyond_symlink_1(state, &name);3792 strbuf_release(&name);37933794 return ret;3795}37963797static void die_on_unsafe_path(struct patch *patch)3798{3799 const char *old_name = NULL;3800 const char *new_name = NULL;3801 if (patch->is_delete)3802 old_name = patch->old_name;3803 else if (!patch->is_new && !patch->is_copy)3804 old_name = patch->old_name;3805 if (!patch->is_delete)3806 new_name = patch->new_name;38073808 if (old_name && !verify_path(old_name))3809 die(_("invalid path '%s'"), old_name);3810 if (new_name && !verify_path(new_name))3811 die(_("invalid path '%s'"), new_name);3812}38133814/*3815 * Check and apply the patch in-core; leave the result in patch->result3816 * for the caller to write it out to the final destination.3817 */3818static int check_patch(struct apply_state *state, struct patch *patch)3819{3820 struct stat st;3821 const char *old_name = patch->old_name;3822 const char *new_name = patch->new_name;3823 const char *name = old_name ? old_name : new_name;3824 struct cache_entry *ce = NULL;3825 struct patch *tpatch;3826 int ok_if_exists;3827 int status;38283829 patch->rejected = 1; /* we will drop this after we succeed */38303831 status = check_preimage(state, patch, &ce, &st);3832 if (status)3833 return status;3834 old_name = patch->old_name;38353836 /*3837 * A type-change diff is always split into a patch to delete3838 * old, immediately followed by a patch to create new (see3839 * diff.c::run_diff()); in such a case it is Ok that the entry3840 * to be deleted by the previous patch is still in the working3841 * tree and in the index.3842 *3843 * A patch to swap-rename between A and B would first rename A3844 * to B and then rename B to A. While applying the first one,3845 * the presence of B should not stop A from getting renamed to3846 * B; ask to_be_deleted() about the later rename. Removal of3847 * B and rename from A to B is handled the same way by asking3848 * was_deleted().3849 */3850 if ((tpatch = in_fn_table(new_name)) &&3851 (was_deleted(tpatch) || to_be_deleted(tpatch)))3852 ok_if_exists = 1;3853 else3854 ok_if_exists = 0;38553856 if (new_name &&3857 ((0 < patch->is_new) || patch->is_rename || patch->is_copy)) {3858 int err = check_to_create(state, new_name, ok_if_exists);38593860 if (err && state->threeway) {3861 patch->direct_to_threeway = 1;3862 } else switch (err) {3863 case 0:3864 break; /* happy */3865 case EXISTS_IN_INDEX:3866 return error(_("%s: already exists in index"), new_name);3867 break;3868 case EXISTS_IN_WORKTREE:3869 return error(_("%s: already exists in working directory"),3870 new_name);3871 default:3872 return err;3873 }38743875 if (!patch->new_mode) {3876 if (0 < patch->is_new)3877 patch->new_mode = S_IFREG | 0644;3878 else3879 patch->new_mode = patch->old_mode;3880 }3881 }38823883 if (new_name && old_name) {3884 int same = !strcmp(old_name, new_name);3885 if (!patch->new_mode)3886 patch->new_mode = patch->old_mode;3887 if ((patch->old_mode ^ patch->new_mode) & S_IFMT) {3888 if (same)3889 return error(_("new mode (%o) of %s does not "3890 "match old mode (%o)"),3891 patch->new_mode, new_name,3892 patch->old_mode);3893 else3894 return error(_("new mode (%o) of %s does not "3895 "match old mode (%o) of %s"),3896 patch->new_mode, new_name,3897 patch->old_mode, old_name);3898 }3899 }39003901 if (!state->unsafe_paths)3902 die_on_unsafe_path(patch);39033904 /*3905 * An attempt to read from or delete a path that is beyond a3906 * symbolic link will be prevented by load_patch_target() that3907 * is called at the beginning of apply_data() so we do not3908 * have to worry about a patch marked with "is_delete" bit3909 * here. We however need to make sure that the patch result3910 * is not deposited to a path that is beyond a symbolic link3911 * here.3912 */3913 if (!patch->is_delete && path_is_beyond_symlink(state, patch->new_name))3914 return error(_("affected file '%s' is beyond a symbolic link"),3915 patch->new_name);39163917 if (apply_data(state, patch, &st, ce) < 0)3918 return error(_("%s: patch does not apply"), name);3919 patch->rejected = 0;3920 return 0;3921}39223923static int check_patch_list(struct apply_state *state, struct patch *patch)3924{3925 int err = 0;39263927 prepare_symlink_changes(patch);3928 prepare_fn_table(patch);3929 while (patch) {3930 if (state->apply_verbosely)3931 say_patch_name(stderr,3932 _("Checking patch %s..."), patch);3933 err |= check_patch(state, patch);3934 patch = patch->next;3935 }3936 return err;3937}39383939/* This function tries to read the sha1 from the current index */3940static int get_current_sha1(const char *path, unsigned char *sha1)3941{3942 int pos;39433944 if (read_cache() < 0)3945 return -1;3946 pos = cache_name_pos(path, strlen(path));3947 if (pos < 0)3948 return -1;3949 hashcpy(sha1, active_cache[pos]->sha1);3950 return 0;3951}39523953static int preimage_sha1_in_gitlink_patch(struct patch *p, unsigned char sha1[20])3954{3955 /*3956 * A usable gitlink patch has only one fragment (hunk) that looks like:3957 * @@ -1 +1 @@3958 * -Subproject commit <old sha1>3959 * +Subproject commit <new sha1>3960 * or3961 * @@ -1 +0,0 @@3962 * -Subproject commit <old sha1>3963 * for a removal patch.3964 */3965 struct fragment *hunk = p->fragments;3966 static const char heading[] = "-Subproject commit ";3967 char *preimage;39683969 if (/* does the patch have only one hunk? */3970 hunk && !hunk->next &&3971 /* is its preimage one line? */3972 hunk->oldpos == 1 && hunk->oldlines == 1 &&3973 /* does preimage begin with the heading? */3974 (preimage = memchr(hunk->patch, '\n', hunk->size)) != NULL &&3975 starts_with(++preimage, heading) &&3976 /* does it record full SHA-1? */3977 !get_sha1_hex(preimage + sizeof(heading) - 1, sha1) &&3978 preimage[sizeof(heading) + 40 - 1] == '\n' &&3979 /* does the abbreviated name on the index line agree with it? */3980 starts_with(preimage + sizeof(heading) - 1, p->old_sha1_prefix))3981 return 0; /* it all looks fine */39823983 /* we may have full object name on the index line */3984 return get_sha1_hex(p->old_sha1_prefix, sha1);3985}39863987/* Build an index that contains the just the files needed for a 3way merge */3988static void build_fake_ancestor(struct patch *list, const char *filename)3989{3990 struct patch *patch;3991 struct index_state result = { NULL };3992 static struct lock_file lock;39933994 /* Once we start supporting the reverse patch, it may be3995 * worth showing the new sha1 prefix, but until then...3996 */3997 for (patch = list; patch; patch = patch->next) {3998 unsigned char sha1[20];3999 struct cache_entry *ce;4000 const char *name;40014002 name = patch->old_name ? patch->old_name : patch->new_name;4003 if (0 < patch->is_new)4004 continue;40054006 if (S_ISGITLINK(patch->old_mode)) {4007 if (!preimage_sha1_in_gitlink_patch(patch, sha1))4008 ; /* ok, the textual part looks sane */4009 else4010 die("sha1 information is lacking or useless for submodule %s",4011 name);4012 } else if (!get_sha1_blob(patch->old_sha1_prefix, sha1)) {4013 ; /* ok */4014 } else if (!patch->lines_added && !patch->lines_deleted) {4015 /* mode-only change: update the current */4016 if (get_current_sha1(patch->old_name, sha1))4017 die("mode change for %s, which is not "4018 "in current HEAD", name);4019 } else4020 die("sha1 information is lacking or useless "4021 "(%s).", name);40224023 ce = make_cache_entry(patch->old_mode, sha1, name, 0, 0);4024 if (!ce)4025 die(_("make_cache_entry failed for path '%s'"), name);4026 if (add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD))4027 die ("Could not add %s to temporary index", name);4028 }40294030 hold_lock_file_for_update(&lock, filename, LOCK_DIE_ON_ERROR);4031 if (write_locked_index(&result, &lock, COMMIT_LOCK))4032 die ("Could not write temporary index to %s", filename);40334034 discard_index(&result);4035}40364037static void stat_patch_list(struct patch *patch)4038{4039 int files, adds, dels;40404041 for (files = adds = dels = 0 ; patch ; patch = patch->next) {4042 files++;4043 adds += patch->lines_added;4044 dels += patch->lines_deleted;4045 show_stats(patch);4046 }40474048 print_stat_summary(stdout, files, adds, dels);4049}40504051static void numstat_patch_list(struct apply_state *state,4052 struct patch *patch)4053{4054 for ( ; patch; patch = patch->next) {4055 const char *name;4056 name = patch->new_name ? patch->new_name : patch->old_name;4057 if (patch->is_binary)4058 printf("-\t-\t");4059 else4060 printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);4061 write_name_quoted(name, stdout, state->line_termination);4062 }4063}40644065static void show_file_mode_name(const char *newdelete, unsigned int mode, const char *name)4066{4067 if (mode)4068 printf(" %s mode %06o %s\n", newdelete, mode, name);4069 else4070 printf(" %s %s\n", newdelete, name);4071}40724073static void show_mode_change(struct patch *p, int show_name)4074{4075 if (p->old_mode && p->new_mode && p->old_mode != p->new_mode) {4076 if (show_name)4077 printf(" mode change %06o => %06o %s\n",4078 p->old_mode, p->new_mode, p->new_name);4079 else4080 printf(" mode change %06o => %06o\n",4081 p->old_mode, p->new_mode);4082 }4083}40844085static void show_rename_copy(struct patch *p)4086{4087 const char *renamecopy = p->is_rename ? "rename" : "copy";4088 const char *old, *new;40894090 /* Find common prefix */4091 old = p->old_name;4092 new = p->new_name;4093 while (1) {4094 const char *slash_old, *slash_new;4095 slash_old = strchr(old, '/');4096 slash_new = strchr(new, '/');4097 if (!slash_old ||4098 !slash_new ||4099 slash_old - old != slash_new - new ||4100 memcmp(old, new, slash_new - new))4101 break;4102 old = slash_old + 1;4103 new = slash_new + 1;4104 }4105 /* p->old_name thru old is the common prefix, and old and new4106 * through the end of names are renames4107 */4108 if (old != p->old_name)4109 printf(" %s %.*s{%s => %s} (%d%%)\n", renamecopy,4110 (int)(old - p->old_name), p->old_name,4111 old, new, p->score);4112 else4113 printf(" %s %s => %s (%d%%)\n", renamecopy,4114 p->old_name, p->new_name, p->score);4115 show_mode_change(p, 0);4116}41174118static void summary_patch_list(struct patch *patch)4119{4120 struct patch *p;41214122 for (p = patch; p; p = p->next) {4123 if (p->is_new)4124 show_file_mode_name("create", p->new_mode, p->new_name);4125 else if (p->is_delete)4126 show_file_mode_name("delete", p->old_mode, p->old_name);4127 else {4128 if (p->is_rename || p->is_copy)4129 show_rename_copy(p);4130 else {4131 if (p->score) {4132 printf(" rewrite %s (%d%%)\n",4133 p->new_name, p->score);4134 show_mode_change(p, 0);4135 }4136 else4137 show_mode_change(p, 1);4138 }4139 }4140 }4141}41424143static void patch_stats(struct patch *patch)4144{4145 int lines = patch->lines_added + patch->lines_deleted;41464147 if (lines > max_change)4148 max_change = lines;4149 if (patch->old_name) {4150 int len = quote_c_style(patch->old_name, NULL, NULL, 0);4151 if (!len)4152 len = strlen(patch->old_name);4153 if (len > max_len)4154 max_len = len;4155 }4156 if (patch->new_name) {4157 int len = quote_c_style(patch->new_name, NULL, NULL, 0);4158 if (!len)4159 len = strlen(patch->new_name);4160 if (len > max_len)4161 max_len = len;4162 }4163}41644165static void remove_file(struct apply_state *state, struct patch *patch, int rmdir_empty)4166{4167 if (state->update_index) {4168 if (remove_file_from_cache(patch->old_name) < 0)4169 die(_("unable to remove %s from index"), patch->old_name);4170 }4171 if (!state->cached) {4172 if (!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {4173 remove_path(patch->old_name);4174 }4175 }4176}41774178static void add_index_file(struct apply_state *state,4179 const char *path,4180 unsigned mode,4181 void *buf,4182 unsigned long size)4183{4184 struct stat st;4185 struct cache_entry *ce;4186 int namelen = strlen(path);4187 unsigned ce_size = cache_entry_size(namelen);41884189 if (!state->update_index)4190 return;41914192 ce = xcalloc(1, ce_size);4193 memcpy(ce->name, path, namelen);4194 ce->ce_mode = create_ce_mode(mode);4195 ce->ce_flags = create_ce_flags(0);4196 ce->ce_namelen = namelen;4197 if (S_ISGITLINK(mode)) {4198 const char *s;41994200 if (!skip_prefix(buf, "Subproject commit ", &s) ||4201 get_sha1_hex(s, ce->sha1))4202 die(_("corrupt patch for submodule %s"), path);4203 } else {4204 if (!state->cached) {4205 if (lstat(path, &st) < 0)4206 die_errno(_("unable to stat newly created file '%s'"),4207 path);4208 fill_stat_cache_info(ce, &st);4209 }4210 if (write_sha1_file(buf, size, blob_type, ce->sha1) < 0)4211 die(_("unable to create backing store for newly created file %s"), path);4212 }4213 if (add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) < 0)4214 die(_("unable to add cache entry for %s"), path);4215}42164217static int try_create_file(const char *path, unsigned int mode, const char *buf, unsigned long size)4218{4219 int fd;4220 struct strbuf nbuf = STRBUF_INIT;42214222 if (S_ISGITLINK(mode)) {4223 struct stat st;4224 if (!lstat(path, &st) && S_ISDIR(st.st_mode))4225 return 0;4226 return mkdir(path, 0777);4227 }42284229 if (has_symlinks && S_ISLNK(mode))4230 /* Although buf:size is counted string, it also is NUL4231 * terminated.4232 */4233 return symlink(buf, path);42344235 fd = open(path, O_CREAT | O_EXCL | O_WRONLY, (mode & 0100) ? 0777 : 0666);4236 if (fd < 0)4237 return -1;42384239 if (convert_to_working_tree(path, buf, size, &nbuf)) {4240 size = nbuf.len;4241 buf = nbuf.buf;4242 }4243 write_or_die(fd, buf, size);4244 strbuf_release(&nbuf);42454246 if (close(fd) < 0)4247 die_errno(_("closing file '%s'"), path);4248 return 0;4249}42504251/*4252 * We optimistically assume that the directories exist,4253 * which is true 99% of the time anyway. If they don't,4254 * we create them and try again.4255 */4256static void create_one_file(struct apply_state *state,4257 char *path,4258 unsigned mode,4259 const char *buf,4260 unsigned long size)4261{4262 if (state->cached)4263 return;4264 if (!try_create_file(path, mode, buf, size))4265 return;42664267 if (errno == ENOENT) {4268 if (safe_create_leading_directories(path))4269 return;4270 if (!try_create_file(path, mode, buf, size))4271 return;4272 }42734274 if (errno == EEXIST || errno == EACCES) {4275 /* We may be trying to create a file where a directory4276 * used to be.4277 */4278 struct stat st;4279 if (!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))4280 errno = EEXIST;4281 }42824283 if (errno == EEXIST) {4284 unsigned int nr = getpid();42854286 for (;;) {4287 char newpath[PATH_MAX];4288 mksnpath(newpath, sizeof(newpath), "%s~%u", path, nr);4289 if (!try_create_file(newpath, mode, buf, size)) {4290 if (!rename(newpath, path))4291 return;4292 unlink_or_warn(newpath);4293 break;4294 }4295 if (errno != EEXIST)4296 break;4297 ++nr;4298 }4299 }4300 die_errno(_("unable to write file '%s' mode %o"), path, mode);4301}43024303static void add_conflicted_stages_file(struct apply_state *state,4304 struct patch *patch)4305{4306 int stage, namelen;4307 unsigned ce_size, mode;4308 struct cache_entry *ce;43094310 if (!state->update_index)4311 return;4312 namelen = strlen(patch->new_name);4313 ce_size = cache_entry_size(namelen);4314 mode = patch->new_mode ? patch->new_mode : (S_IFREG | 0644);43154316 remove_file_from_cache(patch->new_name);4317 for (stage = 1; stage < 4; stage++) {4318 if (is_null_oid(&patch->threeway_stage[stage - 1]))4319 continue;4320 ce = xcalloc(1, ce_size);4321 memcpy(ce->name, patch->new_name, namelen);4322 ce->ce_mode = create_ce_mode(mode);4323 ce->ce_flags = create_ce_flags(stage);4324 ce->ce_namelen = namelen;4325 hashcpy(ce->sha1, patch->threeway_stage[stage - 1].hash);4326 if (add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) < 0)4327 die(_("unable to add cache entry for %s"), patch->new_name);4328 }4329}43304331static void create_file(struct apply_state *state, struct patch *patch)4332{4333 char *path = patch->new_name;4334 unsigned mode = patch->new_mode;4335 unsigned long size = patch->resultsize;4336 char *buf = patch->result;43374338 if (!mode)4339 mode = S_IFREG | 0644;4340 create_one_file(state, path, mode, buf, size);43414342 if (patch->conflicted_threeway)4343 add_conflicted_stages_file(state, patch);4344 else4345 add_index_file(state, path, mode, buf, size);4346}43474348/* phase zero is to remove, phase one is to create */4349static void write_out_one_result(struct apply_state *state,4350 struct patch *patch,4351 int phase)4352{4353 if (patch->is_delete > 0) {4354 if (phase == 0)4355 remove_file(state, patch, 1);4356 return;4357 }4358 if (patch->is_new > 0 || patch->is_copy) {4359 if (phase == 1)4360 create_file(state, patch);4361 return;4362 }4363 /*4364 * Rename or modification boils down to the same4365 * thing: remove the old, write the new4366 */4367 if (phase == 0)4368 remove_file(state, patch, patch->is_rename);4369 if (phase == 1)4370 create_file(state, patch);4371}43724373static int write_out_one_reject(struct apply_state *state, struct patch *patch)4374{4375 FILE *rej;4376 char namebuf[PATH_MAX];4377 struct fragment *frag;4378 int cnt = 0;4379 struct strbuf sb = STRBUF_INIT;43804381 for (cnt = 0, frag = patch->fragments; frag; frag = frag->next) {4382 if (!frag->rejected)4383 continue;4384 cnt++;4385 }43864387 if (!cnt) {4388 if (state->apply_verbosely)4389 say_patch_name(stderr,4390 _("Applied patch %s cleanly."), patch);4391 return 0;4392 }43934394 /* This should not happen, because a removal patch that leaves4395 * contents are marked "rejected" at the patch level.4396 */4397 if (!patch->new_name)4398 die(_("internal error"));43994400 /* Say this even without --verbose */4401 strbuf_addf(&sb, Q_("Applying patch %%s with %d reject...",4402 "Applying patch %%s with %d rejects...",4403 cnt),4404 cnt);4405 say_patch_name(stderr, sb.buf, patch);4406 strbuf_release(&sb);44074408 cnt = strlen(patch->new_name);4409 if (ARRAY_SIZE(namebuf) <= cnt + 5) {4410 cnt = ARRAY_SIZE(namebuf) - 5;4411 warning(_("truncating .rej filename to %.*s.rej"),4412 cnt - 1, patch->new_name);4413 }4414 memcpy(namebuf, patch->new_name, cnt);4415 memcpy(namebuf + cnt, ".rej", 5);44164417 rej = fopen(namebuf, "w");4418 if (!rej)4419 return error(_("cannot open %s: %s"), namebuf, strerror(errno));44204421 /* Normal git tools never deal with .rej, so do not pretend4422 * this is a git patch by saying --git or giving extended4423 * headers. While at it, maybe please "kompare" that wants4424 * the trailing TAB and some garbage at the end of line ;-).4425 */4426 fprintf(rej, "diff a/%s b/%s\t(rejected hunks)\n",4427 patch->new_name, patch->new_name);4428 for (cnt = 1, frag = patch->fragments;4429 frag;4430 cnt++, frag = frag->next) {4431 if (!frag->rejected) {4432 fprintf_ln(stderr, _("Hunk #%d applied cleanly."), cnt);4433 continue;4434 }4435 fprintf_ln(stderr, _("Rejected hunk #%d."), cnt);4436 fprintf(rej, "%.*s", frag->size, frag->patch);4437 if (frag->patch[frag->size-1] != '\n')4438 fputc('\n', rej);4439 }4440 fclose(rej);4441 return -1;4442}44434444static int write_out_results(struct apply_state *state, struct patch *list)4445{4446 int phase;4447 int errs = 0;4448 struct patch *l;4449 struct string_list cpath = STRING_LIST_INIT_DUP;44504451 for (phase = 0; phase < 2; phase++) {4452 l = list;4453 while (l) {4454 if (l->rejected)4455 errs = 1;4456 else {4457 write_out_one_result(state, l, phase);4458 if (phase == 1) {4459 if (write_out_one_reject(state, l))4460 errs = 1;4461 if (l->conflicted_threeway) {4462 string_list_append(&cpath, l->new_name);4463 errs = 1;4464 }4465 }4466 }4467 l = l->next;4468 }4469 }44704471 if (cpath.nr) {4472 struct string_list_item *item;44734474 string_list_sort(&cpath);4475 for_each_string_list_item(item, &cpath)4476 fprintf(stderr, "U %s\n", item->string);4477 string_list_clear(&cpath, 0);44784479 rerere(0);4480 }44814482 return errs;4483}44844485static struct lock_file lock_file;44864487#define INACCURATE_EOF (1<<0)4488#define RECOUNT (1<<1)44894490static int apply_patch(struct apply_state *state,4491 int fd,4492 const char *filename,4493 int options)4494{4495 size_t offset;4496 struct strbuf buf = STRBUF_INIT; /* owns the patch text */4497 struct patch *list = NULL, **listp = &list;4498 int skipped_patch = 0;44994500 state->patch_input_file = filename;4501 read_patch_file(&buf, fd);4502 offset = 0;4503 while (offset < buf.len) {4504 struct patch *patch;4505 int nr;45064507 patch = xcalloc(1, sizeof(*patch));4508 patch->inaccurate_eof = !!(options & INACCURATE_EOF);4509 patch->recount = !!(options & RECOUNT);4510 nr = parse_chunk(state, buf.buf + offset, buf.len - offset, patch);4511 if (nr < 0) {4512 free_patch(patch);4513 break;4514 }4515 if (state->apply_in_reverse)4516 reverse_patches(patch);4517 if (use_patch(state, patch)) {4518 patch_stats(patch);4519 *listp = patch;4520 listp = &patch->next;4521 }4522 else {4523 if (state->apply_verbosely)4524 say_patch_name(stderr, _("Skipped patch '%s'."), patch);4525 free_patch(patch);4526 skipped_patch++;4527 }4528 offset += nr;4529 }45304531 if (!list && !skipped_patch)4532 die(_("unrecognized input"));45334534 if (state->whitespace_error && (ws_error_action == die_on_ws_error))4535 state->apply = 0;45364537 state->update_index = state->check_index && state->apply;4538 if (state->update_index && newfd < 0)4539 newfd = hold_locked_index(&lock_file, 1);45404541 if (state->check_index) {4542 if (read_cache() < 0)4543 die(_("unable to read index file"));4544 }45454546 if ((state->check || state->apply) &&4547 check_patch_list(state, list) < 0 &&4548 !state->apply_with_reject)4549 exit(1);45504551 if (state->apply && write_out_results(state, list)) {4552 if (state->apply_with_reject)4553 exit(1);4554 /* with --3way, we still need to write the index out */4555 return 1;4556 }45574558 if (state->fake_ancestor)4559 build_fake_ancestor(list, state->fake_ancestor);45604561 if (state->diffstat)4562 stat_patch_list(list);45634564 if (state->numstat)4565 numstat_patch_list(state, list);45664567 if (state->summary)4568 summary_patch_list(list);45694570 free_patch_list(list);4571 strbuf_release(&buf);4572 string_list_clear(&fn_table, 0);4573 return 0;4574}45754576static void git_apply_config(void)4577{4578 git_config_get_string_const("apply.whitespace", &apply_default_whitespace);4579 git_config_get_string_const("apply.ignorewhitespace", &apply_default_ignorewhitespace);4580 git_config(git_default_config, NULL);4581}45824583static int option_parse_exclude(const struct option *opt,4584 const char *arg, int unset)4585{4586 struct apply_state *state = opt->value;4587 add_name_limit(state, arg, 1);4588 return 0;4589}45904591static int option_parse_include(const struct option *opt,4592 const char *arg, int unset)4593{4594 struct apply_state *state = opt->value;4595 add_name_limit(state, arg, 0);4596 state->has_include = 1;4597 return 0;4598}45994600static int option_parse_p(const struct option *opt,4601 const char *arg,4602 int unset)4603{4604 struct apply_state *state = opt->value;4605 state->p_value = atoi(arg);4606 state->p_value_known = 1;4607 return 0;4608}46094610static int option_parse_space_change(const struct option *opt,4611 const char *arg, int unset)4612{4613 if (unset)4614 ws_ignore_action = ignore_ws_none;4615 else4616 ws_ignore_action = ignore_ws_change;4617 return 0;4618}46194620static int option_parse_whitespace(const struct option *opt,4621 const char *arg, int unset)4622{4623 struct apply_state *state = opt->value;46244625 state->whitespace_option = arg;4626 parse_whitespace_option(arg);4627 return 0;4628}46294630static int option_parse_directory(const struct option *opt,4631 const char *arg, int unset)4632{4633 struct apply_state *state = opt->value;4634 strbuf_reset(&state->root);4635 strbuf_addstr(&state->root, arg);4636 strbuf_complete(&state->root, '/');4637 return 0;4638}46394640static void init_apply_state(struct apply_state *state, const char *prefix)4641{4642 memset(state, 0, sizeof(*state));4643 state->prefix = prefix;4644 state->prefix_length = state->prefix ? strlen(state->prefix) : 0;4645 state->apply = 1;4646 state->line_termination = '\n';4647 state->p_value = 1;4648 state->p_context = UINT_MAX;4649 strbuf_init(&state->root, 0);46504651 git_apply_config();4652 if (apply_default_whitespace)4653 parse_whitespace_option(apply_default_whitespace);4654 if (apply_default_ignorewhitespace)4655 parse_ignorewhitespace_option(apply_default_ignorewhitespace);4656}46574658static void clear_apply_state(struct apply_state *state)4659{4660 string_list_clear(&state->limit_by_name, 0);4661 strbuf_release(&state->root);4662}46634664int cmd_apply(int argc, const char **argv, const char *prefix)4665{4666 int i;4667 int errs = 0;4668 int is_not_gitdir = !startup_info->have_repository;4669 int force_apply = 0;4670 int options = 0;4671 int read_stdin = 1;4672 struct apply_state state;46734674 struct option builtin_apply_options[] = {4675 { OPTION_CALLBACK, 0, "exclude", &state, N_("path"),4676 N_("don't apply changes matching the given path"),4677 0, option_parse_exclude },4678 { OPTION_CALLBACK, 0, "include", &state, N_("path"),4679 N_("apply changes matching the given path"),4680 0, option_parse_include },4681 { OPTION_CALLBACK, 'p', NULL, &state, N_("num"),4682 N_("remove <num> leading slashes from traditional diff paths"),4683 0, option_parse_p },4684 OPT_BOOL(0, "no-add", &state.no_add,4685 N_("ignore additions made by the patch")),4686 OPT_BOOL(0, "stat", &state.diffstat,4687 N_("instead of applying the patch, output diffstat for the input")),4688 OPT_NOOP_NOARG(0, "allow-binary-replacement"),4689 OPT_NOOP_NOARG(0, "binary"),4690 OPT_BOOL(0, "numstat", &state.numstat,4691 N_("show number of added and deleted lines in decimal notation")),4692 OPT_BOOL(0, "summary", &state.summary,4693 N_("instead of applying the patch, output a summary for the input")),4694 OPT_BOOL(0, "check", &state.check,4695 N_("instead of applying the patch, see if the patch is applicable")),4696 OPT_BOOL(0, "index", &state.check_index,4697 N_("make sure the patch is applicable to the current index")),4698 OPT_BOOL(0, "cached", &state.cached,4699 N_("apply a patch without touching the working tree")),4700 OPT_BOOL(0, "unsafe-paths", &state.unsafe_paths,4701 N_("accept a patch that touches outside the working area")),4702 OPT_BOOL(0, "apply", &force_apply,4703 N_("also apply the patch (use with --stat/--summary/--check)")),4704 OPT_BOOL('3', "3way", &state.threeway,4705 N_( "attempt three-way merge if a patch does not apply")),4706 OPT_FILENAME(0, "build-fake-ancestor", &state.fake_ancestor,4707 N_("build a temporary index based on embedded index information")),4708 /* Think twice before adding "--nul" synonym to this */4709 OPT_SET_INT('z', NULL, &state.line_termination,4710 N_("paths are separated with NUL character"), '\0'),4711 OPT_INTEGER('C', NULL, &state.p_context,4712 N_("ensure at least <n> lines of context match")),4713 { OPTION_CALLBACK, 0, "whitespace", &state, N_("action"),4714 N_("detect new or modified lines that have whitespace errors"),4715 0, option_parse_whitespace },4716 { OPTION_CALLBACK, 0, "ignore-space-change", NULL, NULL,4717 N_("ignore changes in whitespace when finding context"),4718 PARSE_OPT_NOARG, option_parse_space_change },4719 { OPTION_CALLBACK, 0, "ignore-whitespace", NULL, NULL,4720 N_("ignore changes in whitespace when finding context"),4721 PARSE_OPT_NOARG, option_parse_space_change },4722 OPT_BOOL('R', "reverse", &state.apply_in_reverse,4723 N_("apply the patch in reverse")),4724 OPT_BOOL(0, "unidiff-zero", &state.unidiff_zero,4725 N_("don't expect at least one line of context")),4726 OPT_BOOL(0, "reject", &state.apply_with_reject,4727 N_("leave the rejected hunks in corresponding *.rej files")),4728 OPT_BOOL(0, "allow-overlap", &state.allow_overlap,4729 N_("allow overlapping hunks")),4730 OPT__VERBOSE(&state.apply_verbosely, N_("be verbose")),4731 OPT_BIT(0, "inaccurate-eof", &options,4732 N_("tolerate incorrectly detected missing new-line at the end of file"),4733 INACCURATE_EOF),4734 OPT_BIT(0, "recount", &options,4735 N_("do not trust the line counts in the hunk headers"),4736 RECOUNT),4737 { OPTION_CALLBACK, 0, "directory", &state, N_("root"),4738 N_("prepend <root> to all filenames"),4739 0, option_parse_directory },4740 OPT_END()4741 };47424743 init_apply_state(&state, prefix);47444745 argc = parse_options(argc, argv, state.prefix, builtin_apply_options,4746 apply_usage, 0);47474748 if (state.apply_with_reject && state.threeway)4749 die("--reject and --3way cannot be used together.");4750 if (state.cached && state.threeway)4751 die("--cached and --3way cannot be used together.");4752 if (state.threeway) {4753 if (is_not_gitdir)4754 die(_("--3way outside a repository"));4755 state.check_index = 1;4756 }4757 if (state.apply_with_reject)4758 state.apply = state.apply_verbosely = 1;4759 if (!force_apply && (state.diffstat || state.numstat || state.summary || state.check || state.fake_ancestor))4760 state.apply = 0;4761 if (state.check_index && is_not_gitdir)4762 die(_("--index outside a repository"));4763 if (state.cached) {4764 if (is_not_gitdir)4765 die(_("--cached outside a repository"));4766 state.check_index = 1;4767 }4768 if (state.check_index)4769 state.unsafe_paths = 0;47704771 for (i = 0; i < argc; i++) {4772 const char *arg = argv[i];4773 int fd;47744775 if (!strcmp(arg, "-")) {4776 errs |= apply_patch(&state, 0, "<stdin>", options);4777 read_stdin = 0;4778 continue;4779 } else if (0 < state.prefix_length)4780 arg = prefix_filename(state.prefix,4781 state.prefix_length,4782 arg);47834784 fd = open(arg, O_RDONLY);4785 if (fd < 0)4786 die_errno(_("can't open patch '%s'"), arg);4787 read_stdin = 0;4788 set_default_whitespace_mode(&state, state.whitespace_option);4789 errs |= apply_patch(&state, fd, arg, options);4790 close(fd);4791 }4792 set_default_whitespace_mode(&state, state.whitespace_option);4793 if (read_stdin)4794 errs |= apply_patch(&state, 0, "<stdin>", options);4795 if (state.whitespace_error) {4796 if (squelch_whitespace_errors &&4797 squelch_whitespace_errors < state.whitespace_error) {4798 int squelched =4799 state.whitespace_error - squelch_whitespace_errors;4800 warning(Q_("squelched %d whitespace error",4801 "squelched %d whitespace errors",4802 squelched),4803 squelched);4804 }4805 if (ws_error_action == die_on_ws_error)4806 die(Q_("%d line adds whitespace errors.",4807 "%d lines add whitespace errors.",4808 state.whitespace_error),4809 state.whitespace_error);4810 if (applied_after_fixing_ws && state.apply)4811 warning("%d line%s applied after"4812 " fixing whitespace errors.",4813 applied_after_fixing_ws,4814 applied_after_fixing_ws == 1 ? "" : "s");4815 else if (state.whitespace_error)4816 warning(Q_("%d line adds whitespace errors.",4817 "%d lines add whitespace errors.",4818 state.whitespace_error),4819 state.whitespace_error);4820 }48214822 if (state.update_index) {4823 if (write_locked_index(&the_index, &lock_file, COMMIT_LOCK))4824 die(_("Unable to write new index file"));4825 }48264827 clear_apply_state(&state);48284829 return !!errs;4830}