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#include "apply.h" 24 25static const char * const apply_usage[] = { 26 N_("git apply [<options>] [<patch>...]"), 27 NULL 28}; 29 30static void parse_whitespace_option(struct apply_state *state, const char *option) 31{ 32 if (!option) { 33 state->ws_error_action = warn_on_ws_error; 34 return; 35 } 36 if (!strcmp(option, "warn")) { 37 state->ws_error_action = warn_on_ws_error; 38 return; 39 } 40 if (!strcmp(option, "nowarn")) { 41 state->ws_error_action = nowarn_ws_error; 42 return; 43 } 44 if (!strcmp(option, "error")) { 45 state->ws_error_action = die_on_ws_error; 46 return; 47 } 48 if (!strcmp(option, "error-all")) { 49 state->ws_error_action = die_on_ws_error; 50 state->squelch_whitespace_errors = 0; 51 return; 52 } 53 if (!strcmp(option, "strip") || !strcmp(option, "fix")) { 54 state->ws_error_action = correct_ws_error; 55 return; 56 } 57 die(_("unrecognized whitespace option '%s'"), option); 58} 59 60static void parse_ignorewhitespace_option(struct apply_state *state, 61 const char *option) 62{ 63 if (!option || !strcmp(option, "no") || 64 !strcmp(option, "false") || !strcmp(option, "never") || 65 !strcmp(option, "none")) { 66 state->ws_ignore_action = ignore_ws_none; 67 return; 68 } 69 if (!strcmp(option, "change")) { 70 state->ws_ignore_action = ignore_ws_change; 71 return; 72 } 73 die(_("unrecognized whitespace ignore option '%s'"), option); 74} 75 76static void set_default_whitespace_mode(struct apply_state *state) 77{ 78 if (!state->whitespace_option && !apply_default_whitespace) 79 state->ws_error_action = (state->apply ? warn_on_ws_error : nowarn_ws_error); 80} 81 82/* 83 * This represents one "hunk" from a patch, starting with 84 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The 85 * patch text is pointed at by patch, and its byte length 86 * is stored in size. leading and trailing are the number 87 * of context lines. 88 */ 89struct fragment { 90 unsigned long leading, trailing; 91 unsigned long oldpos, oldlines; 92 unsigned long newpos, newlines; 93 /* 94 * 'patch' is usually borrowed from buf in apply_patch(), 95 * but some codepaths store an allocated buffer. 96 */ 97 const char *patch; 98 unsigned free_patch:1, 99 rejected:1; 100 int size; 101 int linenr; 102 struct fragment *next; 103}; 104 105/* 106 * When dealing with a binary patch, we reuse "leading" field 107 * to store the type of the binary hunk, either deflated "delta" 108 * or deflated "literal". 109 */ 110#define binary_patch_method leading 111#define BINARY_DELTA_DEFLATED 1 112#define BINARY_LITERAL_DEFLATED 2 113 114/* 115 * This represents a "patch" to a file, both metainfo changes 116 * such as creation/deletion, filemode and content changes represented 117 * as a series of fragments. 118 */ 119struct patch { 120 char *new_name, *old_name, *def_name; 121 unsigned int old_mode, new_mode; 122 int is_new, is_delete; /* -1 = unknown, 0 = false, 1 = true */ 123 int rejected; 124 unsigned ws_rule; 125 int lines_added, lines_deleted; 126 int score; 127 unsigned int is_toplevel_relative:1; 128 unsigned int inaccurate_eof:1; 129 unsigned int is_binary:1; 130 unsigned int is_copy:1; 131 unsigned int is_rename:1; 132 unsigned int recount:1; 133 unsigned int conflicted_threeway:1; 134 unsigned int direct_to_threeway:1; 135 struct fragment *fragments; 136 char *result; 137 size_t resultsize; 138 char old_sha1_prefix[41]; 139 char new_sha1_prefix[41]; 140 struct patch *next; 141 142 /* three-way fallback result */ 143 struct object_id threeway_stage[3]; 144}; 145 146static void free_fragment_list(struct fragment *list) 147{ 148 while (list) { 149 struct fragment *next = list->next; 150 if (list->free_patch) 151 free((char *)list->patch); 152 free(list); 153 list = next; 154 } 155} 156 157static void free_patch(struct patch *patch) 158{ 159 free_fragment_list(patch->fragments); 160 free(patch->def_name); 161 free(patch->old_name); 162 free(patch->new_name); 163 free(patch->result); 164 free(patch); 165} 166 167static void free_patch_list(struct patch *list) 168{ 169 while (list) { 170 struct patch *next = list->next; 171 free_patch(list); 172 list = next; 173 } 174} 175 176/* 177 * A line in a file, len-bytes long (includes the terminating LF, 178 * except for an incomplete line at the end if the file ends with 179 * one), and its contents hashes to 'hash'. 180 */ 181struct line { 182 size_t len; 183 unsigned hash : 24; 184 unsigned flag : 8; 185#define LINE_COMMON 1 186#define LINE_PATCHED 2 187}; 188 189/* 190 * This represents a "file", which is an array of "lines". 191 */ 192struct image { 193 char *buf; 194 size_t len; 195 size_t nr; 196 size_t alloc; 197 struct line *line_allocated; 198 struct line *line; 199}; 200 201static uint32_t hash_line(const char *cp, size_t len) 202{ 203 size_t i; 204 uint32_t h; 205 for (i = 0, h = 0; i < len; i++) { 206 if (!isspace(cp[i])) { 207 h = h * 3 + (cp[i] & 0xff); 208 } 209 } 210 return h; 211} 212 213/* 214 * Compare lines s1 of length n1 and s2 of length n2, ignoring 215 * whitespace difference. Returns 1 if they match, 0 otherwise 216 */ 217static int fuzzy_matchlines(const char *s1, size_t n1, 218 const char *s2, size_t n2) 219{ 220 const char *last1 = s1 + n1 - 1; 221 const char *last2 = s2 + n2 - 1; 222 int result = 0; 223 224 /* ignore line endings */ 225 while ((*last1 == '\r') || (*last1 == '\n')) 226 last1--; 227 while ((*last2 == '\r') || (*last2 == '\n')) 228 last2--; 229 230 /* skip leading whitespaces, if both begin with whitespace */ 231 if (s1 <= last1 && s2 <= last2 && isspace(*s1) && isspace(*s2)) { 232 while (isspace(*s1) && (s1 <= last1)) 233 s1++; 234 while (isspace(*s2) && (s2 <= last2)) 235 s2++; 236 } 237 /* early return if both lines are empty */ 238 if ((s1 > last1) && (s2 > last2)) 239 return 1; 240 while (!result) { 241 result = *s1++ - *s2++; 242 /* 243 * Skip whitespace inside. We check for whitespace on 244 * both buffers because we don't want "a b" to match 245 * "ab" 246 */ 247 if (isspace(*s1) && isspace(*s2)) { 248 while (isspace(*s1) && s1 <= last1) 249 s1++; 250 while (isspace(*s2) && s2 <= last2) 251 s2++; 252 } 253 /* 254 * If we reached the end on one side only, 255 * lines don't match 256 */ 257 if ( 258 ((s2 > last2) && (s1 <= last1)) || 259 ((s1 > last1) && (s2 <= last2))) 260 return 0; 261 if ((s1 > last1) && (s2 > last2)) 262 break; 263 } 264 265 return !result; 266} 267 268static void add_line_info(struct image *img, const char *bol, size_t len, unsigned flag) 269{ 270 ALLOC_GROW(img->line_allocated, img->nr + 1, img->alloc); 271 img->line_allocated[img->nr].len = len; 272 img->line_allocated[img->nr].hash = hash_line(bol, len); 273 img->line_allocated[img->nr].flag = flag; 274 img->nr++; 275} 276 277/* 278 * "buf" has the file contents to be patched (read from various sources). 279 * attach it to "image" and add line-based index to it. 280 * "image" now owns the "buf". 281 */ 282static void prepare_image(struct image *image, char *buf, size_t len, 283 int prepare_linetable) 284{ 285 const char *cp, *ep; 286 287 memset(image, 0, sizeof(*image)); 288 image->buf = buf; 289 image->len = len; 290 291 if (!prepare_linetable) 292 return; 293 294 ep = image->buf + image->len; 295 cp = image->buf; 296 while (cp < ep) { 297 const char *next; 298 for (next = cp; next < ep && *next != '\n'; next++) 299 ; 300 if (next < ep) 301 next++; 302 add_line_info(image, cp, next - cp, 0); 303 cp = next; 304 } 305 image->line = image->line_allocated; 306} 307 308static void clear_image(struct image *image) 309{ 310 free(image->buf); 311 free(image->line_allocated); 312 memset(image, 0, sizeof(*image)); 313} 314 315/* fmt must contain _one_ %s and no other substitution */ 316static void say_patch_name(FILE *output, const char *fmt, struct patch *patch) 317{ 318 struct strbuf sb = STRBUF_INIT; 319 320 if (patch->old_name && patch->new_name && 321 strcmp(patch->old_name, patch->new_name)) { 322 quote_c_style(patch->old_name, &sb, NULL, 0); 323 strbuf_addstr(&sb, " => "); 324 quote_c_style(patch->new_name, &sb, NULL, 0); 325 } else { 326 const char *n = patch->new_name; 327 if (!n) 328 n = patch->old_name; 329 quote_c_style(n, &sb, NULL, 0); 330 } 331 fprintf(output, fmt, sb.buf); 332 fputc('\n', output); 333 strbuf_release(&sb); 334} 335 336#define SLOP (16) 337 338static int read_patch_file(struct strbuf *sb, int fd) 339{ 340 if (strbuf_read(sb, fd, 0) < 0) 341 return error_errno("git apply: failed to read"); 342 343 /* 344 * Make sure that we have some slop in the buffer 345 * so that we can do speculative "memcmp" etc, and 346 * see to it that it is NUL-filled. 347 */ 348 strbuf_grow(sb, SLOP); 349 memset(sb->buf + sb->len, 0, SLOP); 350 return 0; 351} 352 353static unsigned long linelen(const char *buffer, unsigned long size) 354{ 355 unsigned long len = 0; 356 while (size--) { 357 len++; 358 if (*buffer++ == '\n') 359 break; 360 } 361 return len; 362} 363 364static int is_dev_null(const char *str) 365{ 366 return skip_prefix(str, "/dev/null", &str) && isspace(*str); 367} 368 369#define TERM_SPACE 1 370#define TERM_TAB 2 371 372static int name_terminate(int c, int terminate) 373{ 374 if (c == ' ' && !(terminate & TERM_SPACE)) 375 return 0; 376 if (c == '\t' && !(terminate & TERM_TAB)) 377 return 0; 378 379 return 1; 380} 381 382/* remove double slashes to make --index work with such filenames */ 383static char *squash_slash(char *name) 384{ 385 int i = 0, j = 0; 386 387 if (!name) 388 return NULL; 389 390 while (name[i]) { 391 if ((name[j++] = name[i++]) == '/') 392 while (name[i] == '/') 393 i++; 394 } 395 name[j] = '\0'; 396 return name; 397} 398 399static char *find_name_gnu(struct apply_state *state, 400 const char *line, 401 const char *def, 402 int p_value) 403{ 404 struct strbuf name = STRBUF_INIT; 405 char *cp; 406 407 /* 408 * Proposed "new-style" GNU patch/diff format; see 409 * http://marc.info/?l=git&m=112927316408690&w=2 410 */ 411 if (unquote_c_style(&name, line, NULL)) { 412 strbuf_release(&name); 413 return NULL; 414 } 415 416 for (cp = name.buf; p_value; p_value--) { 417 cp = strchr(cp, '/'); 418 if (!cp) { 419 strbuf_release(&name); 420 return NULL; 421 } 422 cp++; 423 } 424 425 strbuf_remove(&name, 0, cp - name.buf); 426 if (state->root.len) 427 strbuf_insert(&name, 0, state->root.buf, state->root.len); 428 return squash_slash(strbuf_detach(&name, NULL)); 429} 430 431static size_t sane_tz_len(const char *line, size_t len) 432{ 433 const char *tz, *p; 434 435 if (len < strlen(" +0500") || line[len-strlen(" +0500")] != ' ') 436 return 0; 437 tz = line + len - strlen(" +0500"); 438 439 if (tz[1] != '+' && tz[1] != '-') 440 return 0; 441 442 for (p = tz + 2; p != line + len; p++) 443 if (!isdigit(*p)) 444 return 0; 445 446 return line + len - tz; 447} 448 449static size_t tz_with_colon_len(const char *line, size_t len) 450{ 451 const char *tz, *p; 452 453 if (len < strlen(" +08:00") || line[len - strlen(":00")] != ':') 454 return 0; 455 tz = line + len - strlen(" +08:00"); 456 457 if (tz[0] != ' ' || (tz[1] != '+' && tz[1] != '-')) 458 return 0; 459 p = tz + 2; 460 if (!isdigit(*p++) || !isdigit(*p++) || *p++ != ':' || 461 !isdigit(*p++) || !isdigit(*p++)) 462 return 0; 463 464 return line + len - tz; 465} 466 467static size_t date_len(const char *line, size_t len) 468{ 469 const char *date, *p; 470 471 if (len < strlen("72-02-05") || line[len-strlen("-05")] != '-') 472 return 0; 473 p = date = line + len - strlen("72-02-05"); 474 475 if (!isdigit(*p++) || !isdigit(*p++) || *p++ != '-' || 476 !isdigit(*p++) || !isdigit(*p++) || *p++ != '-' || 477 !isdigit(*p++) || !isdigit(*p++)) /* Not a date. */ 478 return 0; 479 480 if (date - line >= strlen("19") && 481 isdigit(date[-1]) && isdigit(date[-2])) /* 4-digit year */ 482 date -= strlen("19"); 483 484 return line + len - date; 485} 486 487static size_t short_time_len(const char *line, size_t len) 488{ 489 const char *time, *p; 490 491 if (len < strlen(" 07:01:32") || line[len-strlen(":32")] != ':') 492 return 0; 493 p = time = line + len - strlen(" 07:01:32"); 494 495 /* Permit 1-digit hours? */ 496 if (*p++ != ' ' || 497 !isdigit(*p++) || !isdigit(*p++) || *p++ != ':' || 498 !isdigit(*p++) || !isdigit(*p++) || *p++ != ':' || 499 !isdigit(*p++) || !isdigit(*p++)) /* Not a time. */ 500 return 0; 501 502 return line + len - time; 503} 504 505static size_t fractional_time_len(const char *line, size_t len) 506{ 507 const char *p; 508 size_t n; 509 510 /* Expected format: 19:41:17.620000023 */ 511 if (!len || !isdigit(line[len - 1])) 512 return 0; 513 p = line + len - 1; 514 515 /* Fractional seconds. */ 516 while (p > line && isdigit(*p)) 517 p--; 518 if (*p != '.') 519 return 0; 520 521 /* Hours, minutes, and whole seconds. */ 522 n = short_time_len(line, p - line); 523 if (!n) 524 return 0; 525 526 return line + len - p + n; 527} 528 529static size_t trailing_spaces_len(const char *line, size_t len) 530{ 531 const char *p; 532 533 /* Expected format: ' ' x (1 or more) */ 534 if (!len || line[len - 1] != ' ') 535 return 0; 536 537 p = line + len; 538 while (p != line) { 539 p--; 540 if (*p != ' ') 541 return line + len - (p + 1); 542 } 543 544 /* All spaces! */ 545 return len; 546} 547 548static size_t diff_timestamp_len(const char *line, size_t len) 549{ 550 const char *end = line + len; 551 size_t n; 552 553 /* 554 * Posix: 2010-07-05 19:41:17 555 * GNU: 2010-07-05 19:41:17.620000023 -0500 556 */ 557 558 if (!isdigit(end[-1])) 559 return 0; 560 561 n = sane_tz_len(line, end - line); 562 if (!n) 563 n = tz_with_colon_len(line, end - line); 564 end -= n; 565 566 n = short_time_len(line, end - line); 567 if (!n) 568 n = fractional_time_len(line, end - line); 569 end -= n; 570 571 n = date_len(line, end - line); 572 if (!n) /* No date. Too bad. */ 573 return 0; 574 end -= n; 575 576 if (end == line) /* No space before date. */ 577 return 0; 578 if (end[-1] == '\t') { /* Success! */ 579 end--; 580 return line + len - end; 581 } 582 if (end[-1] != ' ') /* No space before date. */ 583 return 0; 584 585 /* Whitespace damage. */ 586 end -= trailing_spaces_len(line, end - line); 587 return line + len - end; 588} 589 590static char *find_name_common(struct apply_state *state, 591 const char *line, 592 const char *def, 593 int p_value, 594 const char *end, 595 int terminate) 596{ 597 int len; 598 const char *start = NULL; 599 600 if (p_value == 0) 601 start = line; 602 while (line != end) { 603 char c = *line; 604 605 if (!end && isspace(c)) { 606 if (c == '\n') 607 break; 608 if (name_terminate(c, terminate)) 609 break; 610 } 611 line++; 612 if (c == '/' && !--p_value) 613 start = line; 614 } 615 if (!start) 616 return squash_slash(xstrdup_or_null(def)); 617 len = line - start; 618 if (!len) 619 return squash_slash(xstrdup_or_null(def)); 620 621 /* 622 * Generally we prefer the shorter name, especially 623 * if the other one is just a variation of that with 624 * something else tacked on to the end (ie "file.orig" 625 * or "file~"). 626 */ 627 if (def) { 628 int deflen = strlen(def); 629 if (deflen < len && !strncmp(start, def, deflen)) 630 return squash_slash(xstrdup(def)); 631 } 632 633 if (state->root.len) { 634 char *ret = xstrfmt("%s%.*s", state->root.buf, len, start); 635 return squash_slash(ret); 636 } 637 638 return squash_slash(xmemdupz(start, len)); 639} 640 641static char *find_name(struct apply_state *state, 642 const char *line, 643 char *def, 644 int p_value, 645 int terminate) 646{ 647 if (*line == '"') { 648 char *name = find_name_gnu(state, line, def, p_value); 649 if (name) 650 return name; 651 } 652 653 return find_name_common(state, line, def, p_value, NULL, terminate); 654} 655 656static char *find_name_traditional(struct apply_state *state, 657 const char *line, 658 char *def, 659 int p_value) 660{ 661 size_t len; 662 size_t date_len; 663 664 if (*line == '"') { 665 char *name = find_name_gnu(state, line, def, p_value); 666 if (name) 667 return name; 668 } 669 670 len = strchrnul(line, '\n') - line; 671 date_len = diff_timestamp_len(line, len); 672 if (!date_len) 673 return find_name_common(state, line, def, p_value, NULL, TERM_TAB); 674 len -= date_len; 675 676 return find_name_common(state, line, def, p_value, line + len, 0); 677} 678 679static int count_slashes(const char *cp) 680{ 681 int cnt = 0; 682 char ch; 683 684 while ((ch = *cp++)) 685 if (ch == '/') 686 cnt++; 687 return cnt; 688} 689 690/* 691 * Given the string after "--- " or "+++ ", guess the appropriate 692 * p_value for the given patch. 693 */ 694static int guess_p_value(struct apply_state *state, const char *nameline) 695{ 696 char *name, *cp; 697 int val = -1; 698 699 if (is_dev_null(nameline)) 700 return -1; 701 name = find_name_traditional(state, nameline, NULL, 0); 702 if (!name) 703 return -1; 704 cp = strchr(name, '/'); 705 if (!cp) 706 val = 0; 707 else if (state->prefix) { 708 /* 709 * Does it begin with "a/$our-prefix" and such? Then this is 710 * very likely to apply to our directory. 711 */ 712 if (!strncmp(name, state->prefix, state->prefix_length)) 713 val = count_slashes(state->prefix); 714 else { 715 cp++; 716 if (!strncmp(cp, state->prefix, state->prefix_length)) 717 val = count_slashes(state->prefix) + 1; 718 } 719 } 720 free(name); 721 return val; 722} 723 724/* 725 * Does the ---/+++ line have the POSIX timestamp after the last HT? 726 * GNU diff puts epoch there to signal a creation/deletion event. Is 727 * this such a timestamp? 728 */ 729static int has_epoch_timestamp(const char *nameline) 730{ 731 /* 732 * We are only interested in epoch timestamp; any non-zero 733 * fraction cannot be one, hence "(\.0+)?" in the regexp below. 734 * For the same reason, the date must be either 1969-12-31 or 735 * 1970-01-01, and the seconds part must be "00". 736 */ 737 const char stamp_regexp[] = 738 "^(1969-12-31|1970-01-01)" 739 " " 740 "[0-2][0-9]:[0-5][0-9]:00(\\.0+)?" 741 " " 742 "([-+][0-2][0-9]:?[0-5][0-9])\n"; 743 const char *timestamp = NULL, *cp, *colon; 744 static regex_t *stamp; 745 regmatch_t m[10]; 746 int zoneoffset; 747 int hourminute; 748 int status; 749 750 for (cp = nameline; *cp != '\n'; cp++) { 751 if (*cp == '\t') 752 timestamp = cp + 1; 753 } 754 if (!timestamp) 755 return 0; 756 if (!stamp) { 757 stamp = xmalloc(sizeof(*stamp)); 758 if (regcomp(stamp, stamp_regexp, REG_EXTENDED)) { 759 warning(_("Cannot prepare timestamp regexp %s"), 760 stamp_regexp); 761 return 0; 762 } 763 } 764 765 status = regexec(stamp, timestamp, ARRAY_SIZE(m), m, 0); 766 if (status) { 767 if (status != REG_NOMATCH) 768 warning(_("regexec returned %d for input: %s"), 769 status, timestamp); 770 return 0; 771 } 772 773 zoneoffset = strtol(timestamp + m[3].rm_so + 1, (char **) &colon, 10); 774 if (*colon == ':') 775 zoneoffset = zoneoffset * 60 + strtol(colon + 1, NULL, 10); 776 else 777 zoneoffset = (zoneoffset / 100) * 60 + (zoneoffset % 100); 778 if (timestamp[m[3].rm_so] == '-') 779 zoneoffset = -zoneoffset; 780 781 /* 782 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31 783 * (west of GMT) or 1970-01-01 (east of GMT) 784 */ 785 if ((zoneoffset < 0 && memcmp(timestamp, "1969-12-31", 10)) || 786 (0 <= zoneoffset && memcmp(timestamp, "1970-01-01", 10))) 787 return 0; 788 789 hourminute = (strtol(timestamp + 11, NULL, 10) * 60 + 790 strtol(timestamp + 14, NULL, 10) - 791 zoneoffset); 792 793 return ((zoneoffset < 0 && hourminute == 1440) || 794 (0 <= zoneoffset && !hourminute)); 795} 796 797/* 798 * Get the name etc info from the ---/+++ lines of a traditional patch header 799 * 800 * FIXME! The end-of-filename heuristics are kind of screwy. For existing 801 * files, we can happily check the index for a match, but for creating a 802 * new file we should try to match whatever "patch" does. I have no idea. 803 */ 804static void parse_traditional_patch(struct apply_state *state, 805 const char *first, 806 const char *second, 807 struct patch *patch) 808{ 809 char *name; 810 811 first += 4; /* skip "--- " */ 812 second += 4; /* skip "+++ " */ 813 if (!state->p_value_known) { 814 int p, q; 815 p = guess_p_value(state, first); 816 q = guess_p_value(state, second); 817 if (p < 0) p = q; 818 if (0 <= p && p == q) { 819 state->p_value = p; 820 state->p_value_known = 1; 821 } 822 } 823 if (is_dev_null(first)) { 824 patch->is_new = 1; 825 patch->is_delete = 0; 826 name = find_name_traditional(state, second, NULL, state->p_value); 827 patch->new_name = name; 828 } else if (is_dev_null(second)) { 829 patch->is_new = 0; 830 patch->is_delete = 1; 831 name = find_name_traditional(state, first, NULL, state->p_value); 832 patch->old_name = name; 833 } else { 834 char *first_name; 835 first_name = find_name_traditional(state, first, NULL, state->p_value); 836 name = find_name_traditional(state, second, first_name, state->p_value); 837 free(first_name); 838 if (has_epoch_timestamp(first)) { 839 patch->is_new = 1; 840 patch->is_delete = 0; 841 patch->new_name = name; 842 } else if (has_epoch_timestamp(second)) { 843 patch->is_new = 0; 844 patch->is_delete = 1; 845 patch->old_name = name; 846 } else { 847 patch->old_name = name; 848 patch->new_name = xstrdup_or_null(name); 849 } 850 } 851 if (!name) 852 die(_("unable to find filename in patch at line %d"), state->linenr); 853} 854 855static int gitdiff_hdrend(struct apply_state *state, 856 const char *line, 857 struct patch *patch) 858{ 859 return -1; 860} 861 862/* 863 * We're anal about diff header consistency, to make 864 * sure that we don't end up having strange ambiguous 865 * patches floating around. 866 * 867 * As a result, gitdiff_{old|new}name() will check 868 * their names against any previous information, just 869 * to make sure.. 870 */ 871#define DIFF_OLD_NAME 0 872#define DIFF_NEW_NAME 1 873 874static void gitdiff_verify_name(struct apply_state *state, 875 const char *line, 876 int isnull, 877 char **name, 878 int side) 879{ 880 if (!*name && !isnull) { 881 *name = find_name(state, line, NULL, state->p_value, TERM_TAB); 882 return; 883 } 884 885 if (*name) { 886 int len = strlen(*name); 887 char *another; 888 if (isnull) 889 die(_("git apply: bad git-diff - expected /dev/null, got %s on line %d"), 890 *name, state->linenr); 891 another = find_name(state, line, NULL, state->p_value, TERM_TAB); 892 if (!another || memcmp(another, *name, len + 1)) 893 die((side == DIFF_NEW_NAME) ? 894 _("git apply: bad git-diff - inconsistent new filename on line %d") : 895 _("git apply: bad git-diff - inconsistent old filename on line %d"), state->linenr); 896 free(another); 897 } else { 898 /* expect "/dev/null" */ 899 if (memcmp("/dev/null", line, 9) || line[9] != '\n') 900 die(_("git apply: bad git-diff - expected /dev/null on line %d"), state->linenr); 901 } 902} 903 904static int gitdiff_oldname(struct apply_state *state, 905 const char *line, 906 struct patch *patch) 907{ 908 gitdiff_verify_name(state, line, 909 patch->is_new, &patch->old_name, 910 DIFF_OLD_NAME); 911 return 0; 912} 913 914static int gitdiff_newname(struct apply_state *state, 915 const char *line, 916 struct patch *patch) 917{ 918 gitdiff_verify_name(state, line, 919 patch->is_delete, &patch->new_name, 920 DIFF_NEW_NAME); 921 return 0; 922} 923 924static int gitdiff_oldmode(struct apply_state *state, 925 const char *line, 926 struct patch *patch) 927{ 928 patch->old_mode = strtoul(line, NULL, 8); 929 return 0; 930} 931 932static int gitdiff_newmode(struct apply_state *state, 933 const char *line, 934 struct patch *patch) 935{ 936 patch->new_mode = strtoul(line, NULL, 8); 937 return 0; 938} 939 940static int gitdiff_delete(struct apply_state *state, 941 const char *line, 942 struct patch *patch) 943{ 944 patch->is_delete = 1; 945 free(patch->old_name); 946 patch->old_name = xstrdup_or_null(patch->def_name); 947 return gitdiff_oldmode(state, line, patch); 948} 949 950static int gitdiff_newfile(struct apply_state *state, 951 const char *line, 952 struct patch *patch) 953{ 954 patch->is_new = 1; 955 free(patch->new_name); 956 patch->new_name = xstrdup_or_null(patch->def_name); 957 return gitdiff_newmode(state, line, patch); 958} 959 960static int gitdiff_copysrc(struct apply_state *state, 961 const char *line, 962 struct patch *patch) 963{ 964 patch->is_copy = 1; 965 free(patch->old_name); 966 patch->old_name = find_name(state, line, NULL, state->p_value ? state->p_value - 1 : 0, 0); 967 return 0; 968} 969 970static int gitdiff_copydst(struct apply_state *state, 971 const char *line, 972 struct patch *patch) 973{ 974 patch->is_copy = 1; 975 free(patch->new_name); 976 patch->new_name = find_name(state, line, NULL, state->p_value ? state->p_value - 1 : 0, 0); 977 return 0; 978} 979 980static int gitdiff_renamesrc(struct apply_state *state, 981 const char *line, 982 struct patch *patch) 983{ 984 patch->is_rename = 1; 985 free(patch->old_name); 986 patch->old_name = find_name(state, line, NULL, state->p_value ? state->p_value - 1 : 0, 0); 987 return 0; 988} 989 990static int gitdiff_renamedst(struct apply_state *state, 991 const char *line, 992 struct patch *patch) 993{ 994 patch->is_rename = 1; 995 free(patch->new_name); 996 patch->new_name = find_name(state, line, NULL, state->p_value ? state->p_value - 1 : 0, 0); 997 return 0; 998} 9991000static int gitdiff_similarity(struct apply_state *state,1001 const char *line,1002 struct patch *patch)1003{1004 unsigned long val = strtoul(line, NULL, 10);1005 if (val <= 100)1006 patch->score = val;1007 return 0;1008}10091010static int gitdiff_dissimilarity(struct apply_state *state,1011 const char *line,1012 struct patch *patch)1013{1014 unsigned long val = strtoul(line, NULL, 10);1015 if (val <= 100)1016 patch->score = val;1017 return 0;1018}10191020static int gitdiff_index(struct apply_state *state,1021 const char *line,1022 struct patch *patch)1023{1024 /*1025 * index line is N hexadecimal, "..", N hexadecimal,1026 * and optional space with octal mode.1027 */1028 const char *ptr, *eol;1029 int len;10301031 ptr = strchr(line, '.');1032 if (!ptr || ptr[1] != '.' || 40 < ptr - line)1033 return 0;1034 len = ptr - line;1035 memcpy(patch->old_sha1_prefix, line, len);1036 patch->old_sha1_prefix[len] = 0;10371038 line = ptr + 2;1039 ptr = strchr(line, ' ');1040 eol = strchrnul(line, '\n');10411042 if (!ptr || eol < ptr)1043 ptr = eol;1044 len = ptr - line;10451046 if (40 < len)1047 return 0;1048 memcpy(patch->new_sha1_prefix, line, len);1049 patch->new_sha1_prefix[len] = 0;1050 if (*ptr == ' ')1051 patch->old_mode = strtoul(ptr+1, NULL, 8);1052 return 0;1053}10541055/*1056 * This is normal for a diff that doesn't change anything: we'll fall through1057 * into the next diff. Tell the parser to break out.1058 */1059static int gitdiff_unrecognized(struct apply_state *state,1060 const char *line,1061 struct patch *patch)1062{1063 return -1;1064}10651066/*1067 * Skip p_value leading components from "line"; as we do not accept1068 * absolute paths, return NULL in that case.1069 */1070static const char *skip_tree_prefix(struct apply_state *state,1071 const char *line,1072 int llen)1073{1074 int nslash;1075 int i;10761077 if (!state->p_value)1078 return (llen && line[0] == '/') ? NULL : line;10791080 nslash = state->p_value;1081 for (i = 0; i < llen; i++) {1082 int ch = line[i];1083 if (ch == '/' && --nslash <= 0)1084 return (i == 0) ? NULL : &line[i + 1];1085 }1086 return NULL;1087}10881089/*1090 * This is to extract the same name that appears on "diff --git"1091 * line. We do not find and return anything if it is a rename1092 * patch, and it is OK because we will find the name elsewhere.1093 * We need to reliably find name only when it is mode-change only,1094 * creation or deletion of an empty file. In any of these cases,1095 * both sides are the same name under a/ and b/ respectively.1096 */1097static char *git_header_name(struct apply_state *state,1098 const char *line,1099 int llen)1100{1101 const char *name;1102 const char *second = NULL;1103 size_t len, line_len;11041105 line += strlen("diff --git ");1106 llen -= strlen("diff --git ");11071108 if (*line == '"') {1109 const char *cp;1110 struct strbuf first = STRBUF_INIT;1111 struct strbuf sp = STRBUF_INIT;11121113 if (unquote_c_style(&first, line, &second))1114 goto free_and_fail1;11151116 /* strip the a/b prefix including trailing slash */1117 cp = skip_tree_prefix(state, first.buf, first.len);1118 if (!cp)1119 goto free_and_fail1;1120 strbuf_remove(&first, 0, cp - first.buf);11211122 /*1123 * second points at one past closing dq of name.1124 * find the second name.1125 */1126 while ((second < line + llen) && isspace(*second))1127 second++;11281129 if (line + llen <= second)1130 goto free_and_fail1;1131 if (*second == '"') {1132 if (unquote_c_style(&sp, second, NULL))1133 goto free_and_fail1;1134 cp = skip_tree_prefix(state, sp.buf, sp.len);1135 if (!cp)1136 goto free_and_fail1;1137 /* They must match, otherwise ignore */1138 if (strcmp(cp, first.buf))1139 goto free_and_fail1;1140 strbuf_release(&sp);1141 return strbuf_detach(&first, NULL);1142 }11431144 /* unquoted second */1145 cp = skip_tree_prefix(state, second, line + llen - second);1146 if (!cp)1147 goto free_and_fail1;1148 if (line + llen - cp != first.len ||1149 memcmp(first.buf, cp, first.len))1150 goto free_and_fail1;1151 return strbuf_detach(&first, NULL);11521153 free_and_fail1:1154 strbuf_release(&first);1155 strbuf_release(&sp);1156 return NULL;1157 }11581159 /* unquoted first name */1160 name = skip_tree_prefix(state, line, llen);1161 if (!name)1162 return NULL;11631164 /*1165 * since the first name is unquoted, a dq if exists must be1166 * the beginning of the second name.1167 */1168 for (second = name; second < line + llen; second++) {1169 if (*second == '"') {1170 struct strbuf sp = STRBUF_INIT;1171 const char *np;11721173 if (unquote_c_style(&sp, second, NULL))1174 goto free_and_fail2;11751176 np = skip_tree_prefix(state, sp.buf, sp.len);1177 if (!np)1178 goto free_and_fail2;11791180 len = sp.buf + sp.len - np;1181 if (len < second - name &&1182 !strncmp(np, name, len) &&1183 isspace(name[len])) {1184 /* Good */1185 strbuf_remove(&sp, 0, np - sp.buf);1186 return strbuf_detach(&sp, NULL);1187 }11881189 free_and_fail2:1190 strbuf_release(&sp);1191 return NULL;1192 }1193 }11941195 /*1196 * Accept a name only if it shows up twice, exactly the same1197 * form.1198 */1199 second = strchr(name, '\n');1200 if (!second)1201 return NULL;1202 line_len = second - name;1203 for (len = 0 ; ; len++) {1204 switch (name[len]) {1205 default:1206 continue;1207 case '\n':1208 return NULL;1209 case '\t': case ' ':1210 /*1211 * Is this the separator between the preimage1212 * and the postimage pathname? Again, we are1213 * only interested in the case where there is1214 * no rename, as this is only to set def_name1215 * and a rename patch has the names elsewhere1216 * in an unambiguous form.1217 */1218 if (!name[len + 1])1219 return NULL; /* no postimage name */1220 second = skip_tree_prefix(state, name + len + 1,1221 line_len - (len + 1));1222 if (!second)1223 return NULL;1224 /*1225 * Does len bytes starting at "name" and "second"1226 * (that are separated by one HT or SP we just1227 * found) exactly match?1228 */1229 if (second[len] == '\n' && !strncmp(name, second, len))1230 return xmemdupz(name, len);1231 }1232 }1233}12341235/* Verify that we recognize the lines following a git header */1236static int parse_git_header(struct apply_state *state,1237 const char *line,1238 int len,1239 unsigned int size,1240 struct patch *patch)1241{1242 unsigned long offset;12431244 /* A git diff has explicit new/delete information, so we don't guess */1245 patch->is_new = 0;1246 patch->is_delete = 0;12471248 /*1249 * Some things may not have the old name in the1250 * rest of the headers anywhere (pure mode changes,1251 * or removing or adding empty files), so we get1252 * the default name from the header.1253 */1254 patch->def_name = git_header_name(state, line, len);1255 if (patch->def_name && state->root.len) {1256 char *s = xstrfmt("%s%s", state->root.buf, patch->def_name);1257 free(patch->def_name);1258 patch->def_name = s;1259 }12601261 line += len;1262 size -= len;1263 state->linenr++;1264 for (offset = len ; size > 0 ; offset += len, size -= len, line += len, state->linenr++) {1265 static const struct opentry {1266 const char *str;1267 int (*fn)(struct apply_state *, const char *, struct patch *);1268 } optable[] = {1269 { "@@ -", gitdiff_hdrend },1270 { "--- ", gitdiff_oldname },1271 { "+++ ", gitdiff_newname },1272 { "old mode ", gitdiff_oldmode },1273 { "new mode ", gitdiff_newmode },1274 { "deleted file mode ", gitdiff_delete },1275 { "new file mode ", gitdiff_newfile },1276 { "copy from ", gitdiff_copysrc },1277 { "copy to ", gitdiff_copydst },1278 { "rename old ", gitdiff_renamesrc },1279 { "rename new ", gitdiff_renamedst },1280 { "rename from ", gitdiff_renamesrc },1281 { "rename to ", gitdiff_renamedst },1282 { "similarity index ", gitdiff_similarity },1283 { "dissimilarity index ", gitdiff_dissimilarity },1284 { "index ", gitdiff_index },1285 { "", gitdiff_unrecognized },1286 };1287 int i;12881289 len = linelen(line, size);1290 if (!len || line[len-1] != '\n')1291 break;1292 for (i = 0; i < ARRAY_SIZE(optable); i++) {1293 const struct opentry *p = optable + i;1294 int oplen = strlen(p->str);1295 if (len < oplen || memcmp(p->str, line, oplen))1296 continue;1297 if (p->fn(state, line + oplen, patch) < 0)1298 return offset;1299 break;1300 }1301 }13021303 return offset;1304}13051306static int parse_num(const char *line, unsigned long *p)1307{1308 char *ptr;13091310 if (!isdigit(*line))1311 return 0;1312 *p = strtoul(line, &ptr, 10);1313 return ptr - line;1314}13151316static int parse_range(const char *line, int len, int offset, const char *expect,1317 unsigned long *p1, unsigned long *p2)1318{1319 int digits, ex;13201321 if (offset < 0 || offset >= len)1322 return -1;1323 line += offset;1324 len -= offset;13251326 digits = parse_num(line, p1);1327 if (!digits)1328 return -1;13291330 offset += digits;1331 line += digits;1332 len -= digits;13331334 *p2 = 1;1335 if (*line == ',') {1336 digits = parse_num(line+1, p2);1337 if (!digits)1338 return -1;13391340 offset += digits+1;1341 line += digits+1;1342 len -= digits+1;1343 }13441345 ex = strlen(expect);1346 if (ex > len)1347 return -1;1348 if (memcmp(line, expect, ex))1349 return -1;13501351 return offset + ex;1352}13531354static void recount_diff(const char *line, int size, struct fragment *fragment)1355{1356 int oldlines = 0, newlines = 0, ret = 0;13571358 if (size < 1) {1359 warning("recount: ignore empty hunk");1360 return;1361 }13621363 for (;;) {1364 int len = linelen(line, size);1365 size -= len;1366 line += len;13671368 if (size < 1)1369 break;13701371 switch (*line) {1372 case ' ': case '\n':1373 newlines++;1374 /* fall through */1375 case '-':1376 oldlines++;1377 continue;1378 case '+':1379 newlines++;1380 continue;1381 case '\\':1382 continue;1383 case '@':1384 ret = size < 3 || !starts_with(line, "@@ ");1385 break;1386 case 'd':1387 ret = size < 5 || !starts_with(line, "diff ");1388 break;1389 default:1390 ret = -1;1391 break;1392 }1393 if (ret) {1394 warning(_("recount: unexpected line: %.*s"),1395 (int)linelen(line, size), line);1396 return;1397 }1398 break;1399 }1400 fragment->oldlines = oldlines;1401 fragment->newlines = newlines;1402}14031404/*1405 * Parse a unified diff fragment header of the1406 * form "@@ -a,b +c,d @@"1407 */1408static int parse_fragment_header(const char *line, int len, struct fragment *fragment)1409{1410 int offset;14111412 if (!len || line[len-1] != '\n')1413 return -1;14141415 /* Figure out the number of lines in a fragment */1416 offset = parse_range(line, len, 4, " +", &fragment->oldpos, &fragment->oldlines);1417 offset = parse_range(line, len, offset, " @@", &fragment->newpos, &fragment->newlines);14181419 return offset;1420}14211422/*1423 * Find file diff header1424 *1425 * Returns:1426 * -1 if no header was found1427 * -128 in case of error1428 * the size of the header in bytes (called "offset") otherwise1429 */1430static int find_header(struct apply_state *state,1431 const char *line,1432 unsigned long size,1433 int *hdrsize,1434 struct patch *patch)1435{1436 unsigned long offset, len;14371438 patch->is_toplevel_relative = 0;1439 patch->is_rename = patch->is_copy = 0;1440 patch->is_new = patch->is_delete = -1;1441 patch->old_mode = patch->new_mode = 0;1442 patch->old_name = patch->new_name = NULL;1443 for (offset = 0; size > 0; offset += len, size -= len, line += len, state->linenr++) {1444 unsigned long nextlen;14451446 len = linelen(line, size);1447 if (!len)1448 break;14491450 /* Testing this early allows us to take a few shortcuts.. */1451 if (len < 6)1452 continue;14531454 /*1455 * Make sure we don't find any unconnected patch fragments.1456 * That's a sign that we didn't find a header, and that a1457 * patch has become corrupted/broken up.1458 */1459 if (!memcmp("@@ -", line, 4)) {1460 struct fragment dummy;1461 if (parse_fragment_header(line, len, &dummy) < 0)1462 continue;1463 error(_("patch fragment without header at line %d: %.*s"),1464 state->linenr, (int)len-1, line);1465 return -128;1466 }14671468 if (size < len + 6)1469 break;14701471 /*1472 * Git patch? It might not have a real patch, just a rename1473 * or mode change, so we handle that specially1474 */1475 if (!memcmp("diff --git ", line, 11)) {1476 int git_hdr_len = parse_git_header(state, line, len, size, patch);1477 if (git_hdr_len <= len)1478 continue;1479 if (!patch->old_name && !patch->new_name) {1480 if (!patch->def_name) {1481 error(Q_("git diff header lacks filename information when removing "1482 "%d leading pathname component (line %d)",1483 "git diff header lacks filename information when removing "1484 "%d leading pathname components (line %d)",1485 state->p_value),1486 state->p_value, state->linenr);1487 return -128;1488 }1489 patch->old_name = xstrdup(patch->def_name);1490 patch->new_name = xstrdup(patch->def_name);1491 }1492 if (!patch->is_delete && !patch->new_name) {1493 error("git diff header lacks filename information "1494 "(line %d)", state->linenr);1495 return -128;1496 }1497 patch->is_toplevel_relative = 1;1498 *hdrsize = git_hdr_len;1499 return offset;1500 }15011502 /* --- followed by +++ ? */1503 if (memcmp("--- ", line, 4) || memcmp("+++ ", line + len, 4))1504 continue;15051506 /*1507 * We only accept unified patches, so we want it to1508 * at least have "@@ -a,b +c,d @@\n", which is 14 chars1509 * minimum ("@@ -0,0 +1 @@\n" is the shortest).1510 */1511 nextlen = linelen(line + len, size - len);1512 if (size < nextlen + 14 || memcmp("@@ -", line + len + nextlen, 4))1513 continue;15141515 /* Ok, we'll consider it a patch */1516 parse_traditional_patch(state, line, line+len, patch);1517 *hdrsize = len + nextlen;1518 state->linenr += 2;1519 return offset;1520 }1521 return -1;1522}15231524static void record_ws_error(struct apply_state *state,1525 unsigned result,1526 const char *line,1527 int len,1528 int linenr)1529{1530 char *err;15311532 if (!result)1533 return;15341535 state->whitespace_error++;1536 if (state->squelch_whitespace_errors &&1537 state->squelch_whitespace_errors < state->whitespace_error)1538 return;15391540 err = whitespace_error_string(result);1541 fprintf(stderr, "%s:%d: %s.\n%.*s\n",1542 state->patch_input_file, linenr, err, len, line);1543 free(err);1544}15451546static void check_whitespace(struct apply_state *state,1547 const char *line,1548 int len,1549 unsigned ws_rule)1550{1551 unsigned result = ws_check(line + 1, len - 1, ws_rule);15521553 record_ws_error(state, result, line + 1, len - 2, state->linenr);1554}15551556/*1557 * Parse a unified diff. Note that this really needs to parse each1558 * fragment separately, since the only way to know the difference1559 * between a "---" that is part of a patch, and a "---" that starts1560 * the next patch is to look at the line counts..1561 */1562static int parse_fragment(struct apply_state *state,1563 const char *line,1564 unsigned long size,1565 struct patch *patch,1566 struct fragment *fragment)1567{1568 int added, deleted;1569 int len = linelen(line, size), offset;1570 unsigned long oldlines, newlines;1571 unsigned long leading, trailing;15721573 offset = parse_fragment_header(line, len, fragment);1574 if (offset < 0)1575 return -1;1576 if (offset > 0 && patch->recount)1577 recount_diff(line + offset, size - offset, fragment);1578 oldlines = fragment->oldlines;1579 newlines = fragment->newlines;1580 leading = 0;1581 trailing = 0;15821583 /* Parse the thing.. */1584 line += len;1585 size -= len;1586 state->linenr++;1587 added = deleted = 0;1588 for (offset = len;1589 0 < size;1590 offset += len, size -= len, line += len, state->linenr++) {1591 if (!oldlines && !newlines)1592 break;1593 len = linelen(line, size);1594 if (!len || line[len-1] != '\n')1595 return -1;1596 switch (*line) {1597 default:1598 return -1;1599 case '\n': /* newer GNU diff, an empty context line */1600 case ' ':1601 oldlines--;1602 newlines--;1603 if (!deleted && !added)1604 leading++;1605 trailing++;1606 if (!state->apply_in_reverse &&1607 state->ws_error_action == correct_ws_error)1608 check_whitespace(state, line, len, patch->ws_rule);1609 break;1610 case '-':1611 if (state->apply_in_reverse &&1612 state->ws_error_action != nowarn_ws_error)1613 check_whitespace(state, line, len, patch->ws_rule);1614 deleted++;1615 oldlines--;1616 trailing = 0;1617 break;1618 case '+':1619 if (!state->apply_in_reverse &&1620 state->ws_error_action != nowarn_ws_error)1621 check_whitespace(state, line, len, patch->ws_rule);1622 added++;1623 newlines--;1624 trailing = 0;1625 break;16261627 /*1628 * We allow "\ No newline at end of file". Depending1629 * on locale settings when the patch was produced we1630 * don't know what this line looks like. The only1631 * thing we do know is that it begins with "\ ".1632 * Checking for 12 is just for sanity check -- any1633 * l10n of "\ No newline..." is at least that long.1634 */1635 case '\\':1636 if (len < 12 || memcmp(line, "\\ ", 2))1637 return -1;1638 break;1639 }1640 }1641 if (oldlines || newlines)1642 return -1;1643 if (!deleted && !added)1644 return -1;16451646 fragment->leading = leading;1647 fragment->trailing = trailing;16481649 /*1650 * If a fragment ends with an incomplete line, we failed to include1651 * it in the above loop because we hit oldlines == newlines == 01652 * before seeing it.1653 */1654 if (12 < size && !memcmp(line, "\\ ", 2))1655 offset += linelen(line, size);16561657 patch->lines_added += added;1658 patch->lines_deleted += deleted;16591660 if (0 < patch->is_new && oldlines)1661 return error(_("new file depends on old contents"));1662 if (0 < patch->is_delete && newlines)1663 return error(_("deleted file still has contents"));1664 return offset;1665}16661667/*1668 * We have seen "diff --git a/... b/..." header (or a traditional patch1669 * header). Read hunks that belong to this patch into fragments and hang1670 * them to the given patch structure.1671 *1672 * The (fragment->patch, fragment->size) pair points into the memory given1673 * by the caller, not a copy, when we return.1674 */1675static int parse_single_patch(struct apply_state *state,1676 const char *line,1677 unsigned long size,1678 struct patch *patch)1679{1680 unsigned long offset = 0;1681 unsigned long oldlines = 0, newlines = 0, context = 0;1682 struct fragment **fragp = &patch->fragments;16831684 while (size > 4 && !memcmp(line, "@@ -", 4)) {1685 struct fragment *fragment;1686 int len;16871688 fragment = xcalloc(1, sizeof(*fragment));1689 fragment->linenr = state->linenr;1690 len = parse_fragment(state, line, size, patch, fragment);1691 if (len <= 0)1692 die(_("corrupt patch at line %d"), state->linenr);1693 fragment->patch = line;1694 fragment->size = len;1695 oldlines += fragment->oldlines;1696 newlines += fragment->newlines;1697 context += fragment->leading + fragment->trailing;16981699 *fragp = fragment;1700 fragp = &fragment->next;17011702 offset += len;1703 line += len;1704 size -= len;1705 }17061707 /*1708 * If something was removed (i.e. we have old-lines) it cannot1709 * be creation, and if something was added it cannot be1710 * deletion. However, the reverse is not true; --unified=01711 * patches that only add are not necessarily creation even1712 * though they do not have any old lines, and ones that only1713 * delete are not necessarily deletion.1714 *1715 * Unfortunately, a real creation/deletion patch do _not_ have1716 * any context line by definition, so we cannot safely tell it1717 * apart with --unified=0 insanity. At least if the patch has1718 * more than one hunk it is not creation or deletion.1719 */1720 if (patch->is_new < 0 &&1721 (oldlines || (patch->fragments && patch->fragments->next)))1722 patch->is_new = 0;1723 if (patch->is_delete < 0 &&1724 (newlines || (patch->fragments && patch->fragments->next)))1725 patch->is_delete = 0;17261727 if (0 < patch->is_new && oldlines)1728 die(_("new file %s depends on old contents"), patch->new_name);1729 if (0 < patch->is_delete && newlines)1730 die(_("deleted file %s still has contents"), patch->old_name);1731 if (!patch->is_delete && !newlines && context)1732 fprintf_ln(stderr,1733 _("** warning: "1734 "file %s becomes empty but is not deleted"),1735 patch->new_name);17361737 return offset;1738}17391740static inline int metadata_changes(struct patch *patch)1741{1742 return patch->is_rename > 0 ||1743 patch->is_copy > 0 ||1744 patch->is_new > 0 ||1745 patch->is_delete ||1746 (patch->old_mode && patch->new_mode &&1747 patch->old_mode != patch->new_mode);1748}17491750static char *inflate_it(const void *data, unsigned long size,1751 unsigned long inflated_size)1752{1753 git_zstream stream;1754 void *out;1755 int st;17561757 memset(&stream, 0, sizeof(stream));17581759 stream.next_in = (unsigned char *)data;1760 stream.avail_in = size;1761 stream.next_out = out = xmalloc(inflated_size);1762 stream.avail_out = inflated_size;1763 git_inflate_init(&stream);1764 st = git_inflate(&stream, Z_FINISH);1765 git_inflate_end(&stream);1766 if ((st != Z_STREAM_END) || stream.total_out != inflated_size) {1767 free(out);1768 return NULL;1769 }1770 return out;1771}17721773/*1774 * Read a binary hunk and return a new fragment; fragment->patch1775 * points at an allocated memory that the caller must free, so1776 * it is marked as "->free_patch = 1".1777 */1778static struct fragment *parse_binary_hunk(struct apply_state *state,1779 char **buf_p,1780 unsigned long *sz_p,1781 int *status_p,1782 int *used_p)1783{1784 /*1785 * Expect a line that begins with binary patch method ("literal"1786 * or "delta"), followed by the length of data before deflating.1787 * a sequence of 'length-byte' followed by base-85 encoded data1788 * should follow, terminated by a newline.1789 *1790 * Each 5-byte sequence of base-85 encodes up to 4 bytes,1791 * and we would limit the patch line to 66 characters,1792 * so one line can fit up to 13 groups that would decode1793 * to 52 bytes max. The length byte 'A'-'Z' corresponds1794 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.1795 */1796 int llen, used;1797 unsigned long size = *sz_p;1798 char *buffer = *buf_p;1799 int patch_method;1800 unsigned long origlen;1801 char *data = NULL;1802 int hunk_size = 0;1803 struct fragment *frag;18041805 llen = linelen(buffer, size);1806 used = llen;18071808 *status_p = 0;18091810 if (starts_with(buffer, "delta ")) {1811 patch_method = BINARY_DELTA_DEFLATED;1812 origlen = strtoul(buffer + 6, NULL, 10);1813 }1814 else if (starts_with(buffer, "literal ")) {1815 patch_method = BINARY_LITERAL_DEFLATED;1816 origlen = strtoul(buffer + 8, NULL, 10);1817 }1818 else1819 return NULL;18201821 state->linenr++;1822 buffer += llen;1823 while (1) {1824 int byte_length, max_byte_length, newsize;1825 llen = linelen(buffer, size);1826 used += llen;1827 state->linenr++;1828 if (llen == 1) {1829 /* consume the blank line */1830 buffer++;1831 size--;1832 break;1833 }1834 /*1835 * Minimum line is "A00000\n" which is 7-byte long,1836 * and the line length must be multiple of 5 plus 2.1837 */1838 if ((llen < 7) || (llen-2) % 5)1839 goto corrupt;1840 max_byte_length = (llen - 2) / 5 * 4;1841 byte_length = *buffer;1842 if ('A' <= byte_length && byte_length <= 'Z')1843 byte_length = byte_length - 'A' + 1;1844 else if ('a' <= byte_length && byte_length <= 'z')1845 byte_length = byte_length - 'a' + 27;1846 else1847 goto corrupt;1848 /* if the input length was not multiple of 4, we would1849 * have filler at the end but the filler should never1850 * exceed 3 bytes1851 */1852 if (max_byte_length < byte_length ||1853 byte_length <= max_byte_length - 4)1854 goto corrupt;1855 newsize = hunk_size + byte_length;1856 data = xrealloc(data, newsize);1857 if (decode_85(data + hunk_size, buffer + 1, byte_length))1858 goto corrupt;1859 hunk_size = newsize;1860 buffer += llen;1861 size -= llen;1862 }18631864 frag = xcalloc(1, sizeof(*frag));1865 frag->patch = inflate_it(data, hunk_size, origlen);1866 frag->free_patch = 1;1867 if (!frag->patch)1868 goto corrupt;1869 free(data);1870 frag->size = origlen;1871 *buf_p = buffer;1872 *sz_p = size;1873 *used_p = used;1874 frag->binary_patch_method = patch_method;1875 return frag;18761877 corrupt:1878 free(data);1879 *status_p = -1;1880 error(_("corrupt binary patch at line %d: %.*s"),1881 state->linenr-1, llen-1, buffer);1882 return NULL;1883}18841885/*1886 * Returns:1887 * -1 in case of error,1888 * the length of the parsed binary patch otherwise1889 */1890static int parse_binary(struct apply_state *state,1891 char *buffer,1892 unsigned long size,1893 struct patch *patch)1894{1895 /*1896 * We have read "GIT binary patch\n"; what follows is a line1897 * that says the patch method (currently, either "literal" or1898 * "delta") and the length of data before deflating; a1899 * sequence of 'length-byte' followed by base-85 encoded data1900 * follows.1901 *1902 * When a binary patch is reversible, there is another binary1903 * hunk in the same format, starting with patch method (either1904 * "literal" or "delta") with the length of data, and a sequence1905 * of length-byte + base-85 encoded data, terminated with another1906 * empty line. This data, when applied to the postimage, produces1907 * the preimage.1908 */1909 struct fragment *forward;1910 struct fragment *reverse;1911 int status;1912 int used, used_1;19131914 forward = parse_binary_hunk(state, &buffer, &size, &status, &used);1915 if (!forward && !status)1916 /* there has to be one hunk (forward hunk) */1917 return error(_("unrecognized binary patch at line %d"), state->linenr-1);1918 if (status)1919 /* otherwise we already gave an error message */1920 return status;19211922 reverse = parse_binary_hunk(state, &buffer, &size, &status, &used_1);1923 if (reverse)1924 used += used_1;1925 else if (status) {1926 /*1927 * Not having reverse hunk is not an error, but having1928 * a corrupt reverse hunk is.1929 */1930 free((void*) forward->patch);1931 free(forward);1932 return status;1933 }1934 forward->next = reverse;1935 patch->fragments = forward;1936 patch->is_binary = 1;1937 return used;1938}19391940static void prefix_one(struct apply_state *state, char **name)1941{1942 char *old_name = *name;1943 if (!old_name)1944 return;1945 *name = xstrdup(prefix_filename(state->prefix, state->prefix_length, *name));1946 free(old_name);1947}19481949static void prefix_patch(struct apply_state *state, struct patch *p)1950{1951 if (!state->prefix || p->is_toplevel_relative)1952 return;1953 prefix_one(state, &p->new_name);1954 prefix_one(state, &p->old_name);1955}19561957/*1958 * include/exclude1959 */19601961static void add_name_limit(struct apply_state *state,1962 const char *name,1963 int exclude)1964{1965 struct string_list_item *it;19661967 it = string_list_append(&state->limit_by_name, name);1968 it->util = exclude ? NULL : (void *) 1;1969}19701971static int use_patch(struct apply_state *state, struct patch *p)1972{1973 const char *pathname = p->new_name ? p->new_name : p->old_name;1974 int i;19751976 /* Paths outside are not touched regardless of "--include" */1977 if (0 < state->prefix_length) {1978 int pathlen = strlen(pathname);1979 if (pathlen <= state->prefix_length ||1980 memcmp(state->prefix, pathname, state->prefix_length))1981 return 0;1982 }19831984 /* See if it matches any of exclude/include rule */1985 for (i = 0; i < state->limit_by_name.nr; i++) {1986 struct string_list_item *it = &state->limit_by_name.items[i];1987 if (!wildmatch(it->string, pathname, 0, NULL))1988 return (it->util != NULL);1989 }19901991 /*1992 * If we had any include, a path that does not match any rule is1993 * not used. Otherwise, we saw bunch of exclude rules (or none)1994 * and such a path is used.1995 */1996 return !state->has_include;1997}199819992000/*2001 * Read the patch text in "buffer" that extends for "size" bytes; stop2002 * reading after seeing a single patch (i.e. changes to a single file).2003 * Create fragments (i.e. patch hunks) and hang them to the given patch.2004 * Return the number of bytes consumed, so that the caller can call us2005 * again for the next patch.2006 */2007static int parse_chunk(struct apply_state *state, char *buffer, unsigned long size, struct patch *patch)2008{2009 int hdrsize, patchsize;2010 int offset = find_header(state, buffer, size, &hdrsize, patch);20112012 if (offset == -128)2013 exit(128);20142015 if (offset < 0)2016 return offset;20172018 prefix_patch(state, patch);20192020 if (!use_patch(state, patch))2021 patch->ws_rule = 0;2022 else2023 patch->ws_rule = whitespace_rule(patch->new_name2024 ? patch->new_name2025 : patch->old_name);20262027 patchsize = parse_single_patch(state,2028 buffer + offset + hdrsize,2029 size - offset - hdrsize,2030 patch);20312032 if (!patchsize) {2033 static const char git_binary[] = "GIT binary patch\n";2034 int hd = hdrsize + offset;2035 unsigned long llen = linelen(buffer + hd, size - hd);20362037 if (llen == sizeof(git_binary) - 1 &&2038 !memcmp(git_binary, buffer + hd, llen)) {2039 int used;2040 state->linenr++;2041 used = parse_binary(state, buffer + hd + llen,2042 size - hd - llen, patch);2043 if (used < 0)2044 return -1;2045 if (used)2046 patchsize = used + llen;2047 else2048 patchsize = 0;2049 }2050 else if (!memcmp(" differ\n", buffer + hd + llen - 8, 8)) {2051 static const char *binhdr[] = {2052 "Binary files ",2053 "Files ",2054 NULL,2055 };2056 int i;2057 for (i = 0; binhdr[i]; i++) {2058 int len = strlen(binhdr[i]);2059 if (len < size - hd &&2060 !memcmp(binhdr[i], buffer + hd, len)) {2061 state->linenr++;2062 patch->is_binary = 1;2063 patchsize = llen;2064 break;2065 }2066 }2067 }20682069 /* Empty patch cannot be applied if it is a text patch2070 * without metadata change. A binary patch appears2071 * empty to us here.2072 */2073 if ((state->apply || state->check) &&2074 (!patch->is_binary && !metadata_changes(patch)))2075 die(_("patch with only garbage at line %d"), state->linenr);2076 }20772078 return offset + hdrsize + patchsize;2079}20802081#define swap(a,b) myswap((a),(b),sizeof(a))20822083#define myswap(a, b, size) do { \2084 unsigned char mytmp[size]; \2085 memcpy(mytmp, &a, size); \2086 memcpy(&a, &b, size); \2087 memcpy(&b, mytmp, size); \2088} while (0)20892090static void reverse_patches(struct patch *p)2091{2092 for (; p; p = p->next) {2093 struct fragment *frag = p->fragments;20942095 swap(p->new_name, p->old_name);2096 swap(p->new_mode, p->old_mode);2097 swap(p->is_new, p->is_delete);2098 swap(p->lines_added, p->lines_deleted);2099 swap(p->old_sha1_prefix, p->new_sha1_prefix);21002101 for (; frag; frag = frag->next) {2102 swap(frag->newpos, frag->oldpos);2103 swap(frag->newlines, frag->oldlines);2104 }2105 }2106}21072108static const char pluses[] =2109"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";2110static const char minuses[]=2111"----------------------------------------------------------------------";21122113static void show_stats(struct apply_state *state, struct patch *patch)2114{2115 struct strbuf qname = STRBUF_INIT;2116 char *cp = patch->new_name ? patch->new_name : patch->old_name;2117 int max, add, del;21182119 quote_c_style(cp, &qname, NULL, 0);21202121 /*2122 * "scale" the filename2123 */2124 max = state->max_len;2125 if (max > 50)2126 max = 50;21272128 if (qname.len > max) {2129 cp = strchr(qname.buf + qname.len + 3 - max, '/');2130 if (!cp)2131 cp = qname.buf + qname.len + 3 - max;2132 strbuf_splice(&qname, 0, cp - qname.buf, "...", 3);2133 }21342135 if (patch->is_binary) {2136 printf(" %-*s | Bin\n", max, qname.buf);2137 strbuf_release(&qname);2138 return;2139 }21402141 printf(" %-*s |", max, qname.buf);2142 strbuf_release(&qname);21432144 /*2145 * scale the add/delete2146 */2147 max = max + state->max_change > 70 ? 70 - max : state->max_change;2148 add = patch->lines_added;2149 del = patch->lines_deleted;21502151 if (state->max_change > 0) {2152 int total = ((add + del) * max + state->max_change / 2) / state->max_change;2153 add = (add * max + state->max_change / 2) / state->max_change;2154 del = total - add;2155 }2156 printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,2157 add, pluses, del, minuses);2158}21592160static int read_old_data(struct stat *st, const char *path, struct strbuf *buf)2161{2162 switch (st->st_mode & S_IFMT) {2163 case S_IFLNK:2164 if (strbuf_readlink(buf, path, st->st_size) < 0)2165 return error(_("unable to read symlink %s"), path);2166 return 0;2167 case S_IFREG:2168 if (strbuf_read_file(buf, path, st->st_size) != st->st_size)2169 return error(_("unable to open or read %s"), path);2170 convert_to_git(path, buf->buf, buf->len, buf, 0);2171 return 0;2172 default:2173 return -1;2174 }2175}21762177/*2178 * Update the preimage, and the common lines in postimage,2179 * from buffer buf of length len. If postlen is 0 the postimage2180 * is updated in place, otherwise it's updated on a new buffer2181 * of length postlen2182 */21832184static void update_pre_post_images(struct image *preimage,2185 struct image *postimage,2186 char *buf,2187 size_t len, size_t postlen)2188{2189 int i, ctx, reduced;2190 char *new, *old, *fixed;2191 struct image fixed_preimage;21922193 /*2194 * Update the preimage with whitespace fixes. Note that we2195 * are not losing preimage->buf -- apply_one_fragment() will2196 * free "oldlines".2197 */2198 prepare_image(&fixed_preimage, buf, len, 1);2199 assert(postlen2200 ? fixed_preimage.nr == preimage->nr2201 : fixed_preimage.nr <= preimage->nr);2202 for (i = 0; i < fixed_preimage.nr; i++)2203 fixed_preimage.line[i].flag = preimage->line[i].flag;2204 free(preimage->line_allocated);2205 *preimage = fixed_preimage;22062207 /*2208 * Adjust the common context lines in postimage. This can be2209 * done in-place when we are shrinking it with whitespace2210 * fixing, but needs a new buffer when ignoring whitespace or2211 * expanding leading tabs to spaces.2212 *2213 * We trust the caller to tell us if the update can be done2214 * in place (postlen==0) or not.2215 */2216 old = postimage->buf;2217 if (postlen)2218 new = postimage->buf = xmalloc(postlen);2219 else2220 new = old;2221 fixed = preimage->buf;22222223 for (i = reduced = ctx = 0; i < postimage->nr; i++) {2224 size_t l_len = postimage->line[i].len;2225 if (!(postimage->line[i].flag & LINE_COMMON)) {2226 /* an added line -- no counterparts in preimage */2227 memmove(new, old, l_len);2228 old += l_len;2229 new += l_len;2230 continue;2231 }22322233 /* a common context -- skip it in the original postimage */2234 old += l_len;22352236 /* and find the corresponding one in the fixed preimage */2237 while (ctx < preimage->nr &&2238 !(preimage->line[ctx].flag & LINE_COMMON)) {2239 fixed += preimage->line[ctx].len;2240 ctx++;2241 }22422243 /*2244 * preimage is expected to run out, if the caller2245 * fixed addition of trailing blank lines.2246 */2247 if (preimage->nr <= ctx) {2248 reduced++;2249 continue;2250 }22512252 /* and copy it in, while fixing the line length */2253 l_len = preimage->line[ctx].len;2254 memcpy(new, fixed, l_len);2255 new += l_len;2256 fixed += l_len;2257 postimage->line[i].len = l_len;2258 ctx++;2259 }22602261 if (postlen2262 ? postlen < new - postimage->buf2263 : postimage->len < new - postimage->buf)2264 die("BUG: caller miscounted postlen: asked %d, orig = %d, used = %d",2265 (int)postlen, (int) postimage->len, (int)(new - postimage->buf));22662267 /* Fix the length of the whole thing */2268 postimage->len = new - postimage->buf;2269 postimage->nr -= reduced;2270}22712272static int line_by_line_fuzzy_match(struct image *img,2273 struct image *preimage,2274 struct image *postimage,2275 unsigned long try,2276 int try_lno,2277 int preimage_limit)2278{2279 int i;2280 size_t imgoff = 0;2281 size_t preoff = 0;2282 size_t postlen = postimage->len;2283 size_t extra_chars;2284 char *buf;2285 char *preimage_eof;2286 char *preimage_end;2287 struct strbuf fixed;2288 char *fixed_buf;2289 size_t fixed_len;22902291 for (i = 0; i < preimage_limit; i++) {2292 size_t prelen = preimage->line[i].len;2293 size_t imglen = img->line[try_lno+i].len;22942295 if (!fuzzy_matchlines(img->buf + try + imgoff, imglen,2296 preimage->buf + preoff, prelen))2297 return 0;2298 if (preimage->line[i].flag & LINE_COMMON)2299 postlen += imglen - prelen;2300 imgoff += imglen;2301 preoff += prelen;2302 }23032304 /*2305 * Ok, the preimage matches with whitespace fuzz.2306 *2307 * imgoff now holds the true length of the target that2308 * matches the preimage before the end of the file.2309 *2310 * Count the number of characters in the preimage that fall2311 * beyond the end of the file and make sure that all of them2312 * are whitespace characters. (This can only happen if2313 * we are removing blank lines at the end of the file.)2314 */2315 buf = preimage_eof = preimage->buf + preoff;2316 for ( ; i < preimage->nr; i++)2317 preoff += preimage->line[i].len;2318 preimage_end = preimage->buf + preoff;2319 for ( ; buf < preimage_end; buf++)2320 if (!isspace(*buf))2321 return 0;23222323 /*2324 * Update the preimage and the common postimage context2325 * lines to use the same whitespace as the target.2326 * If whitespace is missing in the target (i.e.2327 * if the preimage extends beyond the end of the file),2328 * use the whitespace from the preimage.2329 */2330 extra_chars = preimage_end - preimage_eof;2331 strbuf_init(&fixed, imgoff + extra_chars);2332 strbuf_add(&fixed, img->buf + try, imgoff);2333 strbuf_add(&fixed, preimage_eof, extra_chars);2334 fixed_buf = strbuf_detach(&fixed, &fixed_len);2335 update_pre_post_images(preimage, postimage,2336 fixed_buf, fixed_len, postlen);2337 return 1;2338}23392340static int match_fragment(struct apply_state *state,2341 struct image *img,2342 struct image *preimage,2343 struct image *postimage,2344 unsigned long try,2345 int try_lno,2346 unsigned ws_rule,2347 int match_beginning, int match_end)2348{2349 int i;2350 char *fixed_buf, *buf, *orig, *target;2351 struct strbuf fixed;2352 size_t fixed_len, postlen;2353 int preimage_limit;23542355 if (preimage->nr + try_lno <= img->nr) {2356 /*2357 * The hunk falls within the boundaries of img.2358 */2359 preimage_limit = preimage->nr;2360 if (match_end && (preimage->nr + try_lno != img->nr))2361 return 0;2362 } else if (state->ws_error_action == correct_ws_error &&2363 (ws_rule & WS_BLANK_AT_EOF)) {2364 /*2365 * This hunk extends beyond the end of img, and we are2366 * removing blank lines at the end of the file. This2367 * many lines from the beginning of the preimage must2368 * match with img, and the remainder of the preimage2369 * must be blank.2370 */2371 preimage_limit = img->nr - try_lno;2372 } else {2373 /*2374 * The hunk extends beyond the end of the img and2375 * we are not removing blanks at the end, so we2376 * should reject the hunk at this position.2377 */2378 return 0;2379 }23802381 if (match_beginning && try_lno)2382 return 0;23832384 /* Quick hash check */2385 for (i = 0; i < preimage_limit; i++)2386 if ((img->line[try_lno + i].flag & LINE_PATCHED) ||2387 (preimage->line[i].hash != img->line[try_lno + i].hash))2388 return 0;23892390 if (preimage_limit == preimage->nr) {2391 /*2392 * Do we have an exact match? If we were told to match2393 * at the end, size must be exactly at try+fragsize,2394 * otherwise try+fragsize must be still within the preimage,2395 * and either case, the old piece should match the preimage2396 * exactly.2397 */2398 if ((match_end2399 ? (try + preimage->len == img->len)2400 : (try + preimage->len <= img->len)) &&2401 !memcmp(img->buf + try, preimage->buf, preimage->len))2402 return 1;2403 } else {2404 /*2405 * The preimage extends beyond the end of img, so2406 * there cannot be an exact match.2407 *2408 * There must be one non-blank context line that match2409 * a line before the end of img.2410 */2411 char *buf_end;24122413 buf = preimage->buf;2414 buf_end = buf;2415 for (i = 0; i < preimage_limit; i++)2416 buf_end += preimage->line[i].len;24172418 for ( ; buf < buf_end; buf++)2419 if (!isspace(*buf))2420 break;2421 if (buf == buf_end)2422 return 0;2423 }24242425 /*2426 * No exact match. If we are ignoring whitespace, run a line-by-line2427 * fuzzy matching. We collect all the line length information because2428 * we need it to adjust whitespace if we match.2429 */2430 if (state->ws_ignore_action == ignore_ws_change)2431 return line_by_line_fuzzy_match(img, preimage, postimage,2432 try, try_lno, preimage_limit);24332434 if (state->ws_error_action != correct_ws_error)2435 return 0;24362437 /*2438 * The hunk does not apply byte-by-byte, but the hash says2439 * it might with whitespace fuzz. We weren't asked to2440 * ignore whitespace, we were asked to correct whitespace2441 * errors, so let's try matching after whitespace correction.2442 *2443 * While checking the preimage against the target, whitespace2444 * errors in both fixed, we count how large the corresponding2445 * postimage needs to be. The postimage prepared by2446 * apply_one_fragment() has whitespace errors fixed on added2447 * lines already, but the common lines were propagated as-is,2448 * which may become longer when their whitespace errors are2449 * fixed.2450 */24512452 /* First count added lines in postimage */2453 postlen = 0;2454 for (i = 0; i < postimage->nr; i++) {2455 if (!(postimage->line[i].flag & LINE_COMMON))2456 postlen += postimage->line[i].len;2457 }24582459 /*2460 * The preimage may extend beyond the end of the file,2461 * but in this loop we will only handle the part of the2462 * preimage that falls within the file.2463 */2464 strbuf_init(&fixed, preimage->len + 1);2465 orig = preimage->buf;2466 target = img->buf + try;2467 for (i = 0; i < preimage_limit; i++) {2468 size_t oldlen = preimage->line[i].len;2469 size_t tgtlen = img->line[try_lno + i].len;2470 size_t fixstart = fixed.len;2471 struct strbuf tgtfix;2472 int match;24732474 /* Try fixing the line in the preimage */2475 ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);24762477 /* Try fixing the line in the target */2478 strbuf_init(&tgtfix, tgtlen);2479 ws_fix_copy(&tgtfix, target, tgtlen, ws_rule, NULL);24802481 /*2482 * If they match, either the preimage was based on2483 * a version before our tree fixed whitespace breakage,2484 * or we are lacking a whitespace-fix patch the tree2485 * the preimage was based on already had (i.e. target2486 * has whitespace breakage, the preimage doesn't).2487 * In either case, we are fixing the whitespace breakages2488 * so we might as well take the fix together with their2489 * real change.2490 */2491 match = (tgtfix.len == fixed.len - fixstart &&2492 !memcmp(tgtfix.buf, fixed.buf + fixstart,2493 fixed.len - fixstart));24942495 /* Add the length if this is common with the postimage */2496 if (preimage->line[i].flag & LINE_COMMON)2497 postlen += tgtfix.len;24982499 strbuf_release(&tgtfix);2500 if (!match)2501 goto unmatch_exit;25022503 orig += oldlen;2504 target += tgtlen;2505 }250625072508 /*2509 * Now handle the lines in the preimage that falls beyond the2510 * end of the file (if any). They will only match if they are2511 * empty or only contain whitespace (if WS_BLANK_AT_EOL is2512 * false).2513 */2514 for ( ; i < preimage->nr; i++) {2515 size_t fixstart = fixed.len; /* start of the fixed preimage */2516 size_t oldlen = preimage->line[i].len;2517 int j;25182519 /* Try fixing the line in the preimage */2520 ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);25212522 for (j = fixstart; j < fixed.len; j++)2523 if (!isspace(fixed.buf[j]))2524 goto unmatch_exit;25252526 orig += oldlen;2527 }25282529 /*2530 * Yes, the preimage is based on an older version that still2531 * has whitespace breakages unfixed, and fixing them makes the2532 * hunk match. Update the context lines in the postimage.2533 */2534 fixed_buf = strbuf_detach(&fixed, &fixed_len);2535 if (postlen < postimage->len)2536 postlen = 0;2537 update_pre_post_images(preimage, postimage,2538 fixed_buf, fixed_len, postlen);2539 return 1;25402541 unmatch_exit:2542 strbuf_release(&fixed);2543 return 0;2544}25452546static int find_pos(struct apply_state *state,2547 struct image *img,2548 struct image *preimage,2549 struct image *postimage,2550 int line,2551 unsigned ws_rule,2552 int match_beginning, int match_end)2553{2554 int i;2555 unsigned long backwards, forwards, try;2556 int backwards_lno, forwards_lno, try_lno;25572558 /*2559 * If match_beginning or match_end is specified, there is no2560 * point starting from a wrong line that will never match and2561 * wander around and wait for a match at the specified end.2562 */2563 if (match_beginning)2564 line = 0;2565 else if (match_end)2566 line = img->nr - preimage->nr;25672568 /*2569 * Because the comparison is unsigned, the following test2570 * will also take care of a negative line number that can2571 * result when match_end and preimage is larger than the target.2572 */2573 if ((size_t) line > img->nr)2574 line = img->nr;25752576 try = 0;2577 for (i = 0; i < line; i++)2578 try += img->line[i].len;25792580 /*2581 * There's probably some smart way to do this, but I'll leave2582 * that to the smart and beautiful people. I'm simple and stupid.2583 */2584 backwards = try;2585 backwards_lno = line;2586 forwards = try;2587 forwards_lno = line;2588 try_lno = line;25892590 for (i = 0; ; i++) {2591 if (match_fragment(state, img, preimage, postimage,2592 try, try_lno, ws_rule,2593 match_beginning, match_end))2594 return try_lno;25952596 again:2597 if (backwards_lno == 0 && forwards_lno == img->nr)2598 break;25992600 if (i & 1) {2601 if (backwards_lno == 0) {2602 i++;2603 goto again;2604 }2605 backwards_lno--;2606 backwards -= img->line[backwards_lno].len;2607 try = backwards;2608 try_lno = backwards_lno;2609 } else {2610 if (forwards_lno == img->nr) {2611 i++;2612 goto again;2613 }2614 forwards += img->line[forwards_lno].len;2615 forwards_lno++;2616 try = forwards;2617 try_lno = forwards_lno;2618 }26192620 }2621 return -1;2622}26232624static void remove_first_line(struct image *img)2625{2626 img->buf += img->line[0].len;2627 img->len -= img->line[0].len;2628 img->line++;2629 img->nr--;2630}26312632static void remove_last_line(struct image *img)2633{2634 img->len -= img->line[--img->nr].len;2635}26362637/*2638 * The change from "preimage" and "postimage" has been found to2639 * apply at applied_pos (counts in line numbers) in "img".2640 * Update "img" to remove "preimage" and replace it with "postimage".2641 */2642static void update_image(struct apply_state *state,2643 struct image *img,2644 int applied_pos,2645 struct image *preimage,2646 struct image *postimage)2647{2648 /*2649 * remove the copy of preimage at offset in img2650 * and replace it with postimage2651 */2652 int i, nr;2653 size_t remove_count, insert_count, applied_at = 0;2654 char *result;2655 int preimage_limit;26562657 /*2658 * If we are removing blank lines at the end of img,2659 * the preimage may extend beyond the end.2660 * If that is the case, we must be careful only to2661 * remove the part of the preimage that falls within2662 * the boundaries of img. Initialize preimage_limit2663 * to the number of lines in the preimage that falls2664 * within the boundaries.2665 */2666 preimage_limit = preimage->nr;2667 if (preimage_limit > img->nr - applied_pos)2668 preimage_limit = img->nr - applied_pos;26692670 for (i = 0; i < applied_pos; i++)2671 applied_at += img->line[i].len;26722673 remove_count = 0;2674 for (i = 0; i < preimage_limit; i++)2675 remove_count += img->line[applied_pos + i].len;2676 insert_count = postimage->len;26772678 /* Adjust the contents */2679 result = xmalloc(st_add3(st_sub(img->len, remove_count), insert_count, 1));2680 memcpy(result, img->buf, applied_at);2681 memcpy(result + applied_at, postimage->buf, postimage->len);2682 memcpy(result + applied_at + postimage->len,2683 img->buf + (applied_at + remove_count),2684 img->len - (applied_at + remove_count));2685 free(img->buf);2686 img->buf = result;2687 img->len += insert_count - remove_count;2688 result[img->len] = '\0';26892690 /* Adjust the line table */2691 nr = img->nr + postimage->nr - preimage_limit;2692 if (preimage_limit < postimage->nr) {2693 /*2694 * NOTE: this knows that we never call remove_first_line()2695 * on anything other than pre/post image.2696 */2697 REALLOC_ARRAY(img->line, nr);2698 img->line_allocated = img->line;2699 }2700 if (preimage_limit != postimage->nr)2701 memmove(img->line + applied_pos + postimage->nr,2702 img->line + applied_pos + preimage_limit,2703 (img->nr - (applied_pos + preimage_limit)) *2704 sizeof(*img->line));2705 memcpy(img->line + applied_pos,2706 postimage->line,2707 postimage->nr * sizeof(*img->line));2708 if (!state->allow_overlap)2709 for (i = 0; i < postimage->nr; i++)2710 img->line[applied_pos + i].flag |= LINE_PATCHED;2711 img->nr = nr;2712}27132714/*2715 * Use the patch-hunk text in "frag" to prepare two images (preimage and2716 * postimage) for the hunk. Find lines that match "preimage" in "img" and2717 * replace the part of "img" with "postimage" text.2718 */2719static int apply_one_fragment(struct apply_state *state,2720 struct image *img, struct fragment *frag,2721 int inaccurate_eof, unsigned ws_rule,2722 int nth_fragment)2723{2724 int match_beginning, match_end;2725 const char *patch = frag->patch;2726 int size = frag->size;2727 char *old, *oldlines;2728 struct strbuf newlines;2729 int new_blank_lines_at_end = 0;2730 int found_new_blank_lines_at_end = 0;2731 int hunk_linenr = frag->linenr;2732 unsigned long leading, trailing;2733 int pos, applied_pos;2734 struct image preimage;2735 struct image postimage;27362737 memset(&preimage, 0, sizeof(preimage));2738 memset(&postimage, 0, sizeof(postimage));2739 oldlines = xmalloc(size);2740 strbuf_init(&newlines, size);27412742 old = oldlines;2743 while (size > 0) {2744 char first;2745 int len = linelen(patch, size);2746 int plen;2747 int added_blank_line = 0;2748 int is_blank_context = 0;2749 size_t start;27502751 if (!len)2752 break;27532754 /*2755 * "plen" is how much of the line we should use for2756 * the actual patch data. Normally we just remove the2757 * first character on the line, but if the line is2758 * followed by "\ No newline", then we also remove the2759 * last one (which is the newline, of course).2760 */2761 plen = len - 1;2762 if (len < size && patch[len] == '\\')2763 plen--;2764 first = *patch;2765 if (state->apply_in_reverse) {2766 if (first == '-')2767 first = '+';2768 else if (first == '+')2769 first = '-';2770 }27712772 switch (first) {2773 case '\n':2774 /* Newer GNU diff, empty context line */2775 if (plen < 0)2776 /* ... followed by '\No newline'; nothing */2777 break;2778 *old++ = '\n';2779 strbuf_addch(&newlines, '\n');2780 add_line_info(&preimage, "\n", 1, LINE_COMMON);2781 add_line_info(&postimage, "\n", 1, LINE_COMMON);2782 is_blank_context = 1;2783 break;2784 case ' ':2785 if (plen && (ws_rule & WS_BLANK_AT_EOF) &&2786 ws_blank_line(patch + 1, plen, ws_rule))2787 is_blank_context = 1;2788 case '-':2789 memcpy(old, patch + 1, plen);2790 add_line_info(&preimage, old, plen,2791 (first == ' ' ? LINE_COMMON : 0));2792 old += plen;2793 if (first == '-')2794 break;2795 /* Fall-through for ' ' */2796 case '+':2797 /* --no-add does not add new lines */2798 if (first == '+' && state->no_add)2799 break;28002801 start = newlines.len;2802 if (first != '+' ||2803 !state->whitespace_error ||2804 state->ws_error_action != correct_ws_error) {2805 strbuf_add(&newlines, patch + 1, plen);2806 }2807 else {2808 ws_fix_copy(&newlines, patch + 1, plen, ws_rule, &state->applied_after_fixing_ws);2809 }2810 add_line_info(&postimage, newlines.buf + start, newlines.len - start,2811 (first == '+' ? 0 : LINE_COMMON));2812 if (first == '+' &&2813 (ws_rule & WS_BLANK_AT_EOF) &&2814 ws_blank_line(patch + 1, plen, ws_rule))2815 added_blank_line = 1;2816 break;2817 case '@': case '\\':2818 /* Ignore it, we already handled it */2819 break;2820 default:2821 if (state->apply_verbosely)2822 error(_("invalid start of line: '%c'"), first);2823 applied_pos = -1;2824 goto out;2825 }2826 if (added_blank_line) {2827 if (!new_blank_lines_at_end)2828 found_new_blank_lines_at_end = hunk_linenr;2829 new_blank_lines_at_end++;2830 }2831 else if (is_blank_context)2832 ;2833 else2834 new_blank_lines_at_end = 0;2835 patch += len;2836 size -= len;2837 hunk_linenr++;2838 }2839 if (inaccurate_eof &&2840 old > oldlines && old[-1] == '\n' &&2841 newlines.len > 0 && newlines.buf[newlines.len - 1] == '\n') {2842 old--;2843 strbuf_setlen(&newlines, newlines.len - 1);2844 }28452846 leading = frag->leading;2847 trailing = frag->trailing;28482849 /*2850 * A hunk to change lines at the beginning would begin with2851 * @@ -1,L +N,M @@2852 * but we need to be careful. -U0 that inserts before the second2853 * line also has this pattern.2854 *2855 * And a hunk to add to an empty file would begin with2856 * @@ -0,0 +N,M @@2857 *2858 * In other words, a hunk that is (frag->oldpos <= 1) with or2859 * without leading context must match at the beginning.2860 */2861 match_beginning = (!frag->oldpos ||2862 (frag->oldpos == 1 && !state->unidiff_zero));28632864 /*2865 * A hunk without trailing lines must match at the end.2866 * However, we simply cannot tell if a hunk must match end2867 * from the lack of trailing lines if the patch was generated2868 * with unidiff without any context.2869 */2870 match_end = !state->unidiff_zero && !trailing;28712872 pos = frag->newpos ? (frag->newpos - 1) : 0;2873 preimage.buf = oldlines;2874 preimage.len = old - oldlines;2875 postimage.buf = newlines.buf;2876 postimage.len = newlines.len;2877 preimage.line = preimage.line_allocated;2878 postimage.line = postimage.line_allocated;28792880 for (;;) {28812882 applied_pos = find_pos(state, img, &preimage, &postimage, pos,2883 ws_rule, match_beginning, match_end);28842885 if (applied_pos >= 0)2886 break;28872888 /* Am I at my context limits? */2889 if ((leading <= state->p_context) && (trailing <= state->p_context))2890 break;2891 if (match_beginning || match_end) {2892 match_beginning = match_end = 0;2893 continue;2894 }28952896 /*2897 * Reduce the number of context lines; reduce both2898 * leading and trailing if they are equal otherwise2899 * just reduce the larger context.2900 */2901 if (leading >= trailing) {2902 remove_first_line(&preimage);2903 remove_first_line(&postimage);2904 pos--;2905 leading--;2906 }2907 if (trailing > leading) {2908 remove_last_line(&preimage);2909 remove_last_line(&postimage);2910 trailing--;2911 }2912 }29132914 if (applied_pos >= 0) {2915 if (new_blank_lines_at_end &&2916 preimage.nr + applied_pos >= img->nr &&2917 (ws_rule & WS_BLANK_AT_EOF) &&2918 state->ws_error_action != nowarn_ws_error) {2919 record_ws_error(state, WS_BLANK_AT_EOF, "+", 1,2920 found_new_blank_lines_at_end);2921 if (state->ws_error_action == correct_ws_error) {2922 while (new_blank_lines_at_end--)2923 remove_last_line(&postimage);2924 }2925 /*2926 * We would want to prevent write_out_results()2927 * from taking place in apply_patch() that follows2928 * the callchain led us here, which is:2929 * apply_patch->check_patch_list->check_patch->2930 * apply_data->apply_fragments->apply_one_fragment2931 */2932 if (state->ws_error_action == die_on_ws_error)2933 state->apply = 0;2934 }29352936 if (state->apply_verbosely && applied_pos != pos) {2937 int offset = applied_pos - pos;2938 if (state->apply_in_reverse)2939 offset = 0 - offset;2940 fprintf_ln(stderr,2941 Q_("Hunk #%d succeeded at %d (offset %d line).",2942 "Hunk #%d succeeded at %d (offset %d lines).",2943 offset),2944 nth_fragment, applied_pos + 1, offset);2945 }29462947 /*2948 * Warn if it was necessary to reduce the number2949 * of context lines.2950 */2951 if ((leading != frag->leading) ||2952 (trailing != frag->trailing))2953 fprintf_ln(stderr, _("Context reduced to (%ld/%ld)"2954 " to apply fragment at %d"),2955 leading, trailing, applied_pos+1);2956 update_image(state, img, applied_pos, &preimage, &postimage);2957 } else {2958 if (state->apply_verbosely)2959 error(_("while searching for:\n%.*s"),2960 (int)(old - oldlines), oldlines);2961 }29622963out:2964 free(oldlines);2965 strbuf_release(&newlines);2966 free(preimage.line_allocated);2967 free(postimage.line_allocated);29682969 return (applied_pos < 0);2970}29712972static int apply_binary_fragment(struct apply_state *state,2973 struct image *img,2974 struct patch *patch)2975{2976 struct fragment *fragment = patch->fragments;2977 unsigned long len;2978 void *dst;29792980 if (!fragment)2981 return error(_("missing binary patch data for '%s'"),2982 patch->new_name ?2983 patch->new_name :2984 patch->old_name);29852986 /* Binary patch is irreversible without the optional second hunk */2987 if (state->apply_in_reverse) {2988 if (!fragment->next)2989 return error("cannot reverse-apply a binary patch "2990 "without the reverse hunk to '%s'",2991 patch->new_name2992 ? patch->new_name : patch->old_name);2993 fragment = fragment->next;2994 }2995 switch (fragment->binary_patch_method) {2996 case BINARY_DELTA_DEFLATED:2997 dst = patch_delta(img->buf, img->len, fragment->patch,2998 fragment->size, &len);2999 if (!dst)3000 return -1;3001 clear_image(img);3002 img->buf = dst;3003 img->len = len;3004 return 0;3005 case BINARY_LITERAL_DEFLATED:3006 clear_image(img);3007 img->len = fragment->size;3008 img->buf = xmemdupz(fragment->patch, img->len);3009 return 0;3010 }3011 return -1;3012}30133014/*3015 * Replace "img" with the result of applying the binary patch.3016 * The binary patch data itself in patch->fragment is still kept3017 * but the preimage prepared by the caller in "img" is freed here3018 * or in the helper function apply_binary_fragment() this calls.3019 */3020static int apply_binary(struct apply_state *state,3021 struct image *img,3022 struct patch *patch)3023{3024 const char *name = patch->old_name ? patch->old_name : patch->new_name;3025 unsigned char sha1[20];30263027 /*3028 * For safety, we require patch index line to contain3029 * full 40-byte textual SHA1 for old and new, at least for now.3030 */3031 if (strlen(patch->old_sha1_prefix) != 40 ||3032 strlen(patch->new_sha1_prefix) != 40 ||3033 get_sha1_hex(patch->old_sha1_prefix, sha1) ||3034 get_sha1_hex(patch->new_sha1_prefix, sha1))3035 return error("cannot apply binary patch to '%s' "3036 "without full index line", name);30373038 if (patch->old_name) {3039 /*3040 * See if the old one matches what the patch3041 * applies to.3042 */3043 hash_sha1_file(img->buf, img->len, blob_type, sha1);3044 if (strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))3045 return error("the patch applies to '%s' (%s), "3046 "which does not match the "3047 "current contents.",3048 name, sha1_to_hex(sha1));3049 }3050 else {3051 /* Otherwise, the old one must be empty. */3052 if (img->len)3053 return error("the patch applies to an empty "3054 "'%s' but it is not empty", name);3055 }30563057 get_sha1_hex(patch->new_sha1_prefix, sha1);3058 if (is_null_sha1(sha1)) {3059 clear_image(img);3060 return 0; /* deletion patch */3061 }30623063 if (has_sha1_file(sha1)) {3064 /* We already have the postimage */3065 enum object_type type;3066 unsigned long size;3067 char *result;30683069 result = read_sha1_file(sha1, &type, &size);3070 if (!result)3071 return error("the necessary postimage %s for "3072 "'%s' cannot be read",3073 patch->new_sha1_prefix, name);3074 clear_image(img);3075 img->buf = result;3076 img->len = size;3077 } else {3078 /*3079 * We have verified buf matches the preimage;3080 * apply the patch data to it, which is stored3081 * in the patch->fragments->{patch,size}.3082 */3083 if (apply_binary_fragment(state, img, patch))3084 return error(_("binary patch does not apply to '%s'"),3085 name);30863087 /* verify that the result matches */3088 hash_sha1_file(img->buf, img->len, blob_type, sha1);3089 if (strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))3090 return error(_("binary patch to '%s' creates incorrect result (expecting %s, got %s)"),3091 name, patch->new_sha1_prefix, sha1_to_hex(sha1));3092 }30933094 return 0;3095}30963097static int apply_fragments(struct apply_state *state, struct image *img, struct patch *patch)3098{3099 struct fragment *frag = patch->fragments;3100 const char *name = patch->old_name ? patch->old_name : patch->new_name;3101 unsigned ws_rule = patch->ws_rule;3102 unsigned inaccurate_eof = patch->inaccurate_eof;3103 int nth = 0;31043105 if (patch->is_binary)3106 return apply_binary(state, img, patch);31073108 while (frag) {3109 nth++;3110 if (apply_one_fragment(state, img, frag, inaccurate_eof, ws_rule, nth)) {3111 error(_("patch failed: %s:%ld"), name, frag->oldpos);3112 if (!state->apply_with_reject)3113 return -1;3114 frag->rejected = 1;3115 }3116 frag = frag->next;3117 }3118 return 0;3119}31203121static int read_blob_object(struct strbuf *buf, const unsigned char *sha1, unsigned mode)3122{3123 if (S_ISGITLINK(mode)) {3124 strbuf_grow(buf, 100);3125 strbuf_addf(buf, "Subproject commit %s\n", sha1_to_hex(sha1));3126 } else {3127 enum object_type type;3128 unsigned long sz;3129 char *result;31303131 result = read_sha1_file(sha1, &type, &sz);3132 if (!result)3133 return -1;3134 /* XXX read_sha1_file NUL-terminates */3135 strbuf_attach(buf, result, sz, sz + 1);3136 }3137 return 0;3138}31393140static int read_file_or_gitlink(const struct cache_entry *ce, struct strbuf *buf)3141{3142 if (!ce)3143 return 0;3144 return read_blob_object(buf, ce->sha1, ce->ce_mode);3145}31463147static struct patch *in_fn_table(struct apply_state *state, const char *name)3148{3149 struct string_list_item *item;31503151 if (name == NULL)3152 return NULL;31533154 item = string_list_lookup(&state->fn_table, name);3155 if (item != NULL)3156 return (struct patch *)item->util;31573158 return NULL;3159}31603161/*3162 * item->util in the filename table records the status of the path.3163 * Usually it points at a patch (whose result records the contents3164 * of it after applying it), but it could be PATH_WAS_DELETED for a3165 * path that a previously applied patch has already removed, or3166 * PATH_TO_BE_DELETED for a path that a later patch would remove.3167 *3168 * The latter is needed to deal with a case where two paths A and B3169 * are swapped by first renaming A to B and then renaming B to A;3170 * moving A to B should not be prevented due to presence of B as we3171 * will remove it in a later patch.3172 */3173#define PATH_TO_BE_DELETED ((struct patch *) -2)3174#define PATH_WAS_DELETED ((struct patch *) -1)31753176static int to_be_deleted(struct patch *patch)3177{3178 return patch == PATH_TO_BE_DELETED;3179}31803181static int was_deleted(struct patch *patch)3182{3183 return patch == PATH_WAS_DELETED;3184}31853186static void add_to_fn_table(struct apply_state *state, struct patch *patch)3187{3188 struct string_list_item *item;31893190 /*3191 * Always add new_name unless patch is a deletion3192 * This should cover the cases for normal diffs,3193 * file creations and copies3194 */3195 if (patch->new_name != NULL) {3196 item = string_list_insert(&state->fn_table, patch->new_name);3197 item->util = patch;3198 }31993200 /*3201 * store a failure on rename/deletion cases because3202 * later chunks shouldn't patch old names3203 */3204 if ((patch->new_name == NULL) || (patch->is_rename)) {3205 item = string_list_insert(&state->fn_table, patch->old_name);3206 item->util = PATH_WAS_DELETED;3207 }3208}32093210static void prepare_fn_table(struct apply_state *state, struct patch *patch)3211{3212 /*3213 * store information about incoming file deletion3214 */3215 while (patch) {3216 if ((patch->new_name == NULL) || (patch->is_rename)) {3217 struct string_list_item *item;3218 item = string_list_insert(&state->fn_table, patch->old_name);3219 item->util = PATH_TO_BE_DELETED;3220 }3221 patch = patch->next;3222 }3223}32243225static int checkout_target(struct index_state *istate,3226 struct cache_entry *ce, struct stat *st)3227{3228 struct checkout costate;32293230 memset(&costate, 0, sizeof(costate));3231 costate.base_dir = "";3232 costate.refresh_cache = 1;3233 costate.istate = istate;3234 if (checkout_entry(ce, &costate, NULL) || lstat(ce->name, st))3235 return error(_("cannot checkout %s"), ce->name);3236 return 0;3237}32383239static struct patch *previous_patch(struct apply_state *state,3240 struct patch *patch,3241 int *gone)3242{3243 struct patch *previous;32443245 *gone = 0;3246 if (patch->is_copy || patch->is_rename)3247 return NULL; /* "git" patches do not depend on the order */32483249 previous = in_fn_table(state, patch->old_name);3250 if (!previous)3251 return NULL;32523253 if (to_be_deleted(previous))3254 return NULL; /* the deletion hasn't happened yet */32553256 if (was_deleted(previous))3257 *gone = 1;32583259 return previous;3260}32613262static int verify_index_match(const struct cache_entry *ce, struct stat *st)3263{3264 if (S_ISGITLINK(ce->ce_mode)) {3265 if (!S_ISDIR(st->st_mode))3266 return -1;3267 return 0;3268 }3269 return ce_match_stat(ce, st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE);3270}32713272#define SUBMODULE_PATCH_WITHOUT_INDEX 132733274static int load_patch_target(struct apply_state *state,3275 struct strbuf *buf,3276 const struct cache_entry *ce,3277 struct stat *st,3278 const char *name,3279 unsigned expected_mode)3280{3281 if (state->cached || state->check_index) {3282 if (read_file_or_gitlink(ce, buf))3283 return error(_("failed to read %s"), name);3284 } else if (name) {3285 if (S_ISGITLINK(expected_mode)) {3286 if (ce)3287 return read_file_or_gitlink(ce, buf);3288 else3289 return SUBMODULE_PATCH_WITHOUT_INDEX;3290 } else if (has_symlink_leading_path(name, strlen(name))) {3291 return error(_("reading from '%s' beyond a symbolic link"), name);3292 } else {3293 if (read_old_data(st, name, buf))3294 return error(_("failed to read %s"), name);3295 }3296 }3297 return 0;3298}32993300/*3301 * We are about to apply "patch"; populate the "image" with the3302 * current version we have, from the working tree or from the index,3303 * depending on the situation e.g. --cached/--index. If we are3304 * applying a non-git patch that incrementally updates the tree,3305 * we read from the result of a previous diff.3306 */3307static int load_preimage(struct apply_state *state,3308 struct image *image,3309 struct patch *patch, struct stat *st,3310 const struct cache_entry *ce)3311{3312 struct strbuf buf = STRBUF_INIT;3313 size_t len;3314 char *img;3315 struct patch *previous;3316 int status;33173318 previous = previous_patch(state, patch, &status);3319 if (status)3320 return error(_("path %s has been renamed/deleted"),3321 patch->old_name);3322 if (previous) {3323 /* We have a patched copy in memory; use that. */3324 strbuf_add(&buf, previous->result, previous->resultsize);3325 } else {3326 status = load_patch_target(state, &buf, ce, st,3327 patch->old_name, patch->old_mode);3328 if (status < 0)3329 return status;3330 else if (status == SUBMODULE_PATCH_WITHOUT_INDEX) {3331 /*3332 * There is no way to apply subproject3333 * patch without looking at the index.3334 * NEEDSWORK: shouldn't this be flagged3335 * as an error???3336 */3337 free_fragment_list(patch->fragments);3338 patch->fragments = NULL;3339 } else if (status) {3340 return error(_("failed to read %s"), patch->old_name);3341 }3342 }33433344 img = strbuf_detach(&buf, &len);3345 prepare_image(image, img, len, !patch->is_binary);3346 return 0;3347}33483349static int three_way_merge(struct image *image,3350 char *path,3351 const unsigned char *base,3352 const unsigned char *ours,3353 const unsigned char *theirs)3354{3355 mmfile_t base_file, our_file, their_file;3356 mmbuffer_t result = { NULL };3357 int status;33583359 read_mmblob(&base_file, base);3360 read_mmblob(&our_file, ours);3361 read_mmblob(&their_file, theirs);3362 status = ll_merge(&result, path,3363 &base_file, "base",3364 &our_file, "ours",3365 &their_file, "theirs", NULL);3366 free(base_file.ptr);3367 free(our_file.ptr);3368 free(their_file.ptr);3369 if (status < 0 || !result.ptr) {3370 free(result.ptr);3371 return -1;3372 }3373 clear_image(image);3374 image->buf = result.ptr;3375 image->len = result.size;33763377 return status;3378}33793380/*3381 * When directly falling back to add/add three-way merge, we read from3382 * the current contents of the new_name. In no cases other than that3383 * this function will be called.3384 */3385static int load_current(struct apply_state *state,3386 struct image *image,3387 struct patch *patch)3388{3389 struct strbuf buf = STRBUF_INIT;3390 int status, pos;3391 size_t len;3392 char *img;3393 struct stat st;3394 struct cache_entry *ce;3395 char *name = patch->new_name;3396 unsigned mode = patch->new_mode;33973398 if (!patch->is_new)3399 die("BUG: patch to %s is not a creation", patch->old_name);34003401 pos = cache_name_pos(name, strlen(name));3402 if (pos < 0)3403 return error(_("%s: does not exist in index"), name);3404 ce = active_cache[pos];3405 if (lstat(name, &st)) {3406 if (errno != ENOENT)3407 return error(_("%s: %s"), name, strerror(errno));3408 if (checkout_target(&the_index, ce, &st))3409 return -1;3410 }3411 if (verify_index_match(ce, &st))3412 return error(_("%s: does not match index"), name);34133414 status = load_patch_target(state, &buf, ce, &st, name, mode);3415 if (status < 0)3416 return status;3417 else if (status)3418 return -1;3419 img = strbuf_detach(&buf, &len);3420 prepare_image(image, img, len, !patch->is_binary);3421 return 0;3422}34233424static int try_threeway(struct apply_state *state,3425 struct image *image,3426 struct patch *patch,3427 struct stat *st,3428 const struct cache_entry *ce)3429{3430 unsigned char pre_sha1[20], post_sha1[20], our_sha1[20];3431 struct strbuf buf = STRBUF_INIT;3432 size_t len;3433 int status;3434 char *img;3435 struct image tmp_image;34363437 /* No point falling back to 3-way merge in these cases */3438 if (patch->is_delete ||3439 S_ISGITLINK(patch->old_mode) || S_ISGITLINK(patch->new_mode))3440 return -1;34413442 /* Preimage the patch was prepared for */3443 if (patch->is_new)3444 write_sha1_file("", 0, blob_type, pre_sha1);3445 else if (get_sha1(patch->old_sha1_prefix, pre_sha1) ||3446 read_blob_object(&buf, pre_sha1, patch->old_mode))3447 return error("repository lacks the necessary blob to fall back on 3-way merge.");34483449 fprintf(stderr, "Falling back to three-way merge...\n");34503451 img = strbuf_detach(&buf, &len);3452 prepare_image(&tmp_image, img, len, 1);3453 /* Apply the patch to get the post image */3454 if (apply_fragments(state, &tmp_image, patch) < 0) {3455 clear_image(&tmp_image);3456 return -1;3457 }3458 /* post_sha1[] is theirs */3459 write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, post_sha1);3460 clear_image(&tmp_image);34613462 /* our_sha1[] is ours */3463 if (patch->is_new) {3464 if (load_current(state, &tmp_image, patch))3465 return error("cannot read the current contents of '%s'",3466 patch->new_name);3467 } else {3468 if (load_preimage(state, &tmp_image, patch, st, ce))3469 return error("cannot read the current contents of '%s'",3470 patch->old_name);3471 }3472 write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, our_sha1);3473 clear_image(&tmp_image);34743475 /* in-core three-way merge between post and our using pre as base */3476 status = three_way_merge(image, patch->new_name,3477 pre_sha1, our_sha1, post_sha1);3478 if (status < 0) {3479 fprintf(stderr, "Failed to fall back on three-way merge...\n");3480 return status;3481 }34823483 if (status) {3484 patch->conflicted_threeway = 1;3485 if (patch->is_new)3486 oidclr(&patch->threeway_stage[0]);3487 else3488 hashcpy(patch->threeway_stage[0].hash, pre_sha1);3489 hashcpy(patch->threeway_stage[1].hash, our_sha1);3490 hashcpy(patch->threeway_stage[2].hash, post_sha1);3491 fprintf(stderr, "Applied patch to '%s' with conflicts.\n", patch->new_name);3492 } else {3493 fprintf(stderr, "Applied patch to '%s' cleanly.\n", patch->new_name);3494 }3495 return 0;3496}34973498static int apply_data(struct apply_state *state, struct patch *patch,3499 struct stat *st, const struct cache_entry *ce)3500{3501 struct image image;35023503 if (load_preimage(state, &image, patch, st, ce) < 0)3504 return -1;35053506 if (patch->direct_to_threeway ||3507 apply_fragments(state, &image, patch) < 0) {3508 /* Note: with --reject, apply_fragments() returns 0 */3509 if (!state->threeway || try_threeway(state, &image, patch, st, ce) < 0)3510 return -1;3511 }3512 patch->result = image.buf;3513 patch->resultsize = image.len;3514 add_to_fn_table(state, patch);3515 free(image.line_allocated);35163517 if (0 < patch->is_delete && patch->resultsize)3518 return error(_("removal patch leaves file contents"));35193520 return 0;3521}35223523/*3524 * If "patch" that we are looking at modifies or deletes what we have,3525 * we would want it not to lose any local modification we have, either3526 * in the working tree or in the index.3527 *3528 * This also decides if a non-git patch is a creation patch or a3529 * modification to an existing empty file. We do not check the state3530 * of the current tree for a creation patch in this function; the caller3531 * check_patch() separately makes sure (and errors out otherwise) that3532 * the path the patch creates does not exist in the current tree.3533 */3534static int check_preimage(struct apply_state *state,3535 struct patch *patch,3536 struct cache_entry **ce,3537 struct stat *st)3538{3539 const char *old_name = patch->old_name;3540 struct patch *previous = NULL;3541 int stat_ret = 0, status;3542 unsigned st_mode = 0;35433544 if (!old_name)3545 return 0;35463547 assert(patch->is_new <= 0);3548 previous = previous_patch(state, patch, &status);35493550 if (status)3551 return error(_("path %s has been renamed/deleted"), old_name);3552 if (previous) {3553 st_mode = previous->new_mode;3554 } else if (!state->cached) {3555 stat_ret = lstat(old_name, st);3556 if (stat_ret && errno != ENOENT)3557 return error(_("%s: %s"), old_name, strerror(errno));3558 }35593560 if (state->check_index && !previous) {3561 int pos = cache_name_pos(old_name, strlen(old_name));3562 if (pos < 0) {3563 if (patch->is_new < 0)3564 goto is_new;3565 return error(_("%s: does not exist in index"), old_name);3566 }3567 *ce = active_cache[pos];3568 if (stat_ret < 0) {3569 if (checkout_target(&the_index, *ce, st))3570 return -1;3571 }3572 if (!state->cached && verify_index_match(*ce, st))3573 return error(_("%s: does not match index"), old_name);3574 if (state->cached)3575 st_mode = (*ce)->ce_mode;3576 } else if (stat_ret < 0) {3577 if (patch->is_new < 0)3578 goto is_new;3579 return error(_("%s: %s"), old_name, strerror(errno));3580 }35813582 if (!state->cached && !previous)3583 st_mode = ce_mode_from_stat(*ce, st->st_mode);35843585 if (patch->is_new < 0)3586 patch->is_new = 0;3587 if (!patch->old_mode)3588 patch->old_mode = st_mode;3589 if ((st_mode ^ patch->old_mode) & S_IFMT)3590 return error(_("%s: wrong type"), old_name);3591 if (st_mode != patch->old_mode)3592 warning(_("%s has type %o, expected %o"),3593 old_name, st_mode, patch->old_mode);3594 if (!patch->new_mode && !patch->is_delete)3595 patch->new_mode = st_mode;3596 return 0;35973598 is_new:3599 patch->is_new = 1;3600 patch->is_delete = 0;3601 free(patch->old_name);3602 patch->old_name = NULL;3603 return 0;3604}360536063607#define EXISTS_IN_INDEX 13608#define EXISTS_IN_WORKTREE 236093610static int check_to_create(struct apply_state *state,3611 const char *new_name,3612 int ok_if_exists)3613{3614 struct stat nst;36153616 if (state->check_index &&3617 cache_name_pos(new_name, strlen(new_name)) >= 0 &&3618 !ok_if_exists)3619 return EXISTS_IN_INDEX;3620 if (state->cached)3621 return 0;36223623 if (!lstat(new_name, &nst)) {3624 if (S_ISDIR(nst.st_mode) || ok_if_exists)3625 return 0;3626 /*3627 * A leading component of new_name might be a symlink3628 * that is going to be removed with this patch, but3629 * still pointing at somewhere that has the path.3630 * In such a case, path "new_name" does not exist as3631 * far as git is concerned.3632 */3633 if (has_symlink_leading_path(new_name, strlen(new_name)))3634 return 0;36353636 return EXISTS_IN_WORKTREE;3637 } else if ((errno != ENOENT) && (errno != ENOTDIR)) {3638 return error("%s: %s", new_name, strerror(errno));3639 }3640 return 0;3641}36423643static uintptr_t register_symlink_changes(struct apply_state *state,3644 const char *path,3645 uintptr_t what)3646{3647 struct string_list_item *ent;36483649 ent = string_list_lookup(&state->symlink_changes, path);3650 if (!ent) {3651 ent = string_list_insert(&state->symlink_changes, path);3652 ent->util = (void *)0;3653 }3654 ent->util = (void *)(what | ((uintptr_t)ent->util));3655 return (uintptr_t)ent->util;3656}36573658static uintptr_t check_symlink_changes(struct apply_state *state, const char *path)3659{3660 struct string_list_item *ent;36613662 ent = string_list_lookup(&state->symlink_changes, path);3663 if (!ent)3664 return 0;3665 return (uintptr_t)ent->util;3666}36673668static void prepare_symlink_changes(struct apply_state *state, struct patch *patch)3669{3670 for ( ; patch; patch = patch->next) {3671 if ((patch->old_name && S_ISLNK(patch->old_mode)) &&3672 (patch->is_rename || patch->is_delete))3673 /* the symlink at patch->old_name is removed */3674 register_symlink_changes(state, patch->old_name, APPLY_SYMLINK_GOES_AWAY);36753676 if (patch->new_name && S_ISLNK(patch->new_mode))3677 /* the symlink at patch->new_name is created or remains */3678 register_symlink_changes(state, patch->new_name, APPLY_SYMLINK_IN_RESULT);3679 }3680}36813682static int path_is_beyond_symlink_1(struct apply_state *state, struct strbuf *name)3683{3684 do {3685 unsigned int change;36863687 while (--name->len && name->buf[name->len] != '/')3688 ; /* scan backwards */3689 if (!name->len)3690 break;3691 name->buf[name->len] = '\0';3692 change = check_symlink_changes(state, name->buf);3693 if (change & APPLY_SYMLINK_IN_RESULT)3694 return 1;3695 if (change & APPLY_SYMLINK_GOES_AWAY)3696 /*3697 * This cannot be "return 0", because we may3698 * see a new one created at a higher level.3699 */3700 continue;37013702 /* otherwise, check the preimage */3703 if (state->check_index) {3704 struct cache_entry *ce;37053706 ce = cache_file_exists(name->buf, name->len, ignore_case);3707 if (ce && S_ISLNK(ce->ce_mode))3708 return 1;3709 } else {3710 struct stat st;3711 if (!lstat(name->buf, &st) && S_ISLNK(st.st_mode))3712 return 1;3713 }3714 } while (1);3715 return 0;3716}37173718static int path_is_beyond_symlink(struct apply_state *state, const char *name_)3719{3720 int ret;3721 struct strbuf name = STRBUF_INIT;37223723 assert(*name_ != '\0');3724 strbuf_addstr(&name, name_);3725 ret = path_is_beyond_symlink_1(state, &name);3726 strbuf_release(&name);37273728 return ret;3729}37303731static void die_on_unsafe_path(struct patch *patch)3732{3733 const char *old_name = NULL;3734 const char *new_name = NULL;3735 if (patch->is_delete)3736 old_name = patch->old_name;3737 else if (!patch->is_new && !patch->is_copy)3738 old_name = patch->old_name;3739 if (!patch->is_delete)3740 new_name = patch->new_name;37413742 if (old_name && !verify_path(old_name))3743 die(_("invalid path '%s'"), old_name);3744 if (new_name && !verify_path(new_name))3745 die(_("invalid path '%s'"), new_name);3746}37473748/*3749 * Check and apply the patch in-core; leave the result in patch->result3750 * for the caller to write it out to the final destination.3751 */3752static int check_patch(struct apply_state *state, struct patch *patch)3753{3754 struct stat st;3755 const char *old_name = patch->old_name;3756 const char *new_name = patch->new_name;3757 const char *name = old_name ? old_name : new_name;3758 struct cache_entry *ce = NULL;3759 struct patch *tpatch;3760 int ok_if_exists;3761 int status;37623763 patch->rejected = 1; /* we will drop this after we succeed */37643765 status = check_preimage(state, patch, &ce, &st);3766 if (status)3767 return status;3768 old_name = patch->old_name;37693770 /*3771 * A type-change diff is always split into a patch to delete3772 * old, immediately followed by a patch to create new (see3773 * diff.c::run_diff()); in such a case it is Ok that the entry3774 * to be deleted by the previous patch is still in the working3775 * tree and in the index.3776 *3777 * A patch to swap-rename between A and B would first rename A3778 * to B and then rename B to A. While applying the first one,3779 * the presence of B should not stop A from getting renamed to3780 * B; ask to_be_deleted() about the later rename. Removal of3781 * B and rename from A to B is handled the same way by asking3782 * was_deleted().3783 */3784 if ((tpatch = in_fn_table(state, new_name)) &&3785 (was_deleted(tpatch) || to_be_deleted(tpatch)))3786 ok_if_exists = 1;3787 else3788 ok_if_exists = 0;37893790 if (new_name &&3791 ((0 < patch->is_new) || patch->is_rename || patch->is_copy)) {3792 int err = check_to_create(state, new_name, ok_if_exists);37933794 if (err && state->threeway) {3795 patch->direct_to_threeway = 1;3796 } else switch (err) {3797 case 0:3798 break; /* happy */3799 case EXISTS_IN_INDEX:3800 return error(_("%s: already exists in index"), new_name);3801 break;3802 case EXISTS_IN_WORKTREE:3803 return error(_("%s: already exists in working directory"),3804 new_name);3805 default:3806 return err;3807 }38083809 if (!patch->new_mode) {3810 if (0 < patch->is_new)3811 patch->new_mode = S_IFREG | 0644;3812 else3813 patch->new_mode = patch->old_mode;3814 }3815 }38163817 if (new_name && old_name) {3818 int same = !strcmp(old_name, new_name);3819 if (!patch->new_mode)3820 patch->new_mode = patch->old_mode;3821 if ((patch->old_mode ^ patch->new_mode) & S_IFMT) {3822 if (same)3823 return error(_("new mode (%o) of %s does not "3824 "match old mode (%o)"),3825 patch->new_mode, new_name,3826 patch->old_mode);3827 else3828 return error(_("new mode (%o) of %s does not "3829 "match old mode (%o) of %s"),3830 patch->new_mode, new_name,3831 patch->old_mode, old_name);3832 }3833 }38343835 if (!state->unsafe_paths)3836 die_on_unsafe_path(patch);38373838 /*3839 * An attempt to read from or delete a path that is beyond a3840 * symbolic link will be prevented by load_patch_target() that3841 * is called at the beginning of apply_data() so we do not3842 * have to worry about a patch marked with "is_delete" bit3843 * here. We however need to make sure that the patch result3844 * is not deposited to a path that is beyond a symbolic link3845 * here.3846 */3847 if (!patch->is_delete && path_is_beyond_symlink(state, patch->new_name))3848 return error(_("affected file '%s' is beyond a symbolic link"),3849 patch->new_name);38503851 if (apply_data(state, patch, &st, ce) < 0)3852 return error(_("%s: patch does not apply"), name);3853 patch->rejected = 0;3854 return 0;3855}38563857static int check_patch_list(struct apply_state *state, struct patch *patch)3858{3859 int err = 0;38603861 prepare_symlink_changes(state, patch);3862 prepare_fn_table(state, patch);3863 while (patch) {3864 if (state->apply_verbosely)3865 say_patch_name(stderr,3866 _("Checking patch %s..."), patch);3867 err |= check_patch(state, patch);3868 patch = patch->next;3869 }3870 return err;3871}38723873/* This function tries to read the sha1 from the current index */3874static int get_current_sha1(const char *path, unsigned char *sha1)3875{3876 int pos;38773878 if (read_cache() < 0)3879 return -1;3880 pos = cache_name_pos(path, strlen(path));3881 if (pos < 0)3882 return -1;3883 hashcpy(sha1, active_cache[pos]->sha1);3884 return 0;3885}38863887static int preimage_sha1_in_gitlink_patch(struct patch *p, unsigned char sha1[20])3888{3889 /*3890 * A usable gitlink patch has only one fragment (hunk) that looks like:3891 * @@ -1 +1 @@3892 * -Subproject commit <old sha1>3893 * +Subproject commit <new sha1>3894 * or3895 * @@ -1 +0,0 @@3896 * -Subproject commit <old sha1>3897 * for a removal patch.3898 */3899 struct fragment *hunk = p->fragments;3900 static const char heading[] = "-Subproject commit ";3901 char *preimage;39023903 if (/* does the patch have only one hunk? */3904 hunk && !hunk->next &&3905 /* is its preimage one line? */3906 hunk->oldpos == 1 && hunk->oldlines == 1 &&3907 /* does preimage begin with the heading? */3908 (preimage = memchr(hunk->patch, '\n', hunk->size)) != NULL &&3909 starts_with(++preimage, heading) &&3910 /* does it record full SHA-1? */3911 !get_sha1_hex(preimage + sizeof(heading) - 1, sha1) &&3912 preimage[sizeof(heading) + 40 - 1] == '\n' &&3913 /* does the abbreviated name on the index line agree with it? */3914 starts_with(preimage + sizeof(heading) - 1, p->old_sha1_prefix))3915 return 0; /* it all looks fine */39163917 /* we may have full object name on the index line */3918 return get_sha1_hex(p->old_sha1_prefix, sha1);3919}39203921/* Build an index that contains the just the files needed for a 3way merge */3922static void build_fake_ancestor(struct patch *list, const char *filename)3923{3924 struct patch *patch;3925 struct index_state result = { NULL };3926 static struct lock_file lock;39273928 /* Once we start supporting the reverse patch, it may be3929 * worth showing the new sha1 prefix, but until then...3930 */3931 for (patch = list; patch; patch = patch->next) {3932 unsigned char sha1[20];3933 struct cache_entry *ce;3934 const char *name;39353936 name = patch->old_name ? patch->old_name : patch->new_name;3937 if (0 < patch->is_new)3938 continue;39393940 if (S_ISGITLINK(patch->old_mode)) {3941 if (!preimage_sha1_in_gitlink_patch(patch, sha1))3942 ; /* ok, the textual part looks sane */3943 else3944 die("sha1 information is lacking or useless for submodule %s",3945 name);3946 } else if (!get_sha1_blob(patch->old_sha1_prefix, sha1)) {3947 ; /* ok */3948 } else if (!patch->lines_added && !patch->lines_deleted) {3949 /* mode-only change: update the current */3950 if (get_current_sha1(patch->old_name, sha1))3951 die("mode change for %s, which is not "3952 "in current HEAD", name);3953 } else3954 die("sha1 information is lacking or useless "3955 "(%s).", name);39563957 ce = make_cache_entry(patch->old_mode, sha1, name, 0, 0);3958 if (!ce)3959 die(_("make_cache_entry failed for path '%s'"), name);3960 if (add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD))3961 die ("Could not add %s to temporary index", name);3962 }39633964 hold_lock_file_for_update(&lock, filename, LOCK_DIE_ON_ERROR);3965 if (write_locked_index(&result, &lock, COMMIT_LOCK))3966 die ("Could not write temporary index to %s", filename);39673968 discard_index(&result);3969}39703971static void stat_patch_list(struct apply_state *state, struct patch *patch)3972{3973 int files, adds, dels;39743975 for (files = adds = dels = 0 ; patch ; patch = patch->next) {3976 files++;3977 adds += patch->lines_added;3978 dels += patch->lines_deleted;3979 show_stats(state, patch);3980 }39813982 print_stat_summary(stdout, files, adds, dels);3983}39843985static void numstat_patch_list(struct apply_state *state,3986 struct patch *patch)3987{3988 for ( ; patch; patch = patch->next) {3989 const char *name;3990 name = patch->new_name ? patch->new_name : patch->old_name;3991 if (patch->is_binary)3992 printf("-\t-\t");3993 else3994 printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);3995 write_name_quoted(name, stdout, state->line_termination);3996 }3997}39983999static void show_file_mode_name(const char *newdelete, unsigned int mode, const char *name)4000{4001 if (mode)4002 printf(" %s mode %06o %s\n", newdelete, mode, name);4003 else4004 printf(" %s %s\n", newdelete, name);4005}40064007static void show_mode_change(struct patch *p, int show_name)4008{4009 if (p->old_mode && p->new_mode && p->old_mode != p->new_mode) {4010 if (show_name)4011 printf(" mode change %06o => %06o %s\n",4012 p->old_mode, p->new_mode, p->new_name);4013 else4014 printf(" mode change %06o => %06o\n",4015 p->old_mode, p->new_mode);4016 }4017}40184019static void show_rename_copy(struct patch *p)4020{4021 const char *renamecopy = p->is_rename ? "rename" : "copy";4022 const char *old, *new;40234024 /* Find common prefix */4025 old = p->old_name;4026 new = p->new_name;4027 while (1) {4028 const char *slash_old, *slash_new;4029 slash_old = strchr(old, '/');4030 slash_new = strchr(new, '/');4031 if (!slash_old ||4032 !slash_new ||4033 slash_old - old != slash_new - new ||4034 memcmp(old, new, slash_new - new))4035 break;4036 old = slash_old + 1;4037 new = slash_new + 1;4038 }4039 /* p->old_name thru old is the common prefix, and old and new4040 * through the end of names are renames4041 */4042 if (old != p->old_name)4043 printf(" %s %.*s{%s => %s} (%d%%)\n", renamecopy,4044 (int)(old - p->old_name), p->old_name,4045 old, new, p->score);4046 else4047 printf(" %s %s => %s (%d%%)\n", renamecopy,4048 p->old_name, p->new_name, p->score);4049 show_mode_change(p, 0);4050}40514052static void summary_patch_list(struct patch *patch)4053{4054 struct patch *p;40554056 for (p = patch; p; p = p->next) {4057 if (p->is_new)4058 show_file_mode_name("create", p->new_mode, p->new_name);4059 else if (p->is_delete)4060 show_file_mode_name("delete", p->old_mode, p->old_name);4061 else {4062 if (p->is_rename || p->is_copy)4063 show_rename_copy(p);4064 else {4065 if (p->score) {4066 printf(" rewrite %s (%d%%)\n",4067 p->new_name, p->score);4068 show_mode_change(p, 0);4069 }4070 else4071 show_mode_change(p, 1);4072 }4073 }4074 }4075}40764077static void patch_stats(struct apply_state *state, struct patch *patch)4078{4079 int lines = patch->lines_added + patch->lines_deleted;40804081 if (lines > state->max_change)4082 state->max_change = lines;4083 if (patch->old_name) {4084 int len = quote_c_style(patch->old_name, NULL, NULL, 0);4085 if (!len)4086 len = strlen(patch->old_name);4087 if (len > state->max_len)4088 state->max_len = len;4089 }4090 if (patch->new_name) {4091 int len = quote_c_style(patch->new_name, NULL, NULL, 0);4092 if (!len)4093 len = strlen(patch->new_name);4094 if (len > state->max_len)4095 state->max_len = len;4096 }4097}40984099static void remove_file(struct apply_state *state, struct patch *patch, int rmdir_empty)4100{4101 if (state->update_index) {4102 if (remove_file_from_cache(patch->old_name) < 0)4103 die(_("unable to remove %s from index"), patch->old_name);4104 }4105 if (!state->cached) {4106 if (!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {4107 remove_path(patch->old_name);4108 }4109 }4110}41114112static void add_index_file(struct apply_state *state,4113 const char *path,4114 unsigned mode,4115 void *buf,4116 unsigned long size)4117{4118 struct stat st;4119 struct cache_entry *ce;4120 int namelen = strlen(path);4121 unsigned ce_size = cache_entry_size(namelen);41224123 if (!state->update_index)4124 return;41254126 ce = xcalloc(1, ce_size);4127 memcpy(ce->name, path, namelen);4128 ce->ce_mode = create_ce_mode(mode);4129 ce->ce_flags = create_ce_flags(0);4130 ce->ce_namelen = namelen;4131 if (S_ISGITLINK(mode)) {4132 const char *s;41334134 if (!skip_prefix(buf, "Subproject commit ", &s) ||4135 get_sha1_hex(s, ce->sha1))4136 die(_("corrupt patch for submodule %s"), path);4137 } else {4138 if (!state->cached) {4139 if (lstat(path, &st) < 0)4140 die_errno(_("unable to stat newly created file '%s'"),4141 path);4142 fill_stat_cache_info(ce, &st);4143 }4144 if (write_sha1_file(buf, size, blob_type, ce->sha1) < 0)4145 die(_("unable to create backing store for newly created file %s"), path);4146 }4147 if (add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) < 0)4148 die(_("unable to add cache entry for %s"), path);4149}41504151static int try_create_file(const char *path, unsigned int mode, const char *buf, unsigned long size)4152{4153 int fd;4154 struct strbuf nbuf = STRBUF_INIT;41554156 if (S_ISGITLINK(mode)) {4157 struct stat st;4158 if (!lstat(path, &st) && S_ISDIR(st.st_mode))4159 return 0;4160 return mkdir(path, 0777);4161 }41624163 if (has_symlinks && S_ISLNK(mode))4164 /* Although buf:size is counted string, it also is NUL4165 * terminated.4166 */4167 return symlink(buf, path);41684169 fd = open(path, O_CREAT | O_EXCL | O_WRONLY, (mode & 0100) ? 0777 : 0666);4170 if (fd < 0)4171 return -1;41724173 if (convert_to_working_tree(path, buf, size, &nbuf)) {4174 size = nbuf.len;4175 buf = nbuf.buf;4176 }4177 write_or_die(fd, buf, size);4178 strbuf_release(&nbuf);41794180 if (close(fd) < 0)4181 die_errno(_("closing file '%s'"), path);4182 return 0;4183}41844185/*4186 * We optimistically assume that the directories exist,4187 * which is true 99% of the time anyway. If they don't,4188 * we create them and try again.4189 */4190static void create_one_file(struct apply_state *state,4191 char *path,4192 unsigned mode,4193 const char *buf,4194 unsigned long size)4195{4196 if (state->cached)4197 return;4198 if (!try_create_file(path, mode, buf, size))4199 return;42004201 if (errno == ENOENT) {4202 if (safe_create_leading_directories(path))4203 return;4204 if (!try_create_file(path, mode, buf, size))4205 return;4206 }42074208 if (errno == EEXIST || errno == EACCES) {4209 /* We may be trying to create a file where a directory4210 * used to be.4211 */4212 struct stat st;4213 if (!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))4214 errno = EEXIST;4215 }42164217 if (errno == EEXIST) {4218 unsigned int nr = getpid();42194220 for (;;) {4221 char newpath[PATH_MAX];4222 mksnpath(newpath, sizeof(newpath), "%s~%u", path, nr);4223 if (!try_create_file(newpath, mode, buf, size)) {4224 if (!rename(newpath, path))4225 return;4226 unlink_or_warn(newpath);4227 break;4228 }4229 if (errno != EEXIST)4230 break;4231 ++nr;4232 }4233 }4234 die_errno(_("unable to write file '%s' mode %o"), path, mode);4235}42364237static void add_conflicted_stages_file(struct apply_state *state,4238 struct patch *patch)4239{4240 int stage, namelen;4241 unsigned ce_size, mode;4242 struct cache_entry *ce;42434244 if (!state->update_index)4245 return;4246 namelen = strlen(patch->new_name);4247 ce_size = cache_entry_size(namelen);4248 mode = patch->new_mode ? patch->new_mode : (S_IFREG | 0644);42494250 remove_file_from_cache(patch->new_name);4251 for (stage = 1; stage < 4; stage++) {4252 if (is_null_oid(&patch->threeway_stage[stage - 1]))4253 continue;4254 ce = xcalloc(1, ce_size);4255 memcpy(ce->name, patch->new_name, namelen);4256 ce->ce_mode = create_ce_mode(mode);4257 ce->ce_flags = create_ce_flags(stage);4258 ce->ce_namelen = namelen;4259 hashcpy(ce->sha1, patch->threeway_stage[stage - 1].hash);4260 if (add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) < 0)4261 die(_("unable to add cache entry for %s"), patch->new_name);4262 }4263}42644265static void create_file(struct apply_state *state, struct patch *patch)4266{4267 char *path = patch->new_name;4268 unsigned mode = patch->new_mode;4269 unsigned long size = patch->resultsize;4270 char *buf = patch->result;42714272 if (!mode)4273 mode = S_IFREG | 0644;4274 create_one_file(state, path, mode, buf, size);42754276 if (patch->conflicted_threeway)4277 add_conflicted_stages_file(state, patch);4278 else4279 add_index_file(state, path, mode, buf, size);4280}42814282/* phase zero is to remove, phase one is to create */4283static void write_out_one_result(struct apply_state *state,4284 struct patch *patch,4285 int phase)4286{4287 if (patch->is_delete > 0) {4288 if (phase == 0)4289 remove_file(state, patch, 1);4290 return;4291 }4292 if (patch->is_new > 0 || patch->is_copy) {4293 if (phase == 1)4294 create_file(state, patch);4295 return;4296 }4297 /*4298 * Rename or modification boils down to the same4299 * thing: remove the old, write the new4300 */4301 if (phase == 0)4302 remove_file(state, patch, patch->is_rename);4303 if (phase == 1)4304 create_file(state, patch);4305}43064307static int write_out_one_reject(struct apply_state *state, struct patch *patch)4308{4309 FILE *rej;4310 char namebuf[PATH_MAX];4311 struct fragment *frag;4312 int cnt = 0;4313 struct strbuf sb = STRBUF_INIT;43144315 for (cnt = 0, frag = patch->fragments; frag; frag = frag->next) {4316 if (!frag->rejected)4317 continue;4318 cnt++;4319 }43204321 if (!cnt) {4322 if (state->apply_verbosely)4323 say_patch_name(stderr,4324 _("Applied patch %s cleanly."), patch);4325 return 0;4326 }43274328 /* This should not happen, because a removal patch that leaves4329 * contents are marked "rejected" at the patch level.4330 */4331 if (!patch->new_name)4332 die(_("internal error"));43334334 /* Say this even without --verbose */4335 strbuf_addf(&sb, Q_("Applying patch %%s with %d reject...",4336 "Applying patch %%s with %d rejects...",4337 cnt),4338 cnt);4339 say_patch_name(stderr, sb.buf, patch);4340 strbuf_release(&sb);43414342 cnt = strlen(patch->new_name);4343 if (ARRAY_SIZE(namebuf) <= cnt + 5) {4344 cnt = ARRAY_SIZE(namebuf) - 5;4345 warning(_("truncating .rej filename to %.*s.rej"),4346 cnt - 1, patch->new_name);4347 }4348 memcpy(namebuf, patch->new_name, cnt);4349 memcpy(namebuf + cnt, ".rej", 5);43504351 rej = fopen(namebuf, "w");4352 if (!rej)4353 return error(_("cannot open %s: %s"), namebuf, strerror(errno));43544355 /* Normal git tools never deal with .rej, so do not pretend4356 * this is a git patch by saying --git or giving extended4357 * headers. While at it, maybe please "kompare" that wants4358 * the trailing TAB and some garbage at the end of line ;-).4359 */4360 fprintf(rej, "diff a/%s b/%s\t(rejected hunks)\n",4361 patch->new_name, patch->new_name);4362 for (cnt = 1, frag = patch->fragments;4363 frag;4364 cnt++, frag = frag->next) {4365 if (!frag->rejected) {4366 fprintf_ln(stderr, _("Hunk #%d applied cleanly."), cnt);4367 continue;4368 }4369 fprintf_ln(stderr, _("Rejected hunk #%d."), cnt);4370 fprintf(rej, "%.*s", frag->size, frag->patch);4371 if (frag->patch[frag->size-1] != '\n')4372 fputc('\n', rej);4373 }4374 fclose(rej);4375 return -1;4376}43774378static int write_out_results(struct apply_state *state, struct patch *list)4379{4380 int phase;4381 int errs = 0;4382 struct patch *l;4383 struct string_list cpath = STRING_LIST_INIT_DUP;43844385 for (phase = 0; phase < 2; phase++) {4386 l = list;4387 while (l) {4388 if (l->rejected)4389 errs = 1;4390 else {4391 write_out_one_result(state, l, phase);4392 if (phase == 1) {4393 if (write_out_one_reject(state, l))4394 errs = 1;4395 if (l->conflicted_threeway) {4396 string_list_append(&cpath, l->new_name);4397 errs = 1;4398 }4399 }4400 }4401 l = l->next;4402 }4403 }44044405 if (cpath.nr) {4406 struct string_list_item *item;44074408 string_list_sort(&cpath);4409 for_each_string_list_item(item, &cpath)4410 fprintf(stderr, "U %s\n", item->string);4411 string_list_clear(&cpath, 0);44124413 rerere(0);4414 }44154416 return errs;4417}44184419static struct lock_file lock_file;44204421#define INACCURATE_EOF (1<<0)4422#define RECOUNT (1<<1)44234424/*4425 * Try to apply a patch.4426 *4427 * Returns:4428 * -128 if a bad error happened (like patch unreadable)4429 * -1 if patch did not apply and user cannot deal with it4430 * 0 if the patch applied4431 * 1 if the patch did not apply but user might fix it4432 */4433static int apply_patch(struct apply_state *state,4434 int fd,4435 const char *filename,4436 int options)4437{4438 size_t offset;4439 struct strbuf buf = STRBUF_INIT; /* owns the patch text */4440 struct patch *list = NULL, **listp = &list;4441 int skipped_patch = 0;4442 int res = 0;44434444 state->patch_input_file = filename;4445 if (read_patch_file(&buf, fd) < 0)4446 return -128;4447 offset = 0;4448 while (offset < buf.len) {4449 struct patch *patch;4450 int nr;44514452 patch = xcalloc(1, sizeof(*patch));4453 patch->inaccurate_eof = !!(options & INACCURATE_EOF);4454 patch->recount = !!(options & RECOUNT);4455 nr = parse_chunk(state, buf.buf + offset, buf.len - offset, patch);4456 if (nr < 0) {4457 free_patch(patch);4458 break;4459 }4460 if (state->apply_in_reverse)4461 reverse_patches(patch);4462 if (use_patch(state, patch)) {4463 patch_stats(state, patch);4464 *listp = patch;4465 listp = &patch->next;4466 }4467 else {4468 if (state->apply_verbosely)4469 say_patch_name(stderr, _("Skipped patch '%s'."), patch);4470 free_patch(patch);4471 skipped_patch++;4472 }4473 offset += nr;4474 }44754476 if (!list && !skipped_patch) {4477 error(_("unrecognized input"));4478 res = -128;4479 goto end;4480 }44814482 if (state->whitespace_error && (state->ws_error_action == die_on_ws_error))4483 state->apply = 0;44844485 state->update_index = state->check_index && state->apply;4486 if (state->update_index && state->newfd < 0)4487 state->newfd = hold_locked_index(state->lock_file, 1);44884489 if (state->check_index && read_cache() < 0) {4490 error(_("unable to read index file"));4491 res = -128;4492 goto end;4493 }44944495 if ((state->check || state->apply) &&4496 check_patch_list(state, list) < 0 &&4497 !state->apply_with_reject) {4498 res = -1;4499 goto end;4500 }45014502 if (state->apply && write_out_results(state, list)) {4503 /* with --3way, we still need to write the index out */4504 res = state->apply_with_reject ? -1 : 1;4505 goto end;4506 }45074508 if (state->fake_ancestor)4509 build_fake_ancestor(list, state->fake_ancestor);45104511 if (state->diffstat)4512 stat_patch_list(state, list);45134514 if (state->numstat)4515 numstat_patch_list(state, list);45164517 if (state->summary)4518 summary_patch_list(list);45194520end:4521 free_patch_list(list);4522 strbuf_release(&buf);4523 string_list_clear(&state->fn_table, 0);4524 return res;4525}45264527static void git_apply_config(void)4528{4529 git_config_get_string_const("apply.whitespace", &apply_default_whitespace);4530 git_config_get_string_const("apply.ignorewhitespace", &apply_default_ignorewhitespace);4531 git_config(git_default_config, NULL);4532}45334534static int option_parse_exclude(const struct option *opt,4535 const char *arg, int unset)4536{4537 struct apply_state *state = opt->value;4538 add_name_limit(state, arg, 1);4539 return 0;4540}45414542static int option_parse_include(const struct option *opt,4543 const char *arg, int unset)4544{4545 struct apply_state *state = opt->value;4546 add_name_limit(state, arg, 0);4547 state->has_include = 1;4548 return 0;4549}45504551static int option_parse_p(const struct option *opt,4552 const char *arg,4553 int unset)4554{4555 struct apply_state *state = opt->value;4556 state->p_value = atoi(arg);4557 state->p_value_known = 1;4558 return 0;4559}45604561static int option_parse_space_change(const struct option *opt,4562 const char *arg, int unset)4563{4564 struct apply_state *state = opt->value;4565 if (unset)4566 state->ws_ignore_action = ignore_ws_none;4567 else4568 state->ws_ignore_action = ignore_ws_change;4569 return 0;4570}45714572static int option_parse_whitespace(const struct option *opt,4573 const char *arg, int unset)4574{4575 struct apply_state *state = opt->value;4576 state->whitespace_option = arg;4577 parse_whitespace_option(state, arg);4578 return 0;4579}45804581static int option_parse_directory(const struct option *opt,4582 const char *arg, int unset)4583{4584 struct apply_state *state = opt->value;4585 strbuf_reset(&state->root);4586 strbuf_addstr(&state->root, arg);4587 strbuf_complete(&state->root, '/');4588 return 0;4589}45904591static void init_apply_state(struct apply_state *state,4592 const char *prefix,4593 struct lock_file *lock_file)4594{4595 memset(state, 0, sizeof(*state));4596 state->prefix = prefix;4597 state->prefix_length = state->prefix ? strlen(state->prefix) : 0;4598 state->lock_file = lock_file;4599 state->newfd = -1;4600 state->apply = 1;4601 state->line_termination = '\n';4602 state->p_value = 1;4603 state->p_context = UINT_MAX;4604 state->squelch_whitespace_errors = 5;4605 state->ws_error_action = warn_on_ws_error;4606 state->ws_ignore_action = ignore_ws_none;4607 state->linenr = 1;4608 string_list_init(&state->fn_table, 0);4609 string_list_init(&state->limit_by_name, 0);4610 string_list_init(&state->symlink_changes, 0);4611 strbuf_init(&state->root, 0);46124613 git_apply_config();4614 if (apply_default_whitespace)4615 parse_whitespace_option(state, apply_default_whitespace);4616 if (apply_default_ignorewhitespace)4617 parse_ignorewhitespace_option(state, apply_default_ignorewhitespace);4618}46194620static void clear_apply_state(struct apply_state *state)4621{4622 string_list_clear(&state->limit_by_name, 0);4623 string_list_clear(&state->symlink_changes, 0);4624 strbuf_release(&state->root);46254626 /* &state->fn_table is cleared at the end of apply_patch() */4627}46284629static void check_apply_state(struct apply_state *state, int force_apply)4630{4631 int is_not_gitdir = !startup_info->have_repository;46324633 if (state->apply_with_reject && state->threeway)4634 die("--reject and --3way cannot be used together.");4635 if (state->cached && state->threeway)4636 die("--cached and --3way cannot be used together.");4637 if (state->threeway) {4638 if (is_not_gitdir)4639 die(_("--3way outside a repository"));4640 state->check_index = 1;4641 }4642 if (state->apply_with_reject)4643 state->apply = state->apply_verbosely = 1;4644 if (!force_apply && (state->diffstat || state->numstat || state->summary || state->check || state->fake_ancestor))4645 state->apply = 0;4646 if (state->check_index && is_not_gitdir)4647 die(_("--index outside a repository"));4648 if (state->cached) {4649 if (is_not_gitdir)4650 die(_("--cached outside a repository"));4651 state->check_index = 1;4652 }4653 if (state->check_index)4654 state->unsafe_paths = 0;4655 if (!state->lock_file)4656 die("BUG: state->lock_file should not be NULL");4657}46584659static int apply_all_patches(struct apply_state *state,4660 int argc,4661 const char **argv,4662 int options)4663{4664 int i;4665 int res;4666 int errs = 0;4667 int read_stdin = 1;46684669 for (i = 0; i < argc; i++) {4670 const char *arg = argv[i];4671 int fd;46724673 if (!strcmp(arg, "-")) {4674 res = apply_patch(state, 0, "<stdin>", options);4675 if (res < 0)4676 goto end;4677 errs |= res;4678 read_stdin = 0;4679 continue;4680 } else if (0 < state->prefix_length)4681 arg = prefix_filename(state->prefix,4682 state->prefix_length,4683 arg);46844685 fd = open(arg, O_RDONLY);4686 if (fd < 0)4687 die_errno(_("can't open patch '%s'"), arg);4688 read_stdin = 0;4689 set_default_whitespace_mode(state);4690 res = apply_patch(state, fd, arg, options);4691 if (res < 0)4692 goto end;4693 errs |= res;4694 close(fd);4695 }4696 set_default_whitespace_mode(state);4697 if (read_stdin) {4698 res = apply_patch(state, 0, "<stdin>", options);4699 if (res < 0)4700 goto end;4701 errs |= res;4702 }47034704 if (state->whitespace_error) {4705 if (state->squelch_whitespace_errors &&4706 state->squelch_whitespace_errors < state->whitespace_error) {4707 int squelched =4708 state->whitespace_error - state->squelch_whitespace_errors;4709 warning(Q_("squelched %d whitespace error",4710 "squelched %d whitespace errors",4711 squelched),4712 squelched);4713 }4714 if (state->ws_error_action == die_on_ws_error)4715 die(Q_("%d line adds whitespace errors.",4716 "%d lines add whitespace errors.",4717 state->whitespace_error),4718 state->whitespace_error);4719 if (state->applied_after_fixing_ws && state->apply)4720 warning("%d line%s applied after"4721 " fixing whitespace errors.",4722 state->applied_after_fixing_ws,4723 state->applied_after_fixing_ws == 1 ? "" : "s");4724 else if (state->whitespace_error)4725 warning(Q_("%d line adds whitespace errors.",4726 "%d lines add whitespace errors.",4727 state->whitespace_error),4728 state->whitespace_error);4729 }47304731 if (state->update_index) {4732 if (write_locked_index(&the_index, state->lock_file, COMMIT_LOCK))4733 die(_("Unable to write new index file"));4734 state->newfd = -1;4735 }47364737 return !!errs;47384739end:4740 exit(res == -1 ? 1 : 128);4741}47424743int cmd_apply(int argc, const char **argv, const char *prefix)4744{4745 int force_apply = 0;4746 int options = 0;4747 int ret;4748 struct apply_state state;47494750 struct option builtin_apply_options[] = {4751 { OPTION_CALLBACK, 0, "exclude", &state, N_("path"),4752 N_("don't apply changes matching the given path"),4753 0, option_parse_exclude },4754 { OPTION_CALLBACK, 0, "include", &state, N_("path"),4755 N_("apply changes matching the given path"),4756 0, option_parse_include },4757 { OPTION_CALLBACK, 'p', NULL, &state, N_("num"),4758 N_("remove <num> leading slashes from traditional diff paths"),4759 0, option_parse_p },4760 OPT_BOOL(0, "no-add", &state.no_add,4761 N_("ignore additions made by the patch")),4762 OPT_BOOL(0, "stat", &state.diffstat,4763 N_("instead of applying the patch, output diffstat for the input")),4764 OPT_NOOP_NOARG(0, "allow-binary-replacement"),4765 OPT_NOOP_NOARG(0, "binary"),4766 OPT_BOOL(0, "numstat", &state.numstat,4767 N_("show number of added and deleted lines in decimal notation")),4768 OPT_BOOL(0, "summary", &state.summary,4769 N_("instead of applying the patch, output a summary for the input")),4770 OPT_BOOL(0, "check", &state.check,4771 N_("instead of applying the patch, see if the patch is applicable")),4772 OPT_BOOL(0, "index", &state.check_index,4773 N_("make sure the patch is applicable to the current index")),4774 OPT_BOOL(0, "cached", &state.cached,4775 N_("apply a patch without touching the working tree")),4776 OPT_BOOL(0, "unsafe-paths", &state.unsafe_paths,4777 N_("accept a patch that touches outside the working area")),4778 OPT_BOOL(0, "apply", &force_apply,4779 N_("also apply the patch (use with --stat/--summary/--check)")),4780 OPT_BOOL('3', "3way", &state.threeway,4781 N_( "attempt three-way merge if a patch does not apply")),4782 OPT_FILENAME(0, "build-fake-ancestor", &state.fake_ancestor,4783 N_("build a temporary index based on embedded index information")),4784 /* Think twice before adding "--nul" synonym to this */4785 OPT_SET_INT('z', NULL, &state.line_termination,4786 N_("paths are separated with NUL character"), '\0'),4787 OPT_INTEGER('C', NULL, &state.p_context,4788 N_("ensure at least <n> lines of context match")),4789 { OPTION_CALLBACK, 0, "whitespace", &state, N_("action"),4790 N_("detect new or modified lines that have whitespace errors"),4791 0, option_parse_whitespace },4792 { OPTION_CALLBACK, 0, "ignore-space-change", &state, NULL,4793 N_("ignore changes in whitespace when finding context"),4794 PARSE_OPT_NOARG, option_parse_space_change },4795 { OPTION_CALLBACK, 0, "ignore-whitespace", &state, NULL,4796 N_("ignore changes in whitespace when finding context"),4797 PARSE_OPT_NOARG, option_parse_space_change },4798 OPT_BOOL('R', "reverse", &state.apply_in_reverse,4799 N_("apply the patch in reverse")),4800 OPT_BOOL(0, "unidiff-zero", &state.unidiff_zero,4801 N_("don't expect at least one line of context")),4802 OPT_BOOL(0, "reject", &state.apply_with_reject,4803 N_("leave the rejected hunks in corresponding *.rej files")),4804 OPT_BOOL(0, "allow-overlap", &state.allow_overlap,4805 N_("allow overlapping hunks")),4806 OPT__VERBOSE(&state.apply_verbosely, N_("be verbose")),4807 OPT_BIT(0, "inaccurate-eof", &options,4808 N_("tolerate incorrectly detected missing new-line at the end of file"),4809 INACCURATE_EOF),4810 OPT_BIT(0, "recount", &options,4811 N_("do not trust the line counts in the hunk headers"),4812 RECOUNT),4813 { OPTION_CALLBACK, 0, "directory", &state, N_("root"),4814 N_("prepend <root> to all filenames"),4815 0, option_parse_directory },4816 OPT_END()4817 };48184819 init_apply_state(&state, prefix, &lock_file);48204821 argc = parse_options(argc, argv, state.prefix, builtin_apply_options,4822 apply_usage, 0);48234824 check_apply_state(&state, force_apply);48254826 ret = apply_all_patches(&state, argc, argv, options);48274828 clear_apply_state(&state);48294830 return ret;4831}