Git fork
at reftables-rust 5169 lines 138 kB view raw
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 10#define USE_THE_REPOSITORY_VARIABLE 11#define DISABLE_SIGN_COMPARE_WARNINGS 12 13#include "git-compat-util.h" 14#include "abspath.h" 15#include "base85.h" 16#include "config.h" 17#include "odb.h" 18#include "delta.h" 19#include "diff.h" 20#include "dir.h" 21#include "environment.h" 22#include "gettext.h" 23#include "hex.h" 24#include "xdiff-interface.h" 25#include "merge-ll.h" 26#include "lockfile.h" 27#include "name-hash.h" 28#include "object-name.h" 29#include "object-file.h" 30#include "parse-options.h" 31#include "path.h" 32#include "quote.h" 33#include "read-cache.h" 34#include "repository.h" 35#include "rerere.h" 36#include "apply.h" 37#include "entry.h" 38#include "setup.h" 39#include "symlinks.h" 40#include "wildmatch.h" 41#include "ws.h" 42 43struct gitdiff_data { 44 struct strbuf *root; 45 int linenr; 46 int p_value; 47}; 48 49static void git_apply_config(void) 50{ 51 repo_config_get_string(the_repository, "apply.whitespace", &apply_default_whitespace); 52 repo_config_get_string(the_repository, "apply.ignorewhitespace", &apply_default_ignorewhitespace); 53 repo_config(the_repository, git_xmerge_config, NULL); 54} 55 56static int parse_whitespace_option(struct apply_state *state, const char *option) 57{ 58 if (!option) { 59 state->ws_error_action = warn_on_ws_error; 60 return 0; 61 } 62 if (!strcmp(option, "warn")) { 63 state->ws_error_action = warn_on_ws_error; 64 return 0; 65 } 66 if (!strcmp(option, "nowarn")) { 67 state->ws_error_action = nowarn_ws_error; 68 return 0; 69 } 70 if (!strcmp(option, "error")) { 71 state->ws_error_action = die_on_ws_error; 72 return 0; 73 } 74 if (!strcmp(option, "error-all")) { 75 state->ws_error_action = die_on_ws_error; 76 state->squelch_whitespace_errors = 0; 77 return 0; 78 } 79 if (!strcmp(option, "strip") || !strcmp(option, "fix")) { 80 state->ws_error_action = correct_ws_error; 81 return 0; 82 } 83 /* 84 * Please update $__git_whitespacelist in git-completion.bash, 85 * Documentation/git-apply.adoc, and Documentation/git-am.adoc 86 * when you add new options. 87 */ 88 return error(_("unrecognized whitespace option '%s'"), option); 89} 90 91static int parse_ignorewhitespace_option(struct apply_state *state, 92 const char *option) 93{ 94 if (!option || !strcmp(option, "no") || 95 !strcmp(option, "false") || !strcmp(option, "never") || 96 !strcmp(option, "none")) { 97 state->ws_ignore_action = ignore_ws_none; 98 return 0; 99 } 100 if (!strcmp(option, "change")) { 101 state->ws_ignore_action = ignore_ws_change; 102 return 0; 103 } 104 return error(_("unrecognized whitespace ignore option '%s'"), option); 105} 106 107int init_apply_state(struct apply_state *state, 108 struct repository *repo, 109 const char *prefix) 110{ 111 memset(state, 0, sizeof(*state)); 112 state->prefix = prefix; 113 state->repo = repo; 114 state->apply = 1; 115 state->line_termination = '\n'; 116 state->p_value = 1; 117 state->p_context = UINT_MAX; 118 state->squelch_whitespace_errors = 5; 119 state->ws_error_action = warn_on_ws_error; 120 state->ws_ignore_action = ignore_ws_none; 121 state->linenr = 1; 122 string_list_init_nodup(&state->fn_table); 123 string_list_init_nodup(&state->limit_by_name); 124 strset_init(&state->removed_symlinks); 125 strset_init(&state->kept_symlinks); 126 strbuf_init(&state->root, 0); 127 128 git_apply_config(); 129 if (apply_default_whitespace && parse_whitespace_option(state, apply_default_whitespace)) 130 return -1; 131 if (apply_default_ignorewhitespace && parse_ignorewhitespace_option(state, apply_default_ignorewhitespace)) 132 return -1; 133 return 0; 134} 135 136void clear_apply_state(struct apply_state *state) 137{ 138 string_list_clear(&state->limit_by_name, 0); 139 strset_clear(&state->removed_symlinks); 140 strset_clear(&state->kept_symlinks); 141 strbuf_release(&state->root); 142 FREE_AND_NULL(state->fake_ancestor); 143 144 /* &state->fn_table is cleared at the end of apply_patch() */ 145} 146 147static void mute_routine(const char *msg UNUSED, va_list params UNUSED) 148{ 149 /* do nothing */ 150} 151 152int check_apply_state(struct apply_state *state, int force_apply) 153{ 154 int is_not_gitdir = !startup_info->have_repository; 155 156 if (state->apply_with_reject && state->threeway) 157 return error(_("options '%s' and '%s' cannot be used together"), "--reject", "--3way"); 158 if (state->threeway) { 159 if (is_not_gitdir) 160 return error(_("'%s' outside a repository"), "--3way"); 161 state->check_index = 1; 162 } 163 if (state->apply_with_reject) { 164 state->apply = 1; 165 if (state->apply_verbosity == verbosity_normal) 166 state->apply_verbosity = verbosity_verbose; 167 } 168 if (!force_apply && (state->diffstat || state->numstat || state->summary || state->check || state->fake_ancestor)) 169 state->apply = 0; 170 if (state->check_index && is_not_gitdir) 171 return error(_("'%s' outside a repository"), "--index"); 172 if (state->cached) { 173 if (is_not_gitdir) 174 return error(_("'%s' outside a repository"), "--cached"); 175 state->check_index = 1; 176 } 177 if (state->ita_only && (state->check_index || is_not_gitdir)) 178 state->ita_only = 0; 179 if (state->check_index) 180 state->unsafe_paths = 0; 181 182 if (state->apply_verbosity <= verbosity_silent) { 183 state->saved_error_routine = get_error_routine(); 184 state->saved_warn_routine = get_warn_routine(); 185 set_error_routine(mute_routine); 186 set_warn_routine(mute_routine); 187 } 188 189 return 0; 190} 191 192static void set_default_whitespace_mode(struct apply_state *state) 193{ 194 if (!state->whitespace_option && !apply_default_whitespace) 195 state->ws_error_action = (state->apply ? warn_on_ws_error : nowarn_ws_error); 196} 197 198/* 199 * This represents one "hunk" from a patch, starting with 200 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The 201 * patch text is pointed at by patch, and its byte length 202 * is stored in size. leading and trailing are the number 203 * of context lines. 204 */ 205struct fragment { 206 unsigned long leading, trailing; 207 unsigned long oldpos, oldlines; 208 unsigned long newpos, newlines; 209 /* 210 * 'patch' is usually borrowed from buf in apply_patch(), 211 * but some codepaths store an allocated buffer. 212 */ 213 const char *patch; 214 unsigned free_patch:1, 215 rejected:1; 216 int size; 217 int linenr; 218 struct fragment *next; 219}; 220 221/* 222 * When dealing with a binary patch, we reuse "leading" field 223 * to store the type of the binary hunk, either deflated "delta" 224 * or deflated "literal". 225 */ 226#define binary_patch_method leading 227#define BINARY_DELTA_DEFLATED 1 228#define BINARY_LITERAL_DEFLATED 2 229 230static void free_fragment_list(struct fragment *list) 231{ 232 while (list) { 233 struct fragment *next = list->next; 234 if (list->free_patch) 235 free((char *)list->patch); 236 free(list); 237 list = next; 238 } 239} 240 241void release_patch(struct patch *patch) 242{ 243 free_fragment_list(patch->fragments); 244 free(patch->def_name); 245 free(patch->old_name); 246 free(patch->new_name); 247 free(patch->result); 248} 249 250static void free_patch(struct patch *patch) 251{ 252 release_patch(patch); 253 free(patch); 254} 255 256static void free_patch_list(struct patch *list) 257{ 258 while (list) { 259 struct patch *next = list->next; 260 free_patch(list); 261 list = next; 262 } 263} 264 265/* 266 * A line in a file, len-bytes long (includes the terminating LF, 267 * except for an incomplete line at the end if the file ends with 268 * one), and its contents hashes to 'hash'. 269 */ 270struct line { 271 size_t len; 272 unsigned hash : 24; 273 unsigned flag : 8; 274#define LINE_COMMON 1 275#define LINE_PATCHED 2 276}; 277 278/* 279 * This represents a "file", which is an array of "lines". 280 */ 281struct image { 282 struct strbuf buf; 283 struct line *line; 284 size_t line_nr, line_alloc; 285}; 286#define IMAGE_INIT { \ 287 .buf = STRBUF_INIT, \ 288} 289 290static void image_init(struct image *image) 291{ 292 struct image empty = IMAGE_INIT; 293 memcpy(image, &empty, sizeof(*image)); 294} 295 296static void image_clear(struct image *image) 297{ 298 strbuf_release(&image->buf); 299 free(image->line); 300 image_init(image); 301} 302 303static uint32_t hash_line(const char *cp, size_t len) 304{ 305 size_t i; 306 uint32_t h; 307 for (i = 0, h = 0; i < len; i++) { 308 if (!isspace(cp[i])) { 309 h = h * 3 + (cp[i] & 0xff); 310 } 311 } 312 return h; 313} 314 315static void image_add_line(struct image *img, const char *bol, size_t len, unsigned flag) 316{ 317 ALLOC_GROW(img->line, img->line_nr + 1, img->line_alloc); 318 img->line[img->line_nr].len = len; 319 img->line[img->line_nr].hash = hash_line(bol, len); 320 img->line[img->line_nr].flag = flag; 321 img->line_nr++; 322} 323 324/* 325 * "buf" has the file contents to be patched (read from various sources). 326 * attach it to "image" and add line-based index to it. 327 * "image" now owns the "buf". 328 */ 329static void image_prepare(struct image *image, char *buf, size_t len, 330 int prepare_linetable) 331{ 332 const char *cp, *ep; 333 334 image_clear(image); 335 strbuf_attach(&image->buf, buf, len, len + 1); 336 337 if (!prepare_linetable) 338 return; 339 340 ep = image->buf.buf + image->buf.len; 341 cp = image->buf.buf; 342 while (cp < ep) { 343 const char *next; 344 for (next = cp; next < ep && *next != '\n'; next++) 345 ; 346 if (next < ep) 347 next++; 348 image_add_line(image, cp, next - cp, 0); 349 cp = next; 350 } 351} 352 353static void image_remove_first_line(struct image *img) 354{ 355 strbuf_remove(&img->buf, 0, img->line[0].len); 356 img->line_nr--; 357 if (img->line_nr) 358 MOVE_ARRAY(img->line, img->line + 1, img->line_nr); 359} 360 361static void image_remove_last_line(struct image *img) 362{ 363 size_t last_line_len = img->line[img->line_nr - 1].len; 364 strbuf_setlen(&img->buf, img->buf.len - last_line_len); 365 img->line_nr--; 366} 367 368/* fmt must contain _one_ %s and no other substitution */ 369static void say_patch_name(FILE *output, const char *fmt, struct patch *patch) 370{ 371 struct strbuf sb = STRBUF_INIT; 372 373 if (patch->old_name && patch->new_name && 374 strcmp(patch->old_name, patch->new_name)) { 375 quote_c_style(patch->old_name, &sb, NULL, 0); 376 strbuf_addstr(&sb, " => "); 377 quote_c_style(patch->new_name, &sb, NULL, 0); 378 } else { 379 const char *n = patch->new_name; 380 if (!n) 381 n = patch->old_name; 382 quote_c_style(n, &sb, NULL, 0); 383 } 384 fprintf(output, fmt, sb.buf); 385 fputc('\n', output); 386 strbuf_release(&sb); 387} 388 389#define SLOP (16) 390 391/* 392 * apply.c isn't equipped to handle arbitrarily large patches, because 393 * it intermingles `unsigned long` with `int` for the type used to store 394 * buffer lengths. 395 * 396 * Only process patches that are just shy of 1 GiB large in order to 397 * avoid any truncation or overflow issues. 398 */ 399#define MAX_APPLY_SIZE (1024UL * 1024 * 1023) 400 401static int read_patch_file(struct strbuf *sb, int fd) 402{ 403 if (strbuf_read(sb, fd, 0) < 0) 404 return error_errno(_("failed to read patch")); 405 else if (sb->len >= MAX_APPLY_SIZE) 406 return error(_("patch too large")); 407 /* 408 * Make sure that we have some slop in the buffer 409 * so that we can do speculative "memcmp" etc, and 410 * see to it that it is NUL-filled. 411 */ 412 strbuf_grow(sb, SLOP); 413 memset(sb->buf + sb->len, 0, SLOP); 414 return 0; 415} 416 417static unsigned long linelen(const char *buffer, unsigned long size) 418{ 419 unsigned long len = 0; 420 while (size--) { 421 len++; 422 if (*buffer++ == '\n') 423 break; 424 } 425 return len; 426} 427 428static int is_dev_null(const char *str) 429{ 430 return skip_prefix(str, "/dev/null", &str) && isspace(*str); 431} 432 433#define TERM_SPACE 1 434#define TERM_TAB 2 435 436static int name_terminate(int c, int terminate) 437{ 438 if (c == ' ' && !(terminate & TERM_SPACE)) 439 return 0; 440 if (c == '\t' && !(terminate & TERM_TAB)) 441 return 0; 442 443 return 1; 444} 445 446/* remove double slashes to make --index work with such filenames */ 447static char *squash_slash(char *name) 448{ 449 int i = 0, j = 0; 450 451 if (!name) 452 return NULL; 453 454 while (name[i]) { 455 if ((name[j++] = name[i++]) == '/') 456 while (name[i] == '/') 457 i++; 458 } 459 name[j] = '\0'; 460 return name; 461} 462 463static char *find_name_gnu(struct strbuf *root, 464 const char *line, 465 int p_value) 466{ 467 struct strbuf name = STRBUF_INIT; 468 char *cp; 469 470 /* 471 * Proposed "new-style" GNU patch/diff format; see 472 * https://lore.kernel.org/git/7vll0wvb2a.fsf@assigned-by-dhcp.cox.net/ 473 */ 474 if (unquote_c_style(&name, line, NULL)) { 475 strbuf_release(&name); 476 return NULL; 477 } 478 479 for (cp = name.buf; p_value; p_value--) { 480 cp = strchr(cp, '/'); 481 if (!cp) { 482 strbuf_release(&name); 483 return NULL; 484 } 485 cp++; 486 } 487 488 strbuf_remove(&name, 0, cp - name.buf); 489 if (root->len) 490 strbuf_insert(&name, 0, root->buf, root->len); 491 return squash_slash(strbuf_detach(&name, NULL)); 492} 493 494static size_t sane_tz_len(const char *line, size_t len) 495{ 496 const char *tz, *p; 497 498 if (len < strlen(" +0500") || line[len-strlen(" +0500")] != ' ') 499 return 0; 500 tz = line + len - strlen(" +0500"); 501 502 if (tz[1] != '+' && tz[1] != '-') 503 return 0; 504 505 for (p = tz + 2; p != line + len; p++) 506 if (!isdigit(*p)) 507 return 0; 508 509 return line + len - tz; 510} 511 512static size_t tz_with_colon_len(const char *line, size_t len) 513{ 514 const char *tz, *p; 515 516 if (len < strlen(" +08:00") || line[len - strlen(":00")] != ':') 517 return 0; 518 tz = line + len - strlen(" +08:00"); 519 520 if (tz[0] != ' ' || (tz[1] != '+' && tz[1] != '-')) 521 return 0; 522 p = tz + 2; 523 if (!isdigit(*p++) || !isdigit(*p++) || *p++ != ':' || 524 !isdigit(*p++) || !isdigit(*p++)) 525 return 0; 526 527 return line + len - tz; 528} 529 530static size_t date_len(const char *line, size_t len) 531{ 532 const char *date, *p; 533 534 if (len < strlen("72-02-05") || line[len-strlen("-05")] != '-') 535 return 0; 536 p = date = line + len - strlen("72-02-05"); 537 538 if (!isdigit(*p++) || !isdigit(*p++) || *p++ != '-' || 539 !isdigit(*p++) || !isdigit(*p++) || *p++ != '-' || 540 !isdigit(*p++) || !isdigit(*p++)) /* Not a date. */ 541 return 0; 542 543 if (date - line >= strlen("19") && 544 isdigit(date[-1]) && isdigit(date[-2])) /* 4-digit year */ 545 date -= strlen("19"); 546 547 return line + len - date; 548} 549 550static size_t short_time_len(const char *line, size_t len) 551{ 552 const char *time, *p; 553 554 if (len < strlen(" 07:01:32") || line[len-strlen(":32")] != ':') 555 return 0; 556 p = time = line + len - strlen(" 07:01:32"); 557 558 /* Permit 1-digit hours? */ 559 if (*p++ != ' ' || 560 !isdigit(*p++) || !isdigit(*p++) || *p++ != ':' || 561 !isdigit(*p++) || !isdigit(*p++) || *p++ != ':' || 562 !isdigit(*p++) || !isdigit(*p++)) /* Not a time. */ 563 return 0; 564 565 return line + len - time; 566} 567 568static size_t fractional_time_len(const char *line, size_t len) 569{ 570 const char *p; 571 size_t n; 572 573 /* Expected format: 19:41:17.620000023 */ 574 if (!len || !isdigit(line[len - 1])) 575 return 0; 576 p = line + len - 1; 577 578 /* Fractional seconds. */ 579 while (p > line && isdigit(*p)) 580 p--; 581 if (*p != '.') 582 return 0; 583 584 /* Hours, minutes, and whole seconds. */ 585 n = short_time_len(line, p - line); 586 if (!n) 587 return 0; 588 589 return line + len - p + n; 590} 591 592static size_t trailing_spaces_len(const char *line, size_t len) 593{ 594 const char *p; 595 596 /* Expected format: ' ' x (1 or more) */ 597 if (!len || line[len - 1] != ' ') 598 return 0; 599 600 p = line + len; 601 while (p != line) { 602 p--; 603 if (*p != ' ') 604 return line + len - (p + 1); 605 } 606 607 /* All spaces! */ 608 return len; 609} 610 611static size_t diff_timestamp_len(const char *line, size_t len) 612{ 613 const char *end = line + len; 614 size_t n; 615 616 /* 617 * Posix: 2010-07-05 19:41:17 618 * GNU: 2010-07-05 19:41:17.620000023 -0500 619 */ 620 621 if (!isdigit(end[-1])) 622 return 0; 623 624 n = sane_tz_len(line, end - line); 625 if (!n) 626 n = tz_with_colon_len(line, end - line); 627 end -= n; 628 629 n = short_time_len(line, end - line); 630 if (!n) 631 n = fractional_time_len(line, end - line); 632 end -= n; 633 634 n = date_len(line, end - line); 635 if (!n) /* No date. Too bad. */ 636 return 0; 637 end -= n; 638 639 if (end == line) /* No space before date. */ 640 return 0; 641 if (end[-1] == '\t') { /* Success! */ 642 end--; 643 return line + len - end; 644 } 645 if (end[-1] != ' ') /* No space before date. */ 646 return 0; 647 648 /* Whitespace damage. */ 649 end -= trailing_spaces_len(line, end - line); 650 return line + len - end; 651} 652 653static char *find_name_common(struct strbuf *root, 654 const char *line, 655 const char *def, 656 int p_value, 657 const char *end, 658 int terminate) 659{ 660 int len; 661 const char *start = NULL; 662 663 if (p_value == 0) 664 start = line; 665 while (line != end) { 666 char c = *line; 667 668 if (!end && isspace(c)) { 669 if (c == '\n') 670 break; 671 if (name_terminate(c, terminate)) 672 break; 673 } 674 line++; 675 if (c == '/' && !--p_value) 676 start = line; 677 } 678 if (!start) 679 return squash_slash(xstrdup_or_null(def)); 680 len = line - start; 681 if (!len) 682 return squash_slash(xstrdup_or_null(def)); 683 684 /* 685 * Generally we prefer the shorter name, especially 686 * if the other one is just a variation of that with 687 * something else tacked on to the end (ie "file.orig" 688 * or "file~"). 689 */ 690 if (def) { 691 int deflen = strlen(def); 692 if (deflen < len && !strncmp(start, def, deflen)) 693 return squash_slash(xstrdup(def)); 694 } 695 696 if (root->len) { 697 char *ret = xstrfmt("%s%.*s", root->buf, len, start); 698 return squash_slash(ret); 699 } 700 701 return squash_slash(xmemdupz(start, len)); 702} 703 704static char *find_name(struct strbuf *root, 705 const char *line, 706 char *def, 707 int p_value, 708 int terminate) 709{ 710 if (*line == '"') { 711 char *name = find_name_gnu(root, line, p_value); 712 if (name) 713 return name; 714 } 715 716 return find_name_common(root, line, def, p_value, NULL, terminate); 717} 718 719static char *find_name_traditional(struct strbuf *root, 720 const char *line, 721 char *def, 722 int p_value) 723{ 724 size_t len; 725 size_t date_len; 726 727 if (*line == '"') { 728 char *name = find_name_gnu(root, line, p_value); 729 if (name) 730 return name; 731 } 732 733 len = strchrnul(line, '\n') - line; 734 date_len = diff_timestamp_len(line, len); 735 if (!date_len) 736 return find_name_common(root, line, def, p_value, NULL, TERM_TAB); 737 len -= date_len; 738 739 return find_name_common(root, line, def, p_value, line + len, 0); 740} 741 742/* 743 * Given the string after "--- " or "+++ ", guess the appropriate 744 * p_value for the given patch. 745 */ 746static int guess_p_value(struct apply_state *state, const char *nameline) 747{ 748 char *name, *cp; 749 int val = -1; 750 751 if (is_dev_null(nameline)) 752 return -1; 753 name = find_name_traditional(&state->root, nameline, NULL, 0); 754 if (!name) 755 return -1; 756 cp = strchr(name, '/'); 757 if (!cp) 758 val = 0; 759 else if (state->prefix) { 760 /* 761 * Does it begin with "a/$our-prefix" and such? Then this is 762 * very likely to apply to our directory. 763 */ 764 if (starts_with(name, state->prefix)) 765 val = count_slashes(state->prefix); 766 else { 767 cp++; 768 if (starts_with(cp, state->prefix)) 769 val = count_slashes(state->prefix) + 1; 770 } 771 } 772 free(name); 773 return val; 774} 775 776/* 777 * Does the ---/+++ line have the POSIX timestamp after the last HT? 778 * GNU diff puts epoch there to signal a creation/deletion event. Is 779 * this such a timestamp? 780 */ 781static int has_epoch_timestamp(const char *nameline) 782{ 783 /* 784 * We are only interested in epoch timestamp; any non-zero 785 * fraction cannot be one, hence "(\.0+)?" in the regexp below. 786 * For the same reason, the date must be either 1969-12-31 or 787 * 1970-01-01, and the seconds part must be "00". 788 */ 789 const char stamp_regexp[] = 790 "^[0-2][0-9]:([0-5][0-9]):00(\\.0+)?" 791 " " 792 "([-+][0-2][0-9]:?[0-5][0-9])\n"; 793 const char *timestamp = NULL, *cp, *colon; 794 static regex_t *stamp; 795 regmatch_t m[10]; 796 int zoneoffset, epoch_hour, hour, minute; 797 int status; 798 799 for (cp = nameline; *cp != '\n'; cp++) { 800 if (*cp == '\t') 801 timestamp = cp + 1; 802 } 803 if (!timestamp) 804 return 0; 805 806 /* 807 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31 808 * (west of GMT) or 1970-01-01 (east of GMT) 809 */ 810 if (skip_prefix(timestamp, "1969-12-31 ", &timestamp)) 811 epoch_hour = 24; 812 else if (skip_prefix(timestamp, "1970-01-01 ", &timestamp)) 813 epoch_hour = 0; 814 else 815 return 0; 816 817 if (!stamp) { 818 stamp = xmalloc(sizeof(*stamp)); 819 if (regcomp(stamp, stamp_regexp, REG_EXTENDED)) { 820 warning(_("Cannot prepare timestamp regexp %s"), 821 stamp_regexp); 822 return 0; 823 } 824 } 825 826 status = regexec(stamp, timestamp, ARRAY_SIZE(m), m, 0); 827 if (status) { 828 if (status != REG_NOMATCH) 829 warning(_("regexec returned %d for input: %s"), 830 status, timestamp); 831 return 0; 832 } 833 834 hour = strtol(timestamp, NULL, 10); 835 minute = strtol(timestamp + m[1].rm_so, NULL, 10); 836 837 zoneoffset = strtol(timestamp + m[3].rm_so + 1, (char **) &colon, 10); 838 if (*colon == ':') 839 zoneoffset = zoneoffset * 60 + strtol(colon + 1, NULL, 10); 840 else 841 zoneoffset = (zoneoffset / 100) * 60 + (zoneoffset % 100); 842 if (timestamp[m[3].rm_so] == '-') 843 zoneoffset = -zoneoffset; 844 845 return hour * 60 + minute - zoneoffset == epoch_hour * 60; 846} 847 848/* 849 * Get the name etc info from the ---/+++ lines of a traditional patch header 850 * 851 * FIXME! The end-of-filename heuristics are kind of screwy. For existing 852 * files, we can happily check the index for a match, but for creating a 853 * new file we should try to match whatever "patch" does. I have no idea. 854 */ 855static int parse_traditional_patch(struct apply_state *state, 856 const char *first, 857 const char *second, 858 struct patch *patch) 859{ 860 char *name; 861 862 first += 4; /* skip "--- " */ 863 second += 4; /* skip "+++ " */ 864 if (!state->p_value_known) { 865 int p, q; 866 p = guess_p_value(state, first); 867 q = guess_p_value(state, second); 868 if (p < 0) p = q; 869 if (0 <= p && p == q) { 870 state->p_value = p; 871 state->p_value_known = 1; 872 } 873 } 874 if (is_dev_null(first)) { 875 patch->is_new = 1; 876 patch->is_delete = 0; 877 name = find_name_traditional(&state->root, second, NULL, state->p_value); 878 patch->new_name = name; 879 } else if (is_dev_null(second)) { 880 patch->is_new = 0; 881 patch->is_delete = 1; 882 name = find_name_traditional(&state->root, first, NULL, state->p_value); 883 patch->old_name = name; 884 } else { 885 char *first_name; 886 first_name = find_name_traditional(&state->root, first, NULL, state->p_value); 887 name = find_name_traditional(&state->root, second, first_name, state->p_value); 888 free(first_name); 889 if (has_epoch_timestamp(first)) { 890 patch->is_new = 1; 891 patch->is_delete = 0; 892 patch->new_name = name; 893 } else if (has_epoch_timestamp(second)) { 894 patch->is_new = 0; 895 patch->is_delete = 1; 896 patch->old_name = name; 897 } else { 898 patch->old_name = name; 899 patch->new_name = xstrdup_or_null(name); 900 } 901 } 902 if (!name) 903 return error(_("unable to find filename in patch at line %d"), state->linenr); 904 905 return 0; 906} 907 908static int gitdiff_hdrend(struct gitdiff_data *state UNUSED, 909 const char *line UNUSED, 910 struct patch *patch UNUSED) 911{ 912 return 1; 913} 914 915/* 916 * We're anal about diff header consistency, to make 917 * sure that we don't end up having strange ambiguous 918 * patches floating around. 919 * 920 * As a result, gitdiff_{old|new}name() will check 921 * their names against any previous information, just 922 * to make sure.. 923 */ 924#define DIFF_OLD_NAME 0 925#define DIFF_NEW_NAME 1 926 927static int gitdiff_verify_name(struct gitdiff_data *state, 928 const char *line, 929 int isnull, 930 char **name, 931 int side) 932{ 933 if (!*name && !isnull) { 934 *name = find_name(state->root, line, NULL, state->p_value, TERM_TAB); 935 return 0; 936 } 937 938 if (*name) { 939 char *another; 940 if (isnull) 941 return error(_("git apply: bad git-diff - expected /dev/null, got %s on line %d"), 942 *name, state->linenr); 943 another = find_name(state->root, line, NULL, state->p_value, TERM_TAB); 944 if (!another || strcmp(another, *name)) { 945 free(another); 946 return error((side == DIFF_NEW_NAME) ? 947 _("git apply: bad git-diff - inconsistent new filename on line %d") : 948 _("git apply: bad git-diff - inconsistent old filename on line %d"), state->linenr); 949 } 950 free(another); 951 } else { 952 if (!is_dev_null(line)) 953 return error(_("git apply: bad git-diff - expected /dev/null on line %d"), state->linenr); 954 } 955 956 return 0; 957} 958 959static int gitdiff_oldname(struct gitdiff_data *state, 960 const char *line, 961 struct patch *patch) 962{ 963 return gitdiff_verify_name(state, line, 964 patch->is_new, &patch->old_name, 965 DIFF_OLD_NAME); 966} 967 968static int gitdiff_newname(struct gitdiff_data *state, 969 const char *line, 970 struct patch *patch) 971{ 972 return gitdiff_verify_name(state, line, 973 patch->is_delete, &patch->new_name, 974 DIFF_NEW_NAME); 975} 976 977static int parse_mode_line(const char *line, int linenr, unsigned int *mode) 978{ 979 char *end; 980 *mode = strtoul(line, &end, 8); 981 if (end == line || !isspace(*end)) 982 return error(_("invalid mode on line %d: %s"), linenr, line); 983 *mode = canon_mode(*mode); 984 return 0; 985} 986 987static int gitdiff_oldmode(struct gitdiff_data *state, 988 const char *line, 989 struct patch *patch) 990{ 991 return parse_mode_line(line, state->linenr, &patch->old_mode); 992} 993 994static int gitdiff_newmode(struct gitdiff_data *state, 995 const char *line, 996 struct patch *patch) 997{ 998 return parse_mode_line(line, state->linenr, &patch->new_mode); 999} 1000 1001static int gitdiff_delete(struct gitdiff_data *state, 1002 const char *line, 1003 struct patch *patch) 1004{ 1005 patch->is_delete = 1; 1006 free(patch->old_name); 1007 patch->old_name = xstrdup_or_null(patch->def_name); 1008 return gitdiff_oldmode(state, line, patch); 1009} 1010 1011static int gitdiff_newfile(struct gitdiff_data *state, 1012 const char *line, 1013 struct patch *patch) 1014{ 1015 patch->is_new = 1; 1016 free(patch->new_name); 1017 patch->new_name = xstrdup_or_null(patch->def_name); 1018 return gitdiff_newmode(state, line, patch); 1019} 1020 1021static int gitdiff_copysrc(struct gitdiff_data *state, 1022 const char *line, 1023 struct patch *patch) 1024{ 1025 patch->is_copy = 1; 1026 free(patch->old_name); 1027 patch->old_name = find_name(state->root, line, NULL, state->p_value ? state->p_value - 1 : 0, 0); 1028 return 0; 1029} 1030 1031static int gitdiff_copydst(struct gitdiff_data *state, 1032 const char *line, 1033 struct patch *patch) 1034{ 1035 patch->is_copy = 1; 1036 free(patch->new_name); 1037 patch->new_name = find_name(state->root, line, NULL, state->p_value ? state->p_value - 1 : 0, 0); 1038 return 0; 1039} 1040 1041static int gitdiff_renamesrc(struct gitdiff_data *state, 1042 const char *line, 1043 struct patch *patch) 1044{ 1045 patch->is_rename = 1; 1046 free(patch->old_name); 1047 patch->old_name = find_name(state->root, line, NULL, state->p_value ? state->p_value - 1 : 0, 0); 1048 return 0; 1049} 1050 1051static int gitdiff_renamedst(struct gitdiff_data *state, 1052 const char *line, 1053 struct patch *patch) 1054{ 1055 patch->is_rename = 1; 1056 free(patch->new_name); 1057 patch->new_name = find_name(state->root, line, NULL, state->p_value ? state->p_value - 1 : 0, 0); 1058 return 0; 1059} 1060 1061static int gitdiff_similarity(struct gitdiff_data *state UNUSED, 1062 const char *line, 1063 struct patch *patch) 1064{ 1065 unsigned long val = strtoul(line, NULL, 10); 1066 if (val <= 100) 1067 patch->score = val; 1068 return 0; 1069} 1070 1071static int gitdiff_dissimilarity(struct gitdiff_data *state UNUSED, 1072 const char *line, 1073 struct patch *patch) 1074{ 1075 unsigned long val = strtoul(line, NULL, 10); 1076 if (val <= 100) 1077 patch->score = val; 1078 return 0; 1079} 1080 1081static int gitdiff_index(struct gitdiff_data *state, 1082 const char *line, 1083 struct patch *patch) 1084{ 1085 /* 1086 * index line is N hexadecimal, "..", N hexadecimal, 1087 * and optional space with octal mode. 1088 */ 1089 const char *ptr, *eol; 1090 int len; 1091 const unsigned hexsz = the_hash_algo->hexsz; 1092 1093 ptr = strchr(line, '.'); 1094 if (!ptr || ptr[1] != '.' || hexsz < ptr - line) 1095 return 0; 1096 len = ptr - line; 1097 memcpy(patch->old_oid_prefix, line, len); 1098 patch->old_oid_prefix[len] = 0; 1099 1100 line = ptr + 2; 1101 ptr = strchr(line, ' '); 1102 eol = strchrnul(line, '\n'); 1103 1104 if (!ptr || eol < ptr) 1105 ptr = eol; 1106 len = ptr - line; 1107 1108 if (hexsz < len) 1109 return 0; 1110 memcpy(patch->new_oid_prefix, line, len); 1111 patch->new_oid_prefix[len] = 0; 1112 if (*ptr == ' ') 1113 return gitdiff_oldmode(state, ptr + 1, patch); 1114 return 0; 1115} 1116 1117/* 1118 * This is normal for a diff that doesn't change anything: we'll fall through 1119 * into the next diff. Tell the parser to break out. 1120 */ 1121static int gitdiff_unrecognized(struct gitdiff_data *state UNUSED, 1122 const char *line UNUSED, 1123 struct patch *patch UNUSED) 1124{ 1125 return 1; 1126} 1127 1128/* 1129 * Skip p_value leading components from "line"; as we do not accept 1130 * absolute paths, return NULL in that case. 1131 */ 1132static const char *skip_tree_prefix(int p_value, 1133 const char *line, 1134 int llen) 1135{ 1136 int nslash; 1137 int i; 1138 1139 if (!p_value) 1140 return (llen && line[0] == '/') ? NULL : line; 1141 1142 nslash = p_value; 1143 for (i = 0; i < llen; i++) { 1144 int ch = line[i]; 1145 if (ch == '/' && --nslash <= 0) 1146 return (i == 0) ? NULL : &line[i + 1]; 1147 } 1148 return NULL; 1149} 1150 1151/* 1152 * This is to extract the same name that appears on "diff --git" 1153 * line. We do not find and return anything if it is a rename 1154 * patch, and it is OK because we will find the name elsewhere. 1155 * We need to reliably find name only when it is mode-change only, 1156 * creation or deletion of an empty file. In any of these cases, 1157 * both sides are the same name under a/ and b/ respectively. 1158 */ 1159static char *git_header_name(int p_value, 1160 const char *line, 1161 int llen) 1162{ 1163 const char *name; 1164 const char *second = NULL; 1165 size_t len, line_len; 1166 1167 line += strlen("diff --git "); 1168 llen -= strlen("diff --git "); 1169 1170 if (*line == '"') { 1171 const char *cp; 1172 struct strbuf first = STRBUF_INIT; 1173 struct strbuf sp = STRBUF_INIT; 1174 1175 if (unquote_c_style(&first, line, &second)) 1176 goto free_and_fail1; 1177 1178 /* strip the a/b prefix including trailing slash */ 1179 cp = skip_tree_prefix(p_value, first.buf, first.len); 1180 if (!cp) 1181 goto free_and_fail1; 1182 strbuf_remove(&first, 0, cp - first.buf); 1183 1184 /* 1185 * second points at one past closing dq of name. 1186 * find the second name. 1187 */ 1188 while ((second < line + llen) && isspace(*second)) 1189 second++; 1190 1191 if (line + llen <= second) 1192 goto free_and_fail1; 1193 if (*second == '"') { 1194 if (unquote_c_style(&sp, second, NULL)) 1195 goto free_and_fail1; 1196 cp = skip_tree_prefix(p_value, sp.buf, sp.len); 1197 if (!cp) 1198 goto free_and_fail1; 1199 /* They must match, otherwise ignore */ 1200 if (strcmp(cp, first.buf)) 1201 goto free_and_fail1; 1202 strbuf_release(&sp); 1203 return strbuf_detach(&first, NULL); 1204 } 1205 1206 /* unquoted second */ 1207 cp = skip_tree_prefix(p_value, second, line + llen - second); 1208 if (!cp) 1209 goto free_and_fail1; 1210 if (line + llen - cp != first.len || 1211 memcmp(first.buf, cp, first.len)) 1212 goto free_and_fail1; 1213 return strbuf_detach(&first, NULL); 1214 1215 free_and_fail1: 1216 strbuf_release(&first); 1217 strbuf_release(&sp); 1218 return NULL; 1219 } 1220 1221 /* unquoted first name */ 1222 name = skip_tree_prefix(p_value, line, llen); 1223 if (!name) 1224 return NULL; 1225 1226 /* 1227 * since the first name is unquoted, a dq if exists must be 1228 * the beginning of the second name. 1229 */ 1230 for (second = name; second < line + llen; second++) { 1231 if (*second == '"') { 1232 struct strbuf sp = STRBUF_INIT; 1233 const char *np; 1234 1235 if (unquote_c_style(&sp, second, NULL)) 1236 goto free_and_fail2; 1237 1238 np = skip_tree_prefix(p_value, sp.buf, sp.len); 1239 if (!np) 1240 goto free_and_fail2; 1241 1242 len = sp.buf + sp.len - np; 1243 if (len < second - name && 1244 !strncmp(np, name, len) && 1245 isspace(name[len])) { 1246 /* Good */ 1247 strbuf_remove(&sp, 0, np - sp.buf); 1248 return strbuf_detach(&sp, NULL); 1249 } 1250 1251 free_and_fail2: 1252 strbuf_release(&sp); 1253 return NULL; 1254 } 1255 } 1256 1257 /* 1258 * Accept a name only if it shows up twice, exactly the same 1259 * form. 1260 */ 1261 second = strchr(name, '\n'); 1262 if (!second) 1263 return NULL; 1264 line_len = second - name; 1265 for (len = 0 ; ; len++) { 1266 switch (name[len]) { 1267 default: 1268 continue; 1269 case '\n': 1270 return NULL; 1271 case '\t': case ' ': 1272 /* 1273 * Is this the separator between the preimage 1274 * and the postimage pathname? Again, we are 1275 * only interested in the case where there is 1276 * no rename, as this is only to set def_name 1277 * and a rename patch has the names elsewhere 1278 * in an unambiguous form. 1279 */ 1280 if (!name[len + 1]) 1281 return NULL; /* no postimage name */ 1282 second = skip_tree_prefix(p_value, name + len + 1, 1283 line_len - (len + 1)); 1284 /* 1285 * If we are at the SP at the end of a directory, 1286 * skip_tree_prefix() may return NULL as that makes 1287 * it appears as if we have an absolute path. 1288 * Keep going to find another SP. 1289 */ 1290 if (!second) 1291 continue; 1292 1293 /* 1294 * Does len bytes starting at "name" and "second" 1295 * (that are separated by one HT or SP we just 1296 * found) exactly match? 1297 */ 1298 if (second[len] == '\n' && !strncmp(name, second, len)) 1299 return xmemdupz(name, len); 1300 } 1301 } 1302} 1303 1304static int check_header_line(int linenr, struct patch *patch) 1305{ 1306 int extensions = (patch->is_delete == 1) + (patch->is_new == 1) + 1307 (patch->is_rename == 1) + (patch->is_copy == 1); 1308 if (extensions > 1) 1309 return error(_("inconsistent header lines %d and %d"), 1310 patch->extension_linenr, linenr); 1311 if (extensions && !patch->extension_linenr) 1312 patch->extension_linenr = linenr; 1313 return 0; 1314} 1315 1316int parse_git_diff_header(struct strbuf *root, 1317 int *linenr, 1318 int p_value, 1319 const char *line, 1320 int len, 1321 unsigned int size, 1322 struct patch *patch) 1323{ 1324 unsigned long offset; 1325 struct gitdiff_data parse_hdr_state; 1326 1327 /* A git diff has explicit new/delete information, so we don't guess */ 1328 patch->is_new = 0; 1329 patch->is_delete = 0; 1330 1331 /* 1332 * Some things may not have the old name in the 1333 * rest of the headers anywhere (pure mode changes, 1334 * or removing or adding empty files), so we get 1335 * the default name from the header. 1336 */ 1337 patch->def_name = git_header_name(p_value, line, len); 1338 if (patch->def_name && root->len) { 1339 char *s = xstrfmt("%s%s", root->buf, patch->def_name); 1340 free(patch->def_name); 1341 patch->def_name = s; 1342 } 1343 1344 line += len; 1345 size -= len; 1346 (*linenr)++; 1347 parse_hdr_state.root = root; 1348 parse_hdr_state.linenr = *linenr; 1349 parse_hdr_state.p_value = p_value; 1350 1351 for (offset = len ; size > 0 ; offset += len, size -= len, line += len, (*linenr)++) { 1352 static const struct opentry { 1353 const char *str; 1354 int (*fn)(struct gitdiff_data *, const char *, struct patch *); 1355 } optable[] = { 1356 { "@@ -", gitdiff_hdrend }, 1357 { "--- ", gitdiff_oldname }, 1358 { "+++ ", gitdiff_newname }, 1359 { "old mode ", gitdiff_oldmode }, 1360 { "new mode ", gitdiff_newmode }, 1361 { "deleted file mode ", gitdiff_delete }, 1362 { "new file mode ", gitdiff_newfile }, 1363 { "copy from ", gitdiff_copysrc }, 1364 { "copy to ", gitdiff_copydst }, 1365 { "rename old ", gitdiff_renamesrc }, 1366 { "rename new ", gitdiff_renamedst }, 1367 { "rename from ", gitdiff_renamesrc }, 1368 { "rename to ", gitdiff_renamedst }, 1369 { "similarity index ", gitdiff_similarity }, 1370 { "dissimilarity index ", gitdiff_dissimilarity }, 1371 { "index ", gitdiff_index }, 1372 { "", gitdiff_unrecognized }, 1373 }; 1374 int i; 1375 1376 len = linelen(line, size); 1377 if (!len || line[len-1] != '\n') 1378 break; 1379 for (i = 0; i < ARRAY_SIZE(optable); i++) { 1380 const struct opentry *p = optable + i; 1381 int oplen = strlen(p->str); 1382 int res; 1383 if (len < oplen || memcmp(p->str, line, oplen)) 1384 continue; 1385 res = p->fn(&parse_hdr_state, line + oplen, patch); 1386 if (res < 0) 1387 return -1; 1388 if (check_header_line(*linenr, patch)) 1389 return -1; 1390 if (res > 0) 1391 goto done; 1392 break; 1393 } 1394 } 1395 1396done: 1397 if (!patch->old_name && !patch->new_name) { 1398 if (!patch->def_name) { 1399 error(Q_("git diff header lacks filename information when removing " 1400 "%d leading pathname component (line %d)", 1401 "git diff header lacks filename information when removing " 1402 "%d leading pathname components (line %d)", 1403 parse_hdr_state.p_value), 1404 parse_hdr_state.p_value, *linenr); 1405 return -128; 1406 } 1407 patch->old_name = xstrdup(patch->def_name); 1408 patch->new_name = xstrdup(patch->def_name); 1409 } 1410 if ((!patch->new_name && !patch->is_delete) || 1411 (!patch->old_name && !patch->is_new)) { 1412 error(_("git diff header lacks filename information " 1413 "(line %d)"), *linenr); 1414 return -128; 1415 } 1416 patch->is_toplevel_relative = 1; 1417 return offset; 1418} 1419 1420static int parse_num(const char *line, unsigned long *p) 1421{ 1422 char *ptr; 1423 1424 if (!isdigit(*line)) 1425 return 0; 1426 errno = 0; 1427 *p = strtoul(line, &ptr, 10); 1428 if (errno) 1429 return 0; 1430 return ptr - line; 1431} 1432 1433static int parse_range(const char *line, int len, int offset, const char *expect, 1434 unsigned long *p1, unsigned long *p2) 1435{ 1436 int digits, ex; 1437 1438 if (offset < 0 || offset >= len) 1439 return -1; 1440 line += offset; 1441 len -= offset; 1442 1443 digits = parse_num(line, p1); 1444 if (!digits) 1445 return -1; 1446 1447 offset += digits; 1448 line += digits; 1449 len -= digits; 1450 1451 *p2 = 1; 1452 if (*line == ',') { 1453 digits = parse_num(line+1, p2); 1454 if (!digits) 1455 return -1; 1456 1457 offset += digits+1; 1458 line += digits+1; 1459 len -= digits+1; 1460 } 1461 1462 ex = strlen(expect); 1463 if (ex > len) 1464 return -1; 1465 if (memcmp(line, expect, ex)) 1466 return -1; 1467 1468 return offset + ex; 1469} 1470 1471static void recount_diff(const char *line, int size, struct fragment *fragment) 1472{ 1473 int oldlines = 0, newlines = 0, ret = 0; 1474 1475 if (size < 1) { 1476 warning("recount: ignore empty hunk"); 1477 return; 1478 } 1479 1480 for (;;) { 1481 int len = linelen(line, size); 1482 size -= len; 1483 line += len; 1484 1485 if (size < 1) 1486 break; 1487 1488 switch (*line) { 1489 case ' ': case '\n': 1490 newlines++; 1491 /* fall through */ 1492 case '-': 1493 oldlines++; 1494 continue; 1495 case '+': 1496 newlines++; 1497 continue; 1498 case '\\': 1499 continue; 1500 case '@': 1501 ret = size < 3 || !starts_with(line, "@@ "); 1502 break; 1503 case 'd': 1504 ret = size < 5 || !starts_with(line, "diff "); 1505 break; 1506 default: 1507 ret = -1; 1508 break; 1509 } 1510 if (ret) { 1511 warning(_("recount: unexpected line: %.*s"), 1512 (int)linelen(line, size), line); 1513 return; 1514 } 1515 break; 1516 } 1517 fragment->oldlines = oldlines; 1518 fragment->newlines = newlines; 1519} 1520 1521/* 1522 * Parse a unified diff fragment header of the 1523 * form "@@ -a,b +c,d @@" 1524 */ 1525static int parse_fragment_header(const char *line, int len, struct fragment *fragment) 1526{ 1527 int offset; 1528 1529 if (!len || line[len-1] != '\n') 1530 return -1; 1531 1532 /* Figure out the number of lines in a fragment */ 1533 offset = parse_range(line, len, 4, " +", &fragment->oldpos, &fragment->oldlines); 1534 offset = parse_range(line, len, offset, " @@", &fragment->newpos, &fragment->newlines); 1535 1536 return offset; 1537} 1538 1539/* 1540 * Find file diff header 1541 * 1542 * Returns: 1543 * -1 if no header was found 1544 * -128 in case of error 1545 * the size of the header in bytes (called "offset") otherwise 1546 */ 1547static int find_header(struct apply_state *state, 1548 const char *line, 1549 unsigned long size, 1550 int *hdrsize, 1551 struct patch *patch) 1552{ 1553 unsigned long offset, len; 1554 1555 patch->is_toplevel_relative = 0; 1556 patch->is_rename = patch->is_copy = 0; 1557 patch->is_new = patch->is_delete = -1; 1558 patch->old_mode = patch->new_mode = 0; 1559 patch->old_name = patch->new_name = NULL; 1560 for (offset = 0; size > 0; offset += len, size -= len, line += len, state->linenr++) { 1561 unsigned long nextlen; 1562 1563 len = linelen(line, size); 1564 if (!len) 1565 break; 1566 1567 /* Testing this early allows us to take a few shortcuts.. */ 1568 if (len < 6) 1569 continue; 1570 1571 /* 1572 * Make sure we don't find any unconnected patch fragments. 1573 * That's a sign that we didn't find a header, and that a 1574 * patch has become corrupted/broken up. 1575 */ 1576 if (!memcmp("@@ -", line, 4)) { 1577 struct fragment dummy; 1578 if (parse_fragment_header(line, len, &dummy) < 0) 1579 continue; 1580 error(_("patch fragment without header at line %d: %.*s"), 1581 state->linenr, (int)len-1, line); 1582 return -128; 1583 } 1584 1585 if (size < len + 6) 1586 break; 1587 1588 /* 1589 * Git patch? It might not have a real patch, just a rename 1590 * or mode change, so we handle that specially 1591 */ 1592 if (!memcmp("diff --git ", line, 11)) { 1593 int git_hdr_len = parse_git_diff_header(&state->root, &state->linenr, 1594 state->p_value, line, len, 1595 size, patch); 1596 if (git_hdr_len < 0) 1597 return -128; 1598 if (git_hdr_len <= len) 1599 continue; 1600 *hdrsize = git_hdr_len; 1601 return offset; 1602 } 1603 1604 /* --- followed by +++ ? */ 1605 if (memcmp("--- ", line, 4) || memcmp("+++ ", line + len, 4)) 1606 continue; 1607 1608 /* 1609 * We only accept unified patches, so we want it to 1610 * at least have "@@ -a,b +c,d @@\n", which is 14 chars 1611 * minimum ("@@ -0,0 +1 @@\n" is the shortest). 1612 */ 1613 nextlen = linelen(line + len, size - len); 1614 if (size < nextlen + 14 || memcmp("@@ -", line + len + nextlen, 4)) 1615 continue; 1616 1617 /* Ok, we'll consider it a patch */ 1618 if (parse_traditional_patch(state, line, line+len, patch)) 1619 return -128; 1620 *hdrsize = len + nextlen; 1621 state->linenr += 2; 1622 return offset; 1623 } 1624 return -1; 1625} 1626 1627static void record_ws_error(struct apply_state *state, 1628 unsigned result, 1629 const char *line, 1630 int len, 1631 int linenr) 1632{ 1633 char *err; 1634 1635 if (!result) 1636 return; 1637 1638 state->whitespace_error++; 1639 if (state->squelch_whitespace_errors && 1640 state->squelch_whitespace_errors < state->whitespace_error) 1641 return; 1642 1643 err = whitespace_error_string(result); 1644 if (state->apply_verbosity > verbosity_silent) 1645 fprintf(stderr, "%s:%d: %s.\n%.*s\n", 1646 state->patch_input_file, linenr, err, len, line); 1647 free(err); 1648} 1649 1650static void check_whitespace(struct apply_state *state, 1651 const char *line, 1652 int len, 1653 unsigned ws_rule) 1654{ 1655 unsigned result = ws_check(line + 1, len - 1, ws_rule); 1656 1657 record_ws_error(state, result, line + 1, len - 2, state->linenr); 1658} 1659 1660/* 1661 * Check if the patch has context lines with CRLF or 1662 * the patch wants to remove lines with CRLF. 1663 */ 1664static void check_old_for_crlf(struct patch *patch, const char *line, int len) 1665{ 1666 if (len >= 2 && line[len-1] == '\n' && line[len-2] == '\r') { 1667 patch->ws_rule |= WS_CR_AT_EOL; 1668 patch->crlf_in_old = 1; 1669 } 1670} 1671 1672 1673/* 1674 * Parse a unified diff. Note that this really needs to parse each 1675 * fragment separately, since the only way to know the difference 1676 * between a "---" that is part of a patch, and a "---" that starts 1677 * the next patch is to look at the line counts.. 1678 */ 1679static int parse_fragment(struct apply_state *state, 1680 const char *line, 1681 unsigned long size, 1682 struct patch *patch, 1683 struct fragment *fragment) 1684{ 1685 int added, deleted; 1686 int len = linelen(line, size), offset; 1687 unsigned long oldlines, newlines; 1688 unsigned long leading, trailing; 1689 1690 offset = parse_fragment_header(line, len, fragment); 1691 if (offset < 0) 1692 return -1; 1693 if (offset > 0 && patch->recount) 1694 recount_diff(line + offset, size - offset, fragment); 1695 oldlines = fragment->oldlines; 1696 newlines = fragment->newlines; 1697 leading = 0; 1698 trailing = 0; 1699 1700 /* Parse the thing.. */ 1701 line += len; 1702 size -= len; 1703 state->linenr++; 1704 added = deleted = 0; 1705 for (offset = len; 1706 0 < size; 1707 offset += len, size -= len, line += len, state->linenr++) { 1708 if (!oldlines && !newlines) 1709 break; 1710 len = linelen(line, size); 1711 if (!len || line[len-1] != '\n') 1712 return -1; 1713 switch (*line) { 1714 default: 1715 return -1; 1716 case '\n': /* newer GNU diff, an empty context line */ 1717 case ' ': 1718 oldlines--; 1719 newlines--; 1720 if (!deleted && !added) 1721 leading++; 1722 trailing++; 1723 check_old_for_crlf(patch, line, len); 1724 if (!state->apply_in_reverse && 1725 state->ws_error_action == correct_ws_error) 1726 check_whitespace(state, line, len, patch->ws_rule); 1727 break; 1728 case '-': 1729 if (!state->apply_in_reverse) 1730 check_old_for_crlf(patch, line, len); 1731 if (state->apply_in_reverse && 1732 state->ws_error_action != nowarn_ws_error) 1733 check_whitespace(state, line, len, patch->ws_rule); 1734 deleted++; 1735 oldlines--; 1736 trailing = 0; 1737 break; 1738 case '+': 1739 if (state->apply_in_reverse) 1740 check_old_for_crlf(patch, line, len); 1741 if (!state->apply_in_reverse && 1742 state->ws_error_action != nowarn_ws_error) 1743 check_whitespace(state, line, len, patch->ws_rule); 1744 added++; 1745 newlines--; 1746 trailing = 0; 1747 break; 1748 1749 /* 1750 * We allow "\ No newline at end of file". Depending 1751 * on locale settings when the patch was produced we 1752 * don't know what this line looks like. The only 1753 * thing we do know is that it begins with "\ ". 1754 * Checking for 12 is just for sanity check -- any 1755 * l10n of "\ No newline..." is at least that long. 1756 */ 1757 case '\\': 1758 if (len < 12 || memcmp(line, "\\ ", 2)) 1759 return -1; 1760 break; 1761 } 1762 } 1763 if (oldlines || newlines) 1764 return -1; 1765 if (!patch->recount && !deleted && !added) 1766 return -1; 1767 1768 fragment->leading = leading; 1769 fragment->trailing = trailing; 1770 1771 /* 1772 * If a fragment ends with an incomplete line, we failed to include 1773 * it in the above loop because we hit oldlines == newlines == 0 1774 * before seeing it. 1775 */ 1776 if (12 < size && !memcmp(line, "\\ ", 2)) 1777 offset += linelen(line, size); 1778 1779 patch->lines_added += added; 1780 patch->lines_deleted += deleted; 1781 1782 if (0 < patch->is_new && oldlines) 1783 return error(_("new file depends on old contents")); 1784 if (0 < patch->is_delete && newlines) 1785 return error(_("deleted file still has contents")); 1786 return offset; 1787} 1788 1789/* 1790 * We have seen "diff --git a/... b/..." header (or a traditional patch 1791 * header). Read hunks that belong to this patch into fragments and hang 1792 * them to the given patch structure. 1793 * 1794 * The (fragment->patch, fragment->size) pair points into the memory given 1795 * by the caller, not a copy, when we return. 1796 * 1797 * Returns: 1798 * -1 in case of error, 1799 * the number of bytes in the patch otherwise. 1800 */ 1801static int parse_single_patch(struct apply_state *state, 1802 const char *line, 1803 unsigned long size, 1804 struct patch *patch) 1805{ 1806 unsigned long offset = 0; 1807 unsigned long oldlines = 0, newlines = 0, context = 0; 1808 struct fragment **fragp = &patch->fragments; 1809 1810 while (size > 4 && !memcmp(line, "@@ -", 4)) { 1811 struct fragment *fragment; 1812 int len; 1813 1814 CALLOC_ARRAY(fragment, 1); 1815 fragment->linenr = state->linenr; 1816 len = parse_fragment(state, line, size, patch, fragment); 1817 if (len <= 0) { 1818 free(fragment); 1819 return error(_("corrupt patch at line %d"), state->linenr); 1820 } 1821 fragment->patch = line; 1822 fragment->size = len; 1823 oldlines += fragment->oldlines; 1824 newlines += fragment->newlines; 1825 context += fragment->leading + fragment->trailing; 1826 1827 *fragp = fragment; 1828 fragp = &fragment->next; 1829 1830 offset += len; 1831 line += len; 1832 size -= len; 1833 } 1834 1835 /* 1836 * If something was removed (i.e. we have old-lines) it cannot 1837 * be creation, and if something was added it cannot be 1838 * deletion. However, the reverse is not true; --unified=0 1839 * patches that only add are not necessarily creation even 1840 * though they do not have any old lines, and ones that only 1841 * delete are not necessarily deletion. 1842 * 1843 * Unfortunately, a real creation/deletion patch do _not_ have 1844 * any context line by definition, so we cannot safely tell it 1845 * apart with --unified=0 insanity. At least if the patch has 1846 * more than one hunk it is not creation or deletion. 1847 */ 1848 if (patch->is_new < 0 && 1849 (oldlines || (patch->fragments && patch->fragments->next))) 1850 patch->is_new = 0; 1851 if (patch->is_delete < 0 && 1852 (newlines || (patch->fragments && patch->fragments->next))) 1853 patch->is_delete = 0; 1854 1855 if (0 < patch->is_new && oldlines) 1856 return error(_("new file %s depends on old contents"), patch->new_name); 1857 if (0 < patch->is_delete && newlines) 1858 return error(_("deleted file %s still has contents"), patch->old_name); 1859 if (!patch->is_delete && !newlines && context && state->apply_verbosity > verbosity_silent) 1860 fprintf_ln(stderr, 1861 _("** warning: " 1862 "file %s becomes empty but is not deleted"), 1863 patch->new_name); 1864 1865 return offset; 1866} 1867 1868static inline int metadata_changes(struct patch *patch) 1869{ 1870 return patch->is_rename > 0 || 1871 patch->is_copy > 0 || 1872 patch->is_new > 0 || 1873 patch->is_delete || 1874 (patch->old_mode && patch->new_mode && 1875 patch->old_mode != patch->new_mode); 1876} 1877 1878static char *inflate_it(const void *data, unsigned long size, 1879 unsigned long inflated_size) 1880{ 1881 git_zstream stream; 1882 void *out; 1883 int st; 1884 1885 memset(&stream, 0, sizeof(stream)); 1886 1887 stream.next_in = (unsigned char *)data; 1888 stream.avail_in = size; 1889 stream.next_out = out = xmalloc(inflated_size); 1890 stream.avail_out = inflated_size; 1891 git_inflate_init(&stream); 1892 st = git_inflate(&stream, Z_FINISH); 1893 git_inflate_end(&stream); 1894 if ((st != Z_STREAM_END) || stream.total_out != inflated_size) { 1895 free(out); 1896 return NULL; 1897 } 1898 return out; 1899} 1900 1901/* 1902 * Read a binary hunk and return a new fragment; fragment->patch 1903 * points at an allocated memory that the caller must free, so 1904 * it is marked as "->free_patch = 1". 1905 */ 1906static struct fragment *parse_binary_hunk(struct apply_state *state, 1907 char **buf_p, 1908 unsigned long *sz_p, 1909 int *status_p, 1910 int *used_p) 1911{ 1912 /* 1913 * Expect a line that begins with binary patch method ("literal" 1914 * or "delta"), followed by the length of data before deflating. 1915 * a sequence of 'length-byte' followed by base-85 encoded data 1916 * should follow, terminated by a newline. 1917 * 1918 * Each 5-byte sequence of base-85 encodes up to 4 bytes, 1919 * and we would limit the patch line to 66 characters, 1920 * so one line can fit up to 13 groups that would decode 1921 * to 52 bytes max. The length byte 'A'-'Z' corresponds 1922 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes. 1923 */ 1924 int llen, used; 1925 unsigned long size = *sz_p; 1926 char *buffer = *buf_p; 1927 int patch_method; 1928 unsigned long origlen; 1929 char *data = NULL; 1930 int hunk_size = 0; 1931 struct fragment *frag; 1932 1933 llen = linelen(buffer, size); 1934 used = llen; 1935 1936 *status_p = 0; 1937 1938 if (starts_with(buffer, "delta ")) { 1939 patch_method = BINARY_DELTA_DEFLATED; 1940 origlen = strtoul(buffer + 6, NULL, 10); 1941 } 1942 else if (starts_with(buffer, "literal ")) { 1943 patch_method = BINARY_LITERAL_DEFLATED; 1944 origlen = strtoul(buffer + 8, NULL, 10); 1945 } 1946 else 1947 return NULL; 1948 1949 state->linenr++; 1950 buffer += llen; 1951 size -= llen; 1952 while (1) { 1953 int byte_length, max_byte_length, newsize; 1954 llen = linelen(buffer, size); 1955 used += llen; 1956 state->linenr++; 1957 if (llen == 1) { 1958 /* consume the blank line */ 1959 buffer++; 1960 size--; 1961 break; 1962 } 1963 /* 1964 * Minimum line is "A00000\n" which is 7-byte long, 1965 * and the line length must be multiple of 5 plus 2. 1966 */ 1967 if ((llen < 7) || (llen-2) % 5) 1968 goto corrupt; 1969 max_byte_length = (llen - 2) / 5 * 4; 1970 byte_length = *buffer; 1971 if ('A' <= byte_length && byte_length <= 'Z') 1972 byte_length = byte_length - 'A' + 1; 1973 else if ('a' <= byte_length && byte_length <= 'z') 1974 byte_length = byte_length - 'a' + 27; 1975 else 1976 goto corrupt; 1977 /* if the input length was not multiple of 4, we would 1978 * have filler at the end but the filler should never 1979 * exceed 3 bytes 1980 */ 1981 if (max_byte_length < byte_length || 1982 byte_length <= max_byte_length - 4) 1983 goto corrupt; 1984 newsize = hunk_size + byte_length; 1985 data = xrealloc(data, newsize); 1986 if (decode_85(data + hunk_size, buffer + 1, byte_length)) 1987 goto corrupt; 1988 hunk_size = newsize; 1989 buffer += llen; 1990 size -= llen; 1991 } 1992 1993 CALLOC_ARRAY(frag, 1); 1994 frag->patch = inflate_it(data, hunk_size, origlen); 1995 frag->free_patch = 1; 1996 if (!frag->patch) 1997 goto corrupt; 1998 free(data); 1999 frag->size = origlen; 2000 *buf_p = buffer; 2001 *sz_p = size; 2002 *used_p = used; 2003 frag->binary_patch_method = patch_method; 2004 return frag; 2005 2006 corrupt: 2007 free(data); 2008 *status_p = -1; 2009 error(_("corrupt binary patch at line %d: %.*s"), 2010 state->linenr-1, llen-1, buffer); 2011 return NULL; 2012} 2013 2014/* 2015 * Returns: 2016 * -1 in case of error, 2017 * the length of the parsed binary patch otherwise 2018 */ 2019static int parse_binary(struct apply_state *state, 2020 char *buffer, 2021 unsigned long size, 2022 struct patch *patch) 2023{ 2024 /* 2025 * We have read "GIT binary patch\n"; what follows is a line 2026 * that says the patch method (currently, either "literal" or 2027 * "delta") and the length of data before deflating; a 2028 * sequence of 'length-byte' followed by base-85 encoded data 2029 * follows. 2030 * 2031 * When a binary patch is reversible, there is another binary 2032 * hunk in the same format, starting with patch method (either 2033 * "literal" or "delta") with the length of data, and a sequence 2034 * of length-byte + base-85 encoded data, terminated with another 2035 * empty line. This data, when applied to the postimage, produces 2036 * the preimage. 2037 */ 2038 struct fragment *forward; 2039 struct fragment *reverse; 2040 int status; 2041 int used, used_1; 2042 2043 forward = parse_binary_hunk(state, &buffer, &size, &status, &used); 2044 if (!forward && !status) 2045 /* there has to be one hunk (forward hunk) */ 2046 return error(_("unrecognized binary patch at line %d"), state->linenr-1); 2047 if (status) 2048 /* otherwise we already gave an error message */ 2049 return status; 2050 2051 reverse = parse_binary_hunk(state, &buffer, &size, &status, &used_1); 2052 if (reverse) 2053 used += used_1; 2054 else if (status) { 2055 /* 2056 * Not having reverse hunk is not an error, but having 2057 * a corrupt reverse hunk is. 2058 */ 2059 free((void*) forward->patch); 2060 free(forward); 2061 return status; 2062 } 2063 forward->next = reverse; 2064 patch->fragments = forward; 2065 patch->is_binary = 1; 2066 return used; 2067} 2068 2069static void prefix_one(struct apply_state *state, char **name) 2070{ 2071 char *old_name = *name; 2072 if (!old_name) 2073 return; 2074 *name = prefix_filename(state->prefix, *name); 2075 free(old_name); 2076} 2077 2078static void prefix_patch(struct apply_state *state, struct patch *p) 2079{ 2080 if (!state->prefix || p->is_toplevel_relative) 2081 return; 2082 prefix_one(state, &p->new_name); 2083 prefix_one(state, &p->old_name); 2084} 2085 2086/* 2087 * include/exclude 2088 */ 2089 2090static void add_name_limit(struct apply_state *state, 2091 const char *name, 2092 int exclude) 2093{ 2094 struct string_list_item *it; 2095 2096 it = string_list_append(&state->limit_by_name, name); 2097 it->util = exclude ? NULL : (void *) 1; 2098} 2099 2100static int use_patch(struct apply_state *state, struct patch *p) 2101{ 2102 const char *pathname = p->new_name ? p->new_name : p->old_name; 2103 int i; 2104 2105 /* Paths outside are not touched regardless of "--include" */ 2106 if (state->prefix && *state->prefix) { 2107 const char *rest; 2108 if (!skip_prefix(pathname, state->prefix, &rest) || !*rest) 2109 return 0; 2110 } 2111 2112 /* See if it matches any of exclude/include rule */ 2113 for (i = 0; i < state->limit_by_name.nr; i++) { 2114 struct string_list_item *it = &state->limit_by_name.items[i]; 2115 if (!wildmatch(it->string, pathname, 0)) 2116 return (it->util != NULL); 2117 } 2118 2119 /* 2120 * If we had any include, a path that does not match any rule is 2121 * not used. Otherwise, we saw bunch of exclude rules (or none) 2122 * and such a path is used. 2123 */ 2124 return !state->has_include; 2125} 2126 2127/* 2128 * Read the patch text in "buffer" that extends for "size" bytes; stop 2129 * reading after seeing a single patch (i.e. changes to a single file). 2130 * Create fragments (i.e. patch hunks) and hang them to the given patch. 2131 * 2132 * Returns: 2133 * -1 if no header was found or parse_binary() failed, 2134 * -128 on another error, 2135 * the number of bytes consumed otherwise, 2136 * so that the caller can call us again for the next patch. 2137 */ 2138static int parse_chunk(struct apply_state *state, char *buffer, unsigned long size, struct patch *patch) 2139{ 2140 int hdrsize, patchsize; 2141 int offset = find_header(state, buffer, size, &hdrsize, patch); 2142 2143 if (offset < 0) 2144 return offset; 2145 2146 prefix_patch(state, patch); 2147 2148 if (!use_patch(state, patch)) 2149 patch->ws_rule = 0; 2150 else if (patch->new_name) 2151 patch->ws_rule = whitespace_rule(state->repo->index, 2152 patch->new_name); 2153 else 2154 patch->ws_rule = whitespace_rule(state->repo->index, 2155 patch->old_name); 2156 2157 patchsize = parse_single_patch(state, 2158 buffer + offset + hdrsize, 2159 size - offset - hdrsize, 2160 patch); 2161 2162 if (patchsize < 0) 2163 return -128; 2164 2165 if (!patchsize) { 2166 static const char git_binary[] = "GIT binary patch\n"; 2167 int hd = hdrsize + offset; 2168 unsigned long llen = linelen(buffer + hd, size - hd); 2169 2170 if (llen == sizeof(git_binary) - 1 && 2171 !memcmp(git_binary, buffer + hd, llen)) { 2172 int used; 2173 state->linenr++; 2174 used = parse_binary(state, buffer + hd + llen, 2175 size - hd - llen, patch); 2176 if (used < 0) 2177 return -1; 2178 if (used) 2179 patchsize = used + llen; 2180 else 2181 patchsize = 0; 2182 } 2183 else if (!memcmp(" differ\n", buffer + hd + llen - 8, 8)) { 2184 static const char *binhdr[] = { 2185 "Binary files ", 2186 "Files ", 2187 NULL, 2188 }; 2189 int i; 2190 for (i = 0; binhdr[i]; i++) { 2191 int len = strlen(binhdr[i]); 2192 if (len < size - hd && 2193 !memcmp(binhdr[i], buffer + hd, len)) { 2194 state->linenr++; 2195 patch->is_binary = 1; 2196 patchsize = llen; 2197 break; 2198 } 2199 } 2200 } 2201 2202 /* Empty patch cannot be applied if it is a text patch 2203 * without metadata change. A binary patch appears 2204 * empty to us here. 2205 */ 2206 if ((state->apply || state->check) && 2207 (!patch->is_binary && !metadata_changes(patch))) { 2208 error(_("patch with only garbage at line %d"), state->linenr); 2209 return -128; 2210 } 2211 } 2212 2213 return offset + hdrsize + patchsize; 2214} 2215 2216static void reverse_patches(struct patch *p) 2217{ 2218 for (; p; p = p->next) { 2219 struct fragment *frag = p->fragments; 2220 2221 SWAP(p->new_name, p->old_name); 2222 if (p->new_mode || p->is_delete) 2223 SWAP(p->new_mode, p->old_mode); 2224 SWAP(p->is_new, p->is_delete); 2225 SWAP(p->lines_added, p->lines_deleted); 2226 SWAP(p->old_oid_prefix, p->new_oid_prefix); 2227 2228 for (; frag; frag = frag->next) { 2229 SWAP(frag->newpos, frag->oldpos); 2230 SWAP(frag->newlines, frag->oldlines); 2231 } 2232 } 2233} 2234 2235static const char pluses[] = 2236"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"; 2237static const char minuses[]= 2238"----------------------------------------------------------------------"; 2239 2240static void show_stats(struct apply_state *state, struct patch *patch) 2241{ 2242 struct strbuf qname = STRBUF_INIT; 2243 char *cp = patch->new_name ? patch->new_name : patch->old_name; 2244 int max, add, del; 2245 2246 quote_c_style(cp, &qname, NULL, 0); 2247 2248 /* 2249 * "scale" the filename 2250 */ 2251 max = state->max_len; 2252 if (max > 50) 2253 max = 50; 2254 2255 if (qname.len > max) { 2256 cp = strchr(qname.buf + qname.len + 3 - max, '/'); 2257 if (!cp) 2258 cp = qname.buf + qname.len + 3 - max; 2259 strbuf_splice(&qname, 0, cp - qname.buf, "...", 3); 2260 } 2261 2262 if (patch->is_binary) { 2263 printf(" %-*s | Bin\n", max, qname.buf); 2264 strbuf_release(&qname); 2265 return; 2266 } 2267 2268 printf(" %-*s |", max, qname.buf); 2269 strbuf_release(&qname); 2270 2271 /* 2272 * scale the add/delete 2273 */ 2274 max = max + state->max_change > 70 ? 70 - max : state->max_change; 2275 add = patch->lines_added; 2276 del = patch->lines_deleted; 2277 2278 if (state->max_change > 0) { 2279 int total = ((add + del) * max + state->max_change / 2) / state->max_change; 2280 add = (add * max + state->max_change / 2) / state->max_change; 2281 del = total - add; 2282 } 2283 printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted, 2284 add, pluses, del, minuses); 2285} 2286 2287static int read_old_data(struct stat *st, struct patch *patch, 2288 const char *path, struct strbuf *buf) 2289{ 2290 int conv_flags = patch->crlf_in_old ? 2291 CONV_EOL_KEEP_CRLF : CONV_EOL_RENORMALIZE; 2292 switch (st->st_mode & S_IFMT) { 2293 case S_IFLNK: 2294 if (strbuf_readlink(buf, path, st->st_size) < 0) 2295 return error(_("unable to read symlink %s"), path); 2296 return 0; 2297 case S_IFREG: 2298 if (strbuf_read_file(buf, path, st->st_size) != st->st_size) 2299 return error(_("unable to open or read %s"), path); 2300 /* 2301 * "git apply" without "--index/--cached" should never look 2302 * at the index; the target file may not have been added to 2303 * the index yet, and we may not even be in any Git repository. 2304 * Pass NULL to convert_to_git() to stress this; the function 2305 * should never look at the index when explicit crlf option 2306 * is given. 2307 */ 2308 convert_to_git(NULL, path, buf->buf, buf->len, buf, conv_flags); 2309 return 0; 2310 default: 2311 return -1; 2312 } 2313} 2314 2315/* 2316 * Update the preimage, and the common lines in postimage, 2317 * from buffer buf of length len. 2318 */ 2319static void update_pre_post_images(struct image *preimage, 2320 struct image *postimage, 2321 char *buf, size_t len) 2322{ 2323 struct image fixed_preimage = IMAGE_INIT; 2324 size_t insert_pos = 0; 2325 int i, ctx, reduced; 2326 const char *fixed; 2327 2328 /* 2329 * Update the preimage with whitespace fixes. Note that we 2330 * are not losing preimage->buf -- apply_one_fragment() will 2331 * free "oldlines". 2332 */ 2333 image_prepare(&fixed_preimage, buf, len, 1); 2334 for (i = 0; i < fixed_preimage.line_nr; i++) 2335 fixed_preimage.line[i].flag = preimage->line[i].flag; 2336 image_clear(preimage); 2337 *preimage = fixed_preimage; 2338 fixed = preimage->buf.buf; 2339 2340 /* 2341 * Adjust the common context lines in postimage. 2342 */ 2343 for (i = reduced = ctx = 0; i < postimage->line_nr; i++) { 2344 size_t l_len = postimage->line[i].len; 2345 2346 if (!(postimage->line[i].flag & LINE_COMMON)) { 2347 /* an added line -- no counterparts in preimage */ 2348 insert_pos += l_len; 2349 continue; 2350 } 2351 2352 /* and find the corresponding one in the fixed preimage */ 2353 while (ctx < preimage->line_nr && 2354 !(preimage->line[ctx].flag & LINE_COMMON)) { 2355 fixed += preimage->line[ctx].len; 2356 ctx++; 2357 } 2358 2359 /* 2360 * preimage is expected to run out, if the caller 2361 * fixed addition of trailing blank lines. 2362 */ 2363 if (preimage->line_nr <= ctx) { 2364 reduced++; 2365 continue; 2366 } 2367 2368 /* and copy it in, while fixing the line length */ 2369 l_len = preimage->line[ctx].len; 2370 strbuf_splice(&postimage->buf, insert_pos, postimage->line[i].len, 2371 fixed, l_len); 2372 insert_pos += l_len; 2373 fixed += l_len; 2374 postimage->line[i].len = l_len; 2375 ctx++; 2376 } 2377 2378 /* Fix the length of the whole thing */ 2379 postimage->line_nr -= reduced; 2380} 2381 2382/* 2383 * Compare lines s1 of length n1 and s2 of length n2, ignoring 2384 * whitespace difference. Returns 1 if they match, 0 otherwise 2385 */ 2386static int fuzzy_matchlines(const char *s1, size_t n1, 2387 const char *s2, size_t n2) 2388{ 2389 const char *end1 = s1 + n1; 2390 const char *end2 = s2 + n2; 2391 2392 /* ignore line endings */ 2393 while (s1 < end1 && (end1[-1] == '\r' || end1[-1] == '\n')) 2394 end1--; 2395 while (s2 < end2 && (end2[-1] == '\r' || end2[-1] == '\n')) 2396 end2--; 2397 2398 while (s1 < end1 && s2 < end2) { 2399 if (isspace(*s1)) { 2400 /* 2401 * Skip whitespace. We check on both buffers 2402 * because we don't want "a b" to match "ab". 2403 */ 2404 if (!isspace(*s2)) 2405 return 0; 2406 while (s1 < end1 && isspace(*s1)) 2407 s1++; 2408 while (s2 < end2 && isspace(*s2)) 2409 s2++; 2410 } else if (*s1++ != *s2++) 2411 return 0; 2412 } 2413 2414 /* If we reached the end on one side only, lines don't match. */ 2415 return s1 == end1 && s2 == end2; 2416} 2417 2418static int line_by_line_fuzzy_match(struct image *img, 2419 struct image *preimage, 2420 struct image *postimage, 2421 unsigned long current, 2422 int current_lno, 2423 int preimage_limit) 2424{ 2425 int i; 2426 size_t imgoff = 0; 2427 size_t preoff = 0; 2428 size_t extra_chars; 2429 char *buf; 2430 char *preimage_eof; 2431 char *preimage_end; 2432 struct strbuf fixed; 2433 char *fixed_buf; 2434 size_t fixed_len; 2435 2436 for (i = 0; i < preimage_limit; i++) { 2437 size_t prelen = preimage->line[i].len; 2438 size_t imglen = img->line[current_lno+i].len; 2439 2440 if (!fuzzy_matchlines(img->buf.buf + current + imgoff, imglen, 2441 preimage->buf.buf + preoff, prelen)) 2442 return 0; 2443 imgoff += imglen; 2444 preoff += prelen; 2445 } 2446 2447 /* 2448 * Ok, the preimage matches with whitespace fuzz. 2449 * 2450 * imgoff now holds the true length of the target that 2451 * matches the preimage before the end of the file. 2452 * 2453 * Count the number of characters in the preimage that fall 2454 * beyond the end of the file and make sure that all of them 2455 * are whitespace characters. (This can only happen if 2456 * we are removing blank lines at the end of the file.) 2457 */ 2458 buf = preimage_eof = preimage->buf.buf + preoff; 2459 for ( ; i < preimage->line_nr; i++) 2460 preoff += preimage->line[i].len; 2461 preimage_end = preimage->buf.buf + preoff; 2462 for ( ; buf < preimage_end; buf++) 2463 if (!isspace(*buf)) 2464 return 0; 2465 2466 /* 2467 * Update the preimage and the common postimage context 2468 * lines to use the same whitespace as the target. 2469 * If whitespace is missing in the target (i.e. 2470 * if the preimage extends beyond the end of the file), 2471 * use the whitespace from the preimage. 2472 */ 2473 extra_chars = preimage_end - preimage_eof; 2474 strbuf_init(&fixed, imgoff + extra_chars); 2475 strbuf_add(&fixed, img->buf.buf + current, imgoff); 2476 strbuf_add(&fixed, preimage_eof, extra_chars); 2477 fixed_buf = strbuf_detach(&fixed, &fixed_len); 2478 update_pre_post_images(preimage, postimage, 2479 fixed_buf, fixed_len); 2480 return 1; 2481} 2482 2483static int match_fragment(struct apply_state *state, 2484 struct image *img, 2485 struct image *preimage, 2486 struct image *postimage, 2487 unsigned long current, 2488 int current_lno, 2489 unsigned ws_rule, 2490 int match_beginning, int match_end) 2491{ 2492 int i; 2493 const char *orig, *target; 2494 struct strbuf fixed = STRBUF_INIT; 2495 char *fixed_buf; 2496 size_t fixed_len; 2497 int preimage_limit; 2498 int ret; 2499 2500 if (preimage->line_nr + current_lno <= img->line_nr) { 2501 /* 2502 * The hunk falls within the boundaries of img. 2503 */ 2504 preimage_limit = preimage->line_nr; 2505 if (match_end && (preimage->line_nr + current_lno != img->line_nr)) { 2506 ret = 0; 2507 goto out; 2508 } 2509 } else if (state->ws_error_action == correct_ws_error && 2510 (ws_rule & WS_BLANK_AT_EOF)) { 2511 /* 2512 * This hunk extends beyond the end of img, and we are 2513 * removing blank lines at the end of the file. This 2514 * many lines from the beginning of the preimage must 2515 * match with img, and the remainder of the preimage 2516 * must be blank. 2517 */ 2518 preimage_limit = img->line_nr - current_lno; 2519 } else { 2520 /* 2521 * The hunk extends beyond the end of the img and 2522 * we are not removing blanks at the end, so we 2523 * should reject the hunk at this position. 2524 */ 2525 ret = 0; 2526 goto out; 2527 } 2528 2529 if (match_beginning && current_lno) { 2530 ret = 0; 2531 goto out; 2532 } 2533 2534 /* Quick hash check */ 2535 for (i = 0; i < preimage_limit; i++) { 2536 if ((img->line[current_lno + i].flag & LINE_PATCHED) || 2537 (preimage->line[i].hash != img->line[current_lno + i].hash)) { 2538 ret = 0; 2539 goto out; 2540 } 2541 } 2542 2543 if (preimage_limit == preimage->line_nr) { 2544 /* 2545 * Do we have an exact match? If we were told to match 2546 * at the end, size must be exactly at current+fragsize, 2547 * otherwise current+fragsize must be still within the preimage, 2548 * and either case, the old piece should match the preimage 2549 * exactly. 2550 */ 2551 if ((match_end 2552 ? (current + preimage->buf.len == img->buf.len) 2553 : (current + preimage->buf.len <= img->buf.len)) && 2554 !memcmp(img->buf.buf + current, preimage->buf.buf, preimage->buf.len)) { 2555 ret = 1; 2556 goto out; 2557 } 2558 } else { 2559 /* 2560 * The preimage extends beyond the end of img, so 2561 * there cannot be an exact match. 2562 * 2563 * There must be one non-blank context line that match 2564 * a line before the end of img. 2565 */ 2566 const char *buf, *buf_end; 2567 2568 buf = preimage->buf.buf; 2569 buf_end = buf; 2570 for (i = 0; i < preimage_limit; i++) 2571 buf_end += preimage->line[i].len; 2572 2573 for ( ; buf < buf_end; buf++) 2574 if (!isspace(*buf)) 2575 break; 2576 if (buf == buf_end) { 2577 ret = 0; 2578 goto out; 2579 } 2580 } 2581 2582 /* 2583 * No exact match. If we are ignoring whitespace, run a line-by-line 2584 * fuzzy matching. We collect all the line length information because 2585 * we need it to adjust whitespace if we match. 2586 */ 2587 if (state->ws_ignore_action == ignore_ws_change) { 2588 ret = line_by_line_fuzzy_match(img, preimage, postimage, 2589 current, current_lno, preimage_limit); 2590 goto out; 2591 } 2592 2593 if (state->ws_error_action != correct_ws_error) { 2594 ret = 0; 2595 goto out; 2596 } 2597 2598 /* 2599 * The hunk does not apply byte-by-byte, but the hash says 2600 * it might with whitespace fuzz. We weren't asked to 2601 * ignore whitespace, we were asked to correct whitespace 2602 * errors, so let's try matching after whitespace correction. 2603 * 2604 * While checking the preimage against the target, whitespace 2605 * errors in both fixed, we count how large the corresponding 2606 * postimage needs to be. The postimage prepared by 2607 * apply_one_fragment() has whitespace errors fixed on added 2608 * lines already, but the common lines were propagated as-is, 2609 * which may become longer when their whitespace errors are 2610 * fixed. 2611 */ 2612 2613 /* 2614 * The preimage may extend beyond the end of the file, 2615 * but in this loop we will only handle the part of the 2616 * preimage that falls within the file. 2617 */ 2618 strbuf_grow(&fixed, preimage->buf.len + 1); 2619 orig = preimage->buf.buf; 2620 target = img->buf.buf + current; 2621 for (i = 0; i < preimage_limit; i++) { 2622 size_t oldlen = preimage->line[i].len; 2623 size_t tgtlen = img->line[current_lno + i].len; 2624 size_t fixstart = fixed.len; 2625 struct strbuf tgtfix; 2626 int match; 2627 2628 /* Try fixing the line in the preimage */ 2629 ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL); 2630 2631 /* Try fixing the line in the target */ 2632 strbuf_init(&tgtfix, tgtlen); 2633 ws_fix_copy(&tgtfix, target, tgtlen, ws_rule, NULL); 2634 2635 /* 2636 * If they match, either the preimage was based on 2637 * a version before our tree fixed whitespace breakage, 2638 * or we are lacking a whitespace-fix patch the tree 2639 * the preimage was based on already had (i.e. target 2640 * has whitespace breakage, the preimage doesn't). 2641 * In either case, we are fixing the whitespace breakages 2642 * so we might as well take the fix together with their 2643 * real change. 2644 */ 2645 match = (tgtfix.len == fixed.len - fixstart && 2646 !memcmp(tgtfix.buf, fixed.buf + fixstart, 2647 fixed.len - fixstart)); 2648 2649 strbuf_release(&tgtfix); 2650 if (!match) { 2651 ret = 0; 2652 goto out; 2653 } 2654 2655 orig += oldlen; 2656 target += tgtlen; 2657 } 2658 2659 2660 /* 2661 * Now handle the lines in the preimage that falls beyond the 2662 * end of the file (if any). They will only match if they are 2663 * empty or only contain whitespace (if WS_BLANK_AT_EOL is 2664 * false). 2665 */ 2666 for ( ; i < preimage->line_nr; i++) { 2667 size_t fixstart = fixed.len; /* start of the fixed preimage */ 2668 size_t oldlen = preimage->line[i].len; 2669 int j; 2670 2671 /* Try fixing the line in the preimage */ 2672 ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL); 2673 2674 for (j = fixstart; j < fixed.len; j++) { 2675 if (!isspace(fixed.buf[j])) { 2676 ret = 0; 2677 goto out; 2678 } 2679 } 2680 2681 2682 orig += oldlen; 2683 } 2684 2685 /* 2686 * Yes, the preimage is based on an older version that still 2687 * has whitespace breakages unfixed, and fixing them makes the 2688 * hunk match. Update the context lines in the postimage. 2689 */ 2690 fixed_buf = strbuf_detach(&fixed, &fixed_len); 2691 update_pre_post_images(preimage, postimage, 2692 fixed_buf, fixed_len); 2693 2694 ret = 1; 2695 2696out: 2697 strbuf_release(&fixed); 2698 return ret; 2699} 2700 2701static int find_pos(struct apply_state *state, 2702 struct image *img, 2703 struct image *preimage, 2704 struct image *postimage, 2705 int line, 2706 unsigned ws_rule, 2707 int match_beginning, int match_end) 2708{ 2709 int i; 2710 unsigned long backwards, forwards, current; 2711 int backwards_lno, forwards_lno, current_lno; 2712 2713 /* 2714 * When running with --allow-overlap, it is possible that a hunk is 2715 * seen that pretends to start at the beginning (but no longer does), 2716 * and that *still* needs to match the end. So trust `match_end` more 2717 * than `match_beginning`. 2718 */ 2719 if (state->allow_overlap && match_beginning && match_end && 2720 img->line_nr - preimage->line_nr != 0) 2721 match_beginning = 0; 2722 2723 /* 2724 * If match_beginning or match_end is specified, there is no 2725 * point starting from a wrong line that will never match and 2726 * wander around and wait for a match at the specified end. 2727 */ 2728 if (match_beginning) 2729 line = 0; 2730 else if (match_end) 2731 line = img->line_nr - preimage->line_nr; 2732 2733 /* 2734 * Because the comparison is unsigned, the following test 2735 * will also take care of a negative line number that can 2736 * result when match_end and preimage is larger than the target. 2737 */ 2738 if ((size_t) line > img->line_nr) 2739 line = img->line_nr; 2740 2741 current = 0; 2742 for (i = 0; i < line; i++) 2743 current += img->line[i].len; 2744 2745 /* 2746 * There's probably some smart way to do this, but I'll leave 2747 * that to the smart and beautiful people. I'm simple and stupid. 2748 */ 2749 backwards = current; 2750 backwards_lno = line; 2751 forwards = current; 2752 forwards_lno = line; 2753 current_lno = line; 2754 2755 for (i = 0; ; i++) { 2756 if (match_fragment(state, img, preimage, postimage, 2757 current, current_lno, ws_rule, 2758 match_beginning, match_end)) 2759 return current_lno; 2760 2761 again: 2762 if (backwards_lno == 0 && forwards_lno == img->line_nr) 2763 break; 2764 2765 if (i & 1) { 2766 if (backwards_lno == 0) { 2767 i++; 2768 goto again; 2769 } 2770 backwards_lno--; 2771 backwards -= img->line[backwards_lno].len; 2772 current = backwards; 2773 current_lno = backwards_lno; 2774 } else { 2775 if (forwards_lno == img->line_nr) { 2776 i++; 2777 goto again; 2778 } 2779 forwards += img->line[forwards_lno].len; 2780 forwards_lno++; 2781 current = forwards; 2782 current_lno = forwards_lno; 2783 } 2784 2785 } 2786 return -1; 2787} 2788 2789/* 2790 * The change from "preimage" and "postimage" has been found to 2791 * apply at applied_pos (counts in line numbers) in "img". 2792 * Update "img" to remove "preimage" and replace it with "postimage". 2793 */ 2794static void update_image(struct apply_state *state, 2795 struct image *img, 2796 int applied_pos, 2797 struct image *preimage, 2798 struct image *postimage) 2799{ 2800 /* 2801 * remove the copy of preimage at offset in img 2802 * and replace it with postimage 2803 */ 2804 int i, nr; 2805 size_t remove_count, insert_count, applied_at = 0; 2806 size_t result_alloc; 2807 char *result; 2808 int preimage_limit; 2809 2810 /* 2811 * If we are removing blank lines at the end of img, 2812 * the preimage may extend beyond the end. 2813 * If that is the case, we must be careful only to 2814 * remove the part of the preimage that falls within 2815 * the boundaries of img. Initialize preimage_limit 2816 * to the number of lines in the preimage that falls 2817 * within the boundaries. 2818 */ 2819 preimage_limit = preimage->line_nr; 2820 if (preimage_limit > img->line_nr - applied_pos) 2821 preimage_limit = img->line_nr - applied_pos; 2822 2823 for (i = 0; i < applied_pos; i++) 2824 applied_at += img->line[i].len; 2825 2826 remove_count = 0; 2827 for (i = 0; i < preimage_limit; i++) 2828 remove_count += img->line[applied_pos + i].len; 2829 insert_count = postimage->buf.len; 2830 2831 /* Adjust the contents */ 2832 result_alloc = st_add3(st_sub(img->buf.len, remove_count), insert_count, 1); 2833 result = xmalloc(result_alloc); 2834 memcpy(result, img->buf.buf, applied_at); 2835 memcpy(result + applied_at, postimage->buf.buf, postimage->buf.len); 2836 memcpy(result + applied_at + postimage->buf.len, 2837 img->buf.buf + (applied_at + remove_count), 2838 img->buf.len - (applied_at + remove_count)); 2839 strbuf_attach(&img->buf, result, postimage->buf.len + img->buf.len - remove_count, 2840 result_alloc); 2841 2842 /* Adjust the line table */ 2843 nr = img->line_nr + postimage->line_nr - preimage_limit; 2844 if (preimage_limit < postimage->line_nr) 2845 /* 2846 * NOTE: this knows that we never call image_remove_first_line() 2847 * on anything other than pre/post image. 2848 */ 2849 REALLOC_ARRAY(img->line, nr); 2850 if (preimage_limit != postimage->line_nr) 2851 MOVE_ARRAY(img->line + applied_pos + postimage->line_nr, 2852 img->line + applied_pos + preimage_limit, 2853 img->line_nr - (applied_pos + preimage_limit)); 2854 COPY_ARRAY(img->line + applied_pos, postimage->line, postimage->line_nr); 2855 if (!state->allow_overlap) 2856 for (i = 0; i < postimage->line_nr; i++) 2857 img->line[applied_pos + i].flag |= LINE_PATCHED; 2858 img->line_nr = nr; 2859} 2860 2861/* 2862 * Use the patch-hunk text in "frag" to prepare two images (preimage and 2863 * postimage) for the hunk. Find lines that match "preimage" in "img" and 2864 * replace the part of "img" with "postimage" text. 2865 */ 2866static int apply_one_fragment(struct apply_state *state, 2867 struct image *img, struct fragment *frag, 2868 int inaccurate_eof, unsigned ws_rule, 2869 int nth_fragment) 2870{ 2871 int match_beginning, match_end; 2872 const char *patch = frag->patch; 2873 int size = frag->size; 2874 char *old, *oldlines; 2875 struct strbuf newlines; 2876 int new_blank_lines_at_end = 0; 2877 int found_new_blank_lines_at_end = 0; 2878 int hunk_linenr = frag->linenr; 2879 unsigned long leading, trailing; 2880 int pos, applied_pos; 2881 struct image preimage = IMAGE_INIT; 2882 struct image postimage = IMAGE_INIT; 2883 2884 oldlines = xmalloc(size); 2885 strbuf_init(&newlines, size); 2886 2887 old = oldlines; 2888 while (size > 0) { 2889 char first; 2890 int len = linelen(patch, size); 2891 int plen; 2892 int added_blank_line = 0; 2893 int is_blank_context = 0; 2894 size_t start; 2895 2896 if (!len) 2897 break; 2898 2899 /* 2900 * "plen" is how much of the line we should use for 2901 * the actual patch data. Normally we just remove the 2902 * first character on the line, but if the line is 2903 * followed by "\ No newline", then we also remove the 2904 * last one (which is the newline, of course). 2905 */ 2906 plen = len - 1; 2907 if (len < size && patch[len] == '\\') 2908 plen--; 2909 first = *patch; 2910 if (state->apply_in_reverse) { 2911 if (first == '-') 2912 first = '+'; 2913 else if (first == '+') 2914 first = '-'; 2915 } 2916 2917 switch (first) { 2918 case '\n': 2919 /* Newer GNU diff, empty context line */ 2920 if (plen < 0) 2921 /* ... followed by '\No newline'; nothing */ 2922 break; 2923 *old++ = '\n'; 2924 strbuf_addch(&newlines, '\n'); 2925 image_add_line(&preimage, "\n", 1, LINE_COMMON); 2926 image_add_line(&postimage, "\n", 1, LINE_COMMON); 2927 is_blank_context = 1; 2928 break; 2929 case ' ': 2930 if (plen && (ws_rule & WS_BLANK_AT_EOF) && 2931 ws_blank_line(patch + 1, plen)) 2932 is_blank_context = 1; 2933 /* fallthrough */ 2934 case '-': 2935 memcpy(old, patch + 1, plen); 2936 image_add_line(&preimage, old, plen, 2937 (first == ' ' ? LINE_COMMON : 0)); 2938 old += plen; 2939 if (first == '-') 2940 break; 2941 /* fallthrough */ 2942 case '+': 2943 /* --no-add does not add new lines */ 2944 if (first == '+' && state->no_add) 2945 break; 2946 2947 start = newlines.len; 2948 if (first != '+' || 2949 !state->whitespace_error || 2950 state->ws_error_action != correct_ws_error) { 2951 strbuf_add(&newlines, patch + 1, plen); 2952 } 2953 else { 2954 ws_fix_copy(&newlines, patch + 1, plen, ws_rule, &state->applied_after_fixing_ws); 2955 } 2956 image_add_line(&postimage, newlines.buf + start, newlines.len - start, 2957 (first == '+' ? 0 : LINE_COMMON)); 2958 if (first == '+' && 2959 (ws_rule & WS_BLANK_AT_EOF) && 2960 ws_blank_line(patch + 1, plen)) 2961 added_blank_line = 1; 2962 break; 2963 case '@': case '\\': 2964 /* Ignore it, we already handled it */ 2965 break; 2966 default: 2967 if (state->apply_verbosity > verbosity_normal) 2968 error(_("invalid start of line: '%c'"), first); 2969 applied_pos = -1; 2970 goto out; 2971 } 2972 if (added_blank_line) { 2973 if (!new_blank_lines_at_end) 2974 found_new_blank_lines_at_end = hunk_linenr; 2975 new_blank_lines_at_end++; 2976 } 2977 else if (is_blank_context) 2978 ; 2979 else 2980 new_blank_lines_at_end = 0; 2981 patch += len; 2982 size -= len; 2983 hunk_linenr++; 2984 } 2985 if (inaccurate_eof && 2986 old > oldlines && old[-1] == '\n' && 2987 newlines.len > 0 && newlines.buf[newlines.len - 1] == '\n') { 2988 old--; 2989 strbuf_setlen(&newlines, newlines.len - 1); 2990 preimage.line[preimage.line_nr - 1].len--; 2991 postimage.line[postimage.line_nr - 1].len--; 2992 } 2993 2994 leading = frag->leading; 2995 trailing = frag->trailing; 2996 2997 /* 2998 * A hunk to change lines at the beginning would begin with 2999 * @@ -1,L +N,M @@ 3000 * but we need to be careful. -U0 that inserts before the second 3001 * line also has this pattern. 3002 * 3003 * And a hunk to add to an empty file would begin with 3004 * @@ -0,0 +N,M @@ 3005 * 3006 * In other words, a hunk that is (frag->oldpos <= 1) with or 3007 * without leading context must match at the beginning. 3008 */ 3009 match_beginning = (!frag->oldpos || 3010 (frag->oldpos == 1 && !state->unidiff_zero)); 3011 3012 /* 3013 * A hunk without trailing lines must match at the end. 3014 * However, we simply cannot tell if a hunk must match end 3015 * from the lack of trailing lines if the patch was generated 3016 * with unidiff without any context. 3017 */ 3018 match_end = !state->unidiff_zero && !trailing; 3019 3020 pos = frag->newpos ? (frag->newpos - 1) : 0; 3021 strbuf_add(&preimage.buf, oldlines, old - oldlines); 3022 strbuf_swap(&postimage.buf, &newlines); 3023 3024 for (;;) { 3025 3026 applied_pos = find_pos(state, img, &preimage, &postimage, pos, 3027 ws_rule, match_beginning, match_end); 3028 3029 if (applied_pos >= 0) 3030 break; 3031 3032 /* Am I at my context limits? */ 3033 if ((leading <= state->p_context) && (trailing <= state->p_context)) 3034 break; 3035 if (match_beginning || match_end) { 3036 match_beginning = match_end = 0; 3037 continue; 3038 } 3039 3040 /* 3041 * Reduce the number of context lines; reduce both 3042 * leading and trailing if they are equal otherwise 3043 * just reduce the larger context. 3044 */ 3045 if (leading >= trailing) { 3046 image_remove_first_line(&preimage); 3047 image_remove_first_line(&postimage); 3048 pos--; 3049 leading--; 3050 } 3051 if (trailing > leading) { 3052 image_remove_last_line(&preimage); 3053 image_remove_last_line(&postimage); 3054 trailing--; 3055 } 3056 } 3057 3058 if (applied_pos >= 0) { 3059 if (new_blank_lines_at_end && 3060 preimage.line_nr + applied_pos >= img->line_nr && 3061 (ws_rule & WS_BLANK_AT_EOF) && 3062 state->ws_error_action != nowarn_ws_error) { 3063 record_ws_error(state, WS_BLANK_AT_EOF, "+", 1, 3064 found_new_blank_lines_at_end); 3065 if (state->ws_error_action == correct_ws_error) { 3066 while (new_blank_lines_at_end--) 3067 image_remove_last_line(&postimage); 3068 } 3069 /* 3070 * We would want to prevent write_out_results() 3071 * from taking place in apply_patch() that follows 3072 * the callchain led us here, which is: 3073 * apply_patch->check_patch_list->check_patch-> 3074 * apply_data->apply_fragments->apply_one_fragment 3075 */ 3076 if (state->ws_error_action == die_on_ws_error) 3077 state->apply = 0; 3078 } 3079 3080 if (state->apply_verbosity > verbosity_normal && applied_pos != pos) { 3081 int offset = applied_pos - pos; 3082 if (state->apply_in_reverse) 3083 offset = 0 - offset; 3084 fprintf_ln(stderr, 3085 Q_("Hunk #%d succeeded at %d (offset %d line).", 3086 "Hunk #%d succeeded at %d (offset %d lines).", 3087 offset), 3088 nth_fragment, applied_pos + 1, offset); 3089 } 3090 3091 /* 3092 * Warn if it was necessary to reduce the number 3093 * of context lines. 3094 */ 3095 if ((leading != frag->leading || 3096 trailing != frag->trailing) && state->apply_verbosity > verbosity_silent) 3097 fprintf_ln(stderr, _("Context reduced to (%ld/%ld)" 3098 " to apply fragment at %d"), 3099 leading, trailing, applied_pos+1); 3100 update_image(state, img, applied_pos, &preimage, &postimage); 3101 } else { 3102 if (state->apply_verbosity > verbosity_normal) 3103 error(_("while searching for:\n%.*s"), 3104 (int)(old - oldlines), oldlines); 3105 } 3106 3107out: 3108 free(oldlines); 3109 strbuf_release(&newlines); 3110 image_clear(&preimage); 3111 image_clear(&postimage); 3112 3113 return (applied_pos < 0); 3114} 3115 3116static int apply_binary_fragment(struct apply_state *state, 3117 struct image *img, 3118 struct patch *patch) 3119{ 3120 struct fragment *fragment = patch->fragments; 3121 unsigned long len; 3122 void *dst; 3123 3124 if (!fragment) 3125 return error(_("missing binary patch data for '%s'"), 3126 patch->new_name ? 3127 patch->new_name : 3128 patch->old_name); 3129 3130 /* Binary patch is irreversible without the optional second hunk */ 3131 if (state->apply_in_reverse) { 3132 if (!fragment->next) 3133 return error(_("cannot reverse-apply a binary patch " 3134 "without the reverse hunk to '%s'"), 3135 patch->new_name 3136 ? patch->new_name : patch->old_name); 3137 fragment = fragment->next; 3138 } 3139 switch (fragment->binary_patch_method) { 3140 case BINARY_DELTA_DEFLATED: 3141 dst = patch_delta(img->buf.buf, img->buf.len, fragment->patch, 3142 fragment->size, &len); 3143 if (!dst) 3144 return -1; 3145 image_clear(img); 3146 strbuf_attach(&img->buf, dst, len, len + 1); 3147 return 0; 3148 case BINARY_LITERAL_DEFLATED: 3149 image_clear(img); 3150 strbuf_add(&img->buf, fragment->patch, fragment->size); 3151 return 0; 3152 } 3153 return -1; 3154} 3155 3156/* 3157 * Replace "img" with the result of applying the binary patch. 3158 * The binary patch data itself in patch->fragment is still kept 3159 * but the preimage prepared by the caller in "img" is freed here 3160 * or in the helper function apply_binary_fragment() this calls. 3161 */ 3162static int apply_binary(struct apply_state *state, 3163 struct image *img, 3164 struct patch *patch) 3165{ 3166 const char *name = patch->old_name ? patch->old_name : patch->new_name; 3167 struct object_id oid; 3168 const unsigned hexsz = the_hash_algo->hexsz; 3169 3170 /* 3171 * For safety, we require patch index line to contain 3172 * full hex textual object ID for old and new, at least for now. 3173 */ 3174 if (strlen(patch->old_oid_prefix) != hexsz || 3175 strlen(patch->new_oid_prefix) != hexsz || 3176 get_oid_hex(patch->old_oid_prefix, &oid) || 3177 get_oid_hex(patch->new_oid_prefix, &oid)) 3178 return error(_("cannot apply binary patch to '%s' " 3179 "without full index line"), name); 3180 3181 if (patch->old_name) { 3182 /* 3183 * See if the old one matches what the patch 3184 * applies to. 3185 */ 3186 hash_object_file(the_hash_algo, img->buf.buf, img->buf.len, 3187 OBJ_BLOB, &oid); 3188 if (strcmp(oid_to_hex(&oid), patch->old_oid_prefix)) 3189 return error(_("the patch applies to '%s' (%s), " 3190 "which does not match the " 3191 "current contents."), 3192 name, oid_to_hex(&oid)); 3193 } 3194 else { 3195 /* Otherwise, the old one must be empty. */ 3196 if (img->buf.len) 3197 return error(_("the patch applies to an empty " 3198 "'%s' but it is not empty"), name); 3199 } 3200 3201 get_oid_hex(patch->new_oid_prefix, &oid); 3202 if (is_null_oid(&oid)) { 3203 image_clear(img); 3204 return 0; /* deletion patch */ 3205 } 3206 3207 if (odb_has_object(the_repository->objects, &oid, 0)) { 3208 /* We already have the postimage */ 3209 enum object_type type; 3210 unsigned long size; 3211 char *result; 3212 3213 result = odb_read_object(the_repository->objects, &oid, 3214 &type, &size); 3215 if (!result) 3216 return error(_("the necessary postimage %s for " 3217 "'%s' cannot be read"), 3218 patch->new_oid_prefix, name); 3219 image_clear(img); 3220 strbuf_attach(&img->buf, result, size, size + 1); 3221 } else { 3222 /* 3223 * We have verified buf matches the preimage; 3224 * apply the patch data to it, which is stored 3225 * in the patch->fragments->{patch,size}. 3226 */ 3227 if (apply_binary_fragment(state, img, patch)) 3228 return error(_("binary patch does not apply to '%s'"), 3229 name); 3230 3231 /* verify that the result matches */ 3232 hash_object_file(the_hash_algo, img->buf.buf, img->buf.len, OBJ_BLOB, 3233 &oid); 3234 if (strcmp(oid_to_hex(&oid), patch->new_oid_prefix)) 3235 return error(_("binary patch to '%s' creates incorrect result (expecting %s, got %s)"), 3236 name, patch->new_oid_prefix, oid_to_hex(&oid)); 3237 } 3238 3239 return 0; 3240} 3241 3242static int apply_fragments(struct apply_state *state, struct image *img, struct patch *patch) 3243{ 3244 struct fragment *frag = patch->fragments; 3245 const char *name = patch->old_name ? patch->old_name : patch->new_name; 3246 unsigned ws_rule = patch->ws_rule; 3247 unsigned inaccurate_eof = patch->inaccurate_eof; 3248 int nth = 0; 3249 3250 if (patch->is_binary) 3251 return apply_binary(state, img, patch); 3252 3253 while (frag) { 3254 nth++; 3255 if (apply_one_fragment(state, img, frag, inaccurate_eof, ws_rule, nth)) { 3256 error(_("patch failed: %s:%ld"), name, frag->oldpos); 3257 if (!state->apply_with_reject) 3258 return -1; 3259 frag->rejected = 1; 3260 } 3261 frag = frag->next; 3262 } 3263 return 0; 3264} 3265 3266static int read_blob_object(struct strbuf *buf, const struct object_id *oid, unsigned mode) 3267{ 3268 if (S_ISGITLINK(mode)) { 3269 strbuf_grow(buf, 100); 3270 strbuf_addf(buf, "Subproject commit %s\n", oid_to_hex(oid)); 3271 } else { 3272 enum object_type type; 3273 unsigned long sz; 3274 char *result; 3275 3276 result = odb_read_object(the_repository->objects, oid, 3277 &type, &sz); 3278 if (!result) 3279 return -1; 3280 /* XXX read_sha1_file NUL-terminates */ 3281 strbuf_attach(buf, result, sz, sz + 1); 3282 } 3283 return 0; 3284} 3285 3286static int read_file_or_gitlink(const struct cache_entry *ce, struct strbuf *buf) 3287{ 3288 if (!ce) 3289 return 0; 3290 return read_blob_object(buf, &ce->oid, ce->ce_mode); 3291} 3292 3293static struct patch *in_fn_table(struct apply_state *state, const char *name) 3294{ 3295 struct string_list_item *item; 3296 3297 if (!name) 3298 return NULL; 3299 3300 item = string_list_lookup(&state->fn_table, name); 3301 if (item) 3302 return (struct patch *)item->util; 3303 3304 return NULL; 3305} 3306 3307/* 3308 * item->util in the filename table records the status of the path. 3309 * Usually it points at a patch (whose result records the contents 3310 * of it after applying it), but it could be PATH_WAS_DELETED for a 3311 * path that a previously applied patch has already removed, or 3312 * PATH_TO_BE_DELETED for a path that a later patch would remove. 3313 * 3314 * The latter is needed to deal with a case where two paths A and B 3315 * are swapped by first renaming A to B and then renaming B to A; 3316 * moving A to B should not be prevented due to presence of B as we 3317 * will remove it in a later patch. 3318 */ 3319#define PATH_TO_BE_DELETED ((struct patch *) -2) 3320#define PATH_WAS_DELETED ((struct patch *) -1) 3321 3322static int to_be_deleted(struct patch *patch) 3323{ 3324 return patch == PATH_TO_BE_DELETED; 3325} 3326 3327static int was_deleted(struct patch *patch) 3328{ 3329 return patch == PATH_WAS_DELETED; 3330} 3331 3332static void add_to_fn_table(struct apply_state *state, struct patch *patch) 3333{ 3334 struct string_list_item *item; 3335 3336 /* 3337 * Always add new_name unless patch is a deletion 3338 * This should cover the cases for normal diffs, 3339 * file creations and copies 3340 */ 3341 if (patch->new_name) { 3342 item = string_list_insert(&state->fn_table, patch->new_name); 3343 item->util = patch; 3344 } 3345 3346 /* 3347 * store a failure on rename/deletion cases because 3348 * later chunks shouldn't patch old names 3349 */ 3350 if ((patch->new_name == NULL) || (patch->is_rename)) { 3351 item = string_list_insert(&state->fn_table, patch->old_name); 3352 item->util = PATH_WAS_DELETED; 3353 } 3354} 3355 3356static void prepare_fn_table(struct apply_state *state, struct patch *patch) 3357{ 3358 /* 3359 * store information about incoming file deletion 3360 */ 3361 while (patch) { 3362 if ((patch->new_name == NULL) || (patch->is_rename)) { 3363 struct string_list_item *item; 3364 item = string_list_insert(&state->fn_table, patch->old_name); 3365 item->util = PATH_TO_BE_DELETED; 3366 } 3367 patch = patch->next; 3368 } 3369} 3370 3371static int checkout_target(struct index_state *istate, 3372 struct cache_entry *ce, struct stat *st) 3373{ 3374 struct checkout costate = CHECKOUT_INIT; 3375 3376 costate.refresh_cache = 1; 3377 costate.istate = istate; 3378 if (checkout_entry(ce, &costate, NULL, NULL) || 3379 lstat(ce->name, st)) 3380 return error(_("cannot checkout %s"), ce->name); 3381 return 0; 3382} 3383 3384static struct patch *previous_patch(struct apply_state *state, 3385 struct patch *patch, 3386 int *gone) 3387{ 3388 struct patch *previous; 3389 3390 *gone = 0; 3391 if (patch->is_copy || patch->is_rename) 3392 return NULL; /* "git" patches do not depend on the order */ 3393 3394 previous = in_fn_table(state, patch->old_name); 3395 if (!previous) 3396 return NULL; 3397 3398 if (to_be_deleted(previous)) 3399 return NULL; /* the deletion hasn't happened yet */ 3400 3401 if (was_deleted(previous)) 3402 *gone = 1; 3403 3404 return previous; 3405} 3406 3407static int verify_index_match(struct apply_state *state, 3408 const struct cache_entry *ce, 3409 struct stat *st) 3410{ 3411 if (S_ISGITLINK(ce->ce_mode)) { 3412 if (!S_ISDIR(st->st_mode)) 3413 return -1; 3414 return 0; 3415 } 3416 return ie_match_stat(state->repo->index, ce, st, 3417 CE_MATCH_IGNORE_VALID | CE_MATCH_IGNORE_SKIP_WORKTREE); 3418} 3419 3420#define SUBMODULE_PATCH_WITHOUT_INDEX 1 3421 3422static int load_patch_target(struct apply_state *state, 3423 struct strbuf *buf, 3424 const struct cache_entry *ce, 3425 struct stat *st, 3426 struct patch *patch, 3427 const char *name, 3428 unsigned expected_mode) 3429{ 3430 if (state->cached || state->check_index) { 3431 if (read_file_or_gitlink(ce, buf)) 3432 return error(_("failed to read %s"), name); 3433 } else if (name) { 3434 if (S_ISGITLINK(expected_mode)) { 3435 if (ce) 3436 return read_file_or_gitlink(ce, buf); 3437 else 3438 return SUBMODULE_PATCH_WITHOUT_INDEX; 3439 } else if (has_symlink_leading_path(name, strlen(name))) { 3440 return error(_("reading from '%s' beyond a symbolic link"), name); 3441 } else { 3442 if (read_old_data(st, patch, name, buf)) 3443 return error(_("failed to read %s"), name); 3444 } 3445 } 3446 return 0; 3447} 3448 3449/* 3450 * We are about to apply "patch"; populate the "image" with the 3451 * current version we have, from the working tree or from the index, 3452 * depending on the situation e.g. --cached/--index. If we are 3453 * applying a non-git patch that incrementally updates the tree, 3454 * we read from the result of a previous diff. 3455 */ 3456static int load_preimage(struct apply_state *state, 3457 struct image *image, 3458 struct patch *patch, struct stat *st, 3459 const struct cache_entry *ce) 3460{ 3461 struct strbuf buf = STRBUF_INIT; 3462 size_t len; 3463 char *img; 3464 struct patch *previous; 3465 int status; 3466 3467 previous = previous_patch(state, patch, &status); 3468 if (status) 3469 return error(_("path %s has been renamed/deleted"), 3470 patch->old_name); 3471 if (previous) { 3472 /* We have a patched copy in memory; use that. */ 3473 strbuf_add(&buf, previous->result, previous->resultsize); 3474 } else { 3475 status = load_patch_target(state, &buf, ce, st, patch, 3476 patch->old_name, patch->old_mode); 3477 if (status < 0) 3478 return status; 3479 else if (status == SUBMODULE_PATCH_WITHOUT_INDEX) { 3480 /* 3481 * There is no way to apply subproject 3482 * patch without looking at the index. 3483 * NEEDSWORK: shouldn't this be flagged 3484 * as an error??? 3485 */ 3486 free_fragment_list(patch->fragments); 3487 patch->fragments = NULL; 3488 } else if (status) { 3489 return error(_("failed to read %s"), patch->old_name); 3490 } 3491 } 3492 3493 img = strbuf_detach(&buf, &len); 3494 image_prepare(image, img, len, !patch->is_binary); 3495 return 0; 3496} 3497 3498static int resolve_to(struct image *image, const struct object_id *result_id) 3499{ 3500 unsigned long size; 3501 enum object_type type; 3502 char *data; 3503 3504 image_clear(image); 3505 3506 data = odb_read_object(the_repository->objects, result_id, &type, &size); 3507 if (!data || type != OBJ_BLOB) 3508 die("unable to read blob object %s", oid_to_hex(result_id)); 3509 strbuf_attach(&image->buf, data, size, size + 1); 3510 3511 return 0; 3512} 3513 3514static int three_way_merge(struct apply_state *state, 3515 struct image *image, 3516 char *path, 3517 const struct object_id *base, 3518 const struct object_id *ours, 3519 const struct object_id *theirs) 3520{ 3521 mmfile_t base_file, our_file, their_file; 3522 struct ll_merge_options merge_opts = LL_MERGE_OPTIONS_INIT; 3523 mmbuffer_t result = { NULL }; 3524 enum ll_merge_result status; 3525 3526 /* resolve trivial cases first */ 3527 if (oideq(base, ours)) 3528 return resolve_to(image, theirs); 3529 else if (oideq(base, theirs) || oideq(ours, theirs)) 3530 return resolve_to(image, ours); 3531 3532 read_mmblob(&base_file, base); 3533 read_mmblob(&our_file, ours); 3534 read_mmblob(&their_file, theirs); 3535 merge_opts.variant = state->merge_variant; 3536 status = ll_merge(&result, path, 3537 &base_file, "base", 3538 &our_file, "ours", 3539 &their_file, "theirs", 3540 state->repo->index, 3541 &merge_opts); 3542 if (status == LL_MERGE_BINARY_CONFLICT) 3543 warning("Cannot merge binary files: %s (%s vs. %s)", 3544 path, "ours", "theirs"); 3545 free(base_file.ptr); 3546 free(our_file.ptr); 3547 free(their_file.ptr); 3548 if (status < 0 || !result.ptr) { 3549 free(result.ptr); 3550 return -1; 3551 } 3552 image_clear(image); 3553 strbuf_attach(&image->buf, result.ptr, result.size, result.size); 3554 3555 return status; 3556} 3557 3558/* 3559 * When directly falling back to add/add three-way merge, we read from 3560 * the current contents of the new_name. In no cases other than that 3561 * this function will be called. 3562 */ 3563static int load_current(struct apply_state *state, 3564 struct image *image, 3565 struct patch *patch) 3566{ 3567 struct strbuf buf = STRBUF_INIT; 3568 int status, pos; 3569 size_t len; 3570 char *img; 3571 struct stat st; 3572 struct cache_entry *ce; 3573 char *name = patch->new_name; 3574 unsigned mode = patch->new_mode; 3575 3576 if (!patch->is_new) 3577 BUG("patch to %s is not a creation", patch->old_name); 3578 3579 pos = index_name_pos(state->repo->index, name, strlen(name)); 3580 if (pos < 0) 3581 return error(_("%s: does not exist in index"), name); 3582 ce = state->repo->index->cache[pos]; 3583 if (lstat(name, &st)) { 3584 if (errno != ENOENT) 3585 return error_errno("%s", name); 3586 if (checkout_target(state->repo->index, ce, &st)) 3587 return -1; 3588 } 3589 if (verify_index_match(state, ce, &st)) 3590 return error(_("%s: does not match index"), name); 3591 3592 status = load_patch_target(state, &buf, ce, &st, patch, name, mode); 3593 if (status < 0) 3594 return status; 3595 else if (status) 3596 return -1; 3597 img = strbuf_detach(&buf, &len); 3598 image_prepare(image, img, len, !patch->is_binary); 3599 return 0; 3600} 3601 3602static int try_threeway(struct apply_state *state, 3603 struct image *image, 3604 struct patch *patch, 3605 struct stat *st, 3606 const struct cache_entry *ce) 3607{ 3608 struct object_id pre_oid, post_oid, our_oid; 3609 struct strbuf buf = STRBUF_INIT; 3610 size_t len; 3611 int status; 3612 char *img; 3613 struct image tmp_image = IMAGE_INIT; 3614 3615 /* No point falling back to 3-way merge in these cases */ 3616 if (patch->is_delete || 3617 S_ISGITLINK(patch->old_mode) || S_ISGITLINK(patch->new_mode) || 3618 (patch->is_new && !patch->direct_to_threeway) || 3619 (patch->is_rename && !patch->lines_added && !patch->lines_deleted)) 3620 return -1; 3621 3622 /* Preimage the patch was prepared for */ 3623 if (patch->is_new) 3624 odb_write_object(the_repository->objects, "", 0, OBJ_BLOB, &pre_oid); 3625 else if (repo_get_oid(the_repository, patch->old_oid_prefix, &pre_oid) || 3626 read_blob_object(&buf, &pre_oid, patch->old_mode)) 3627 return error(_("repository lacks the necessary blob to perform 3-way merge.")); 3628 3629 if (state->apply_verbosity > verbosity_silent && patch->direct_to_threeway) 3630 fprintf(stderr, _("Performing three-way merge...\n")); 3631 3632 img = strbuf_detach(&buf, &len); 3633 image_prepare(&tmp_image, img, len, 1); 3634 /* Apply the patch to get the post image */ 3635 if (apply_fragments(state, &tmp_image, patch) < 0) { 3636 image_clear(&tmp_image); 3637 return -1; 3638 } 3639 /* post_oid is theirs */ 3640 odb_write_object(the_repository->objects, tmp_image.buf.buf, 3641 tmp_image.buf.len, OBJ_BLOB, &post_oid); 3642 image_clear(&tmp_image); 3643 3644 /* our_oid is ours */ 3645 if (patch->is_new) { 3646 if (load_current(state, &tmp_image, patch)) 3647 return error(_("cannot read the current contents of '%s'"), 3648 patch->new_name); 3649 } else { 3650 if (load_preimage(state, &tmp_image, patch, st, ce)) 3651 return error(_("cannot read the current contents of '%s'"), 3652 patch->old_name); 3653 } 3654 odb_write_object(the_repository->objects, tmp_image.buf.buf, 3655 tmp_image.buf.len, OBJ_BLOB, &our_oid); 3656 image_clear(&tmp_image); 3657 3658 /* in-core three-way merge between post and our using pre as base */ 3659 status = three_way_merge(state, image, patch->new_name, 3660 &pre_oid, &our_oid, &post_oid); 3661 if (status < 0) { 3662 if (state->apply_verbosity > verbosity_silent) 3663 fprintf(stderr, 3664 _("Failed to perform three-way merge...\n")); 3665 return status; 3666 } 3667 3668 if (status) { 3669 patch->conflicted_threeway = 1; 3670 if (patch->is_new) 3671 oidclr(&patch->threeway_stage[0], the_repository->hash_algo); 3672 else 3673 oidcpy(&patch->threeway_stage[0], &pre_oid); 3674 oidcpy(&patch->threeway_stage[1], &our_oid); 3675 oidcpy(&patch->threeway_stage[2], &post_oid); 3676 if (state->apply_verbosity > verbosity_silent) 3677 fprintf(stderr, 3678 _("Applied patch to '%s' with conflicts.\n"), 3679 patch->new_name); 3680 } else { 3681 if (state->apply_verbosity > verbosity_silent) 3682 fprintf(stderr, 3683 _("Applied patch to '%s' cleanly.\n"), 3684 patch->new_name); 3685 } 3686 return 0; 3687} 3688 3689static int apply_data(struct apply_state *state, struct patch *patch, 3690 struct stat *st, const struct cache_entry *ce) 3691{ 3692 struct image image = IMAGE_INIT; 3693 3694 if (load_preimage(state, &image, patch, st, ce) < 0) 3695 return -1; 3696 3697 if (!state->threeway || try_threeway(state, &image, patch, st, ce) < 0) { 3698 if (state->apply_verbosity > verbosity_silent && 3699 state->threeway && !patch->direct_to_threeway) 3700 fprintf(stderr, _("Falling back to direct application...\n")); 3701 3702 /* Note: with --reject, apply_fragments() returns 0 */ 3703 if (patch->direct_to_threeway || apply_fragments(state, &image, patch) < 0) { 3704 image_clear(&image); 3705 return -1; 3706 } 3707 } 3708 patch->result = strbuf_detach(&image.buf, &patch->resultsize); 3709 add_to_fn_table(state, patch); 3710 free(image.line); 3711 3712 if (0 < patch->is_delete && patch->resultsize) 3713 return error(_("removal patch leaves file contents")); 3714 3715 return 0; 3716} 3717 3718/* 3719 * If "patch" that we are looking at modifies or deletes what we have, 3720 * we would want it not to lose any local modification we have, either 3721 * in the working tree or in the index. 3722 * 3723 * This also decides if a non-git patch is a creation patch or a 3724 * modification to an existing empty file. We do not check the state 3725 * of the current tree for a creation patch in this function; the caller 3726 * check_patch() separately makes sure (and errors out otherwise) that 3727 * the path the patch creates does not exist in the current tree. 3728 */ 3729static int check_preimage(struct apply_state *state, 3730 struct patch *patch, 3731 struct cache_entry **ce, 3732 struct stat *st) 3733{ 3734 const char *old_name = patch->old_name; 3735 struct patch *previous = NULL; 3736 int stat_ret = 0, status; 3737 unsigned st_mode = 0; 3738 3739 if (!old_name) 3740 return 0; 3741 3742 assert(patch->is_new <= 0); 3743 previous = previous_patch(state, patch, &status); 3744 3745 if (status) 3746 return error(_("path %s has been renamed/deleted"), old_name); 3747 if (previous) { 3748 st_mode = previous->new_mode; 3749 } else if (!state->cached) { 3750 stat_ret = lstat(old_name, st); 3751 if (stat_ret && errno != ENOENT) 3752 return error_errno("%s", old_name); 3753 } 3754 3755 if (state->check_index && !previous) { 3756 int pos = index_name_pos(state->repo->index, old_name, 3757 strlen(old_name)); 3758 if (pos < 0) { 3759 if (patch->is_new < 0) 3760 goto is_new; 3761 return error(_("%s: does not exist in index"), old_name); 3762 } 3763 *ce = state->repo->index->cache[pos]; 3764 if (stat_ret < 0) { 3765 if (checkout_target(state->repo->index, *ce, st)) 3766 return -1; 3767 } 3768 if (!state->cached && verify_index_match(state, *ce, st)) 3769 return error(_("%s: does not match index"), old_name); 3770 if (state->cached) 3771 st_mode = (*ce)->ce_mode; 3772 } else if (stat_ret < 0) { 3773 if (patch->is_new < 0) 3774 goto is_new; 3775 return error_errno("%s", old_name); 3776 } 3777 3778 if (!state->cached && !previous) { 3779 if (*ce && !(*ce)->ce_mode) 3780 BUG("ce_mode == 0 for path '%s'", old_name); 3781 3782 if (trust_executable_bit) 3783 st_mode = ce_mode_from_stat(*ce, st->st_mode); 3784 else if (*ce) 3785 st_mode = (*ce)->ce_mode; 3786 else 3787 st_mode = patch->old_mode; 3788 } 3789 3790 if (patch->is_new < 0) 3791 patch->is_new = 0; 3792 if (!patch->old_mode) 3793 patch->old_mode = st_mode; 3794 if ((st_mode ^ patch->old_mode) & S_IFMT) 3795 return error(_("%s: wrong type"), old_name); 3796 if (st_mode != patch->old_mode) 3797 warning(_("%s has type %o, expected %o"), 3798 old_name, st_mode, patch->old_mode); 3799 if (!patch->new_mode && !patch->is_delete) 3800 patch->new_mode = st_mode; 3801 return 0; 3802 3803 is_new: 3804 patch->is_new = 1; 3805 patch->is_delete = 0; 3806 FREE_AND_NULL(patch->old_name); 3807 return 0; 3808} 3809 3810 3811#define EXISTS_IN_INDEX 1 3812#define EXISTS_IN_WORKTREE 2 3813#define EXISTS_IN_INDEX_AS_ITA 3 3814 3815static int check_to_create(struct apply_state *state, 3816 const char *new_name, 3817 int ok_if_exists) 3818{ 3819 struct stat nst; 3820 3821 if (state->check_index && (!ok_if_exists || !state->cached)) { 3822 int pos; 3823 3824 pos = index_name_pos(state->repo->index, new_name, strlen(new_name)); 3825 if (pos >= 0) { 3826 struct cache_entry *ce = state->repo->index->cache[pos]; 3827 3828 /* allow ITA, as they do not yet exist in the index */ 3829 if (!ok_if_exists && !(ce->ce_flags & CE_INTENT_TO_ADD)) 3830 return EXISTS_IN_INDEX; 3831 3832 /* ITA entries can never match working tree files */ 3833 if (!state->cached && (ce->ce_flags & CE_INTENT_TO_ADD)) 3834 return EXISTS_IN_INDEX_AS_ITA; 3835 } 3836 } 3837 3838 if (state->cached) 3839 return 0; 3840 3841 if (!lstat(new_name, &nst)) { 3842 if (S_ISDIR(nst.st_mode) || ok_if_exists) 3843 return 0; 3844 /* 3845 * A leading component of new_name might be a symlink 3846 * that is going to be removed with this patch, but 3847 * still pointing at somewhere that has the path. 3848 * In such a case, path "new_name" does not exist as 3849 * far as git is concerned. 3850 */ 3851 if (has_symlink_leading_path(new_name, strlen(new_name))) 3852 return 0; 3853 3854 return EXISTS_IN_WORKTREE; 3855 } else if (!is_missing_file_error(errno)) { 3856 return error_errno("%s", new_name); 3857 } 3858 return 0; 3859} 3860 3861static void prepare_symlink_changes(struct apply_state *state, struct patch *patch) 3862{ 3863 for ( ; patch; patch = patch->next) { 3864 if ((patch->old_name && S_ISLNK(patch->old_mode)) && 3865 (patch->is_rename || patch->is_delete)) 3866 /* the symlink at patch->old_name is removed */ 3867 strset_add(&state->removed_symlinks, patch->old_name); 3868 3869 if (patch->new_name && S_ISLNK(patch->new_mode)) 3870 /* the symlink at patch->new_name is created or remains */ 3871 strset_add(&state->kept_symlinks, patch->new_name); 3872 } 3873} 3874 3875static int path_is_beyond_symlink_1(struct apply_state *state, struct strbuf *name) 3876{ 3877 do { 3878 while (--name->len && name->buf[name->len] != '/') 3879 ; /* scan backwards */ 3880 if (!name->len) 3881 break; 3882 name->buf[name->len] = '\0'; 3883 if (strset_contains(&state->kept_symlinks, name->buf)) 3884 return 1; 3885 if (strset_contains(&state->removed_symlinks, name->buf)) 3886 /* 3887 * This cannot be "return 0", because we may 3888 * see a new one created at a higher level. 3889 */ 3890 continue; 3891 3892 /* otherwise, check the preimage */ 3893 if (state->check_index) { 3894 struct cache_entry *ce; 3895 3896 ce = index_file_exists(state->repo->index, name->buf, 3897 name->len, ignore_case); 3898 if (ce && S_ISLNK(ce->ce_mode)) 3899 return 1; 3900 } else { 3901 struct stat st; 3902 if (!lstat(name->buf, &st) && S_ISLNK(st.st_mode)) 3903 return 1; 3904 } 3905 } while (1); 3906 return 0; 3907} 3908 3909static int path_is_beyond_symlink(struct apply_state *state, const char *name_) 3910{ 3911 int ret; 3912 struct strbuf name = STRBUF_INIT; 3913 3914 assert(*name_ != '\0'); 3915 strbuf_addstr(&name, name_); 3916 ret = path_is_beyond_symlink_1(state, &name); 3917 strbuf_release(&name); 3918 3919 return ret; 3920} 3921 3922static int check_unsafe_path(struct patch *patch) 3923{ 3924 const char *old_name = NULL; 3925 const char *new_name = NULL; 3926 if (patch->is_delete) 3927 old_name = patch->old_name; 3928 else if (!patch->is_new && !patch->is_copy) 3929 old_name = patch->old_name; 3930 if (!patch->is_delete) 3931 new_name = patch->new_name; 3932 3933 if (old_name && !verify_path(old_name, patch->old_mode)) 3934 return error(_("invalid path '%s'"), old_name); 3935 if (new_name && !verify_path(new_name, patch->new_mode)) 3936 return error(_("invalid path '%s'"), new_name); 3937 return 0; 3938} 3939 3940/* 3941 * Check and apply the patch in-core; leave the result in patch->result 3942 * for the caller to write it out to the final destination. 3943 */ 3944static int check_patch(struct apply_state *state, struct patch *patch) 3945{ 3946 struct stat st; 3947 const char *old_name = patch->old_name; 3948 const char *new_name = patch->new_name; 3949 const char *name = old_name ? old_name : new_name; 3950 struct cache_entry *ce = NULL; 3951 struct patch *tpatch; 3952 int ok_if_exists; 3953 int status; 3954 3955 patch->rejected = 1; /* we will drop this after we succeed */ 3956 3957 status = check_preimage(state, patch, &ce, &st); 3958 if (status) 3959 return status; 3960 old_name = patch->old_name; 3961 3962 /* 3963 * A type-change diff is always split into a patch to delete 3964 * old, immediately followed by a patch to create new (see 3965 * diff.c::run_diff()); in such a case it is Ok that the entry 3966 * to be deleted by the previous patch is still in the working 3967 * tree and in the index. 3968 * 3969 * A patch to swap-rename between A and B would first rename A 3970 * to B and then rename B to A. While applying the first one, 3971 * the presence of B should not stop A from getting renamed to 3972 * B; ask to_be_deleted() about the later rename. Removal of 3973 * B and rename from A to B is handled the same way by asking 3974 * was_deleted(). 3975 */ 3976 if ((tpatch = in_fn_table(state, new_name)) && 3977 (was_deleted(tpatch) || to_be_deleted(tpatch))) 3978 ok_if_exists = 1; 3979 else 3980 ok_if_exists = 0; 3981 3982 if (new_name && 3983 ((0 < patch->is_new) || patch->is_rename || patch->is_copy)) { 3984 int err = check_to_create(state, new_name, ok_if_exists); 3985 3986 if (err && state->threeway) { 3987 patch->direct_to_threeway = 1; 3988 } else switch (err) { 3989 case 0: 3990 break; /* happy */ 3991 case EXISTS_IN_INDEX: 3992 return error(_("%s: already exists in index"), new_name); 3993 case EXISTS_IN_INDEX_AS_ITA: 3994 return error(_("%s: does not match index"), new_name); 3995 case EXISTS_IN_WORKTREE: 3996 return error(_("%s: already exists in working directory"), 3997 new_name); 3998 default: 3999 return err; 4000 } 4001 4002 if (!patch->new_mode) { 4003 if (0 < patch->is_new) 4004 patch->new_mode = S_IFREG | 0644; 4005 else 4006 patch->new_mode = patch->old_mode; 4007 } 4008 } 4009 4010 if (new_name && old_name) { 4011 int same = !strcmp(old_name, new_name); 4012 if (!patch->new_mode) 4013 patch->new_mode = patch->old_mode; 4014 if ((patch->old_mode ^ patch->new_mode) & S_IFMT) { 4015 if (same) 4016 return error(_("new mode (%o) of %s does not " 4017 "match old mode (%o)"), 4018 patch->new_mode, new_name, 4019 patch->old_mode); 4020 else 4021 return error(_("new mode (%o) of %s does not " 4022 "match old mode (%o) of %s"), 4023 patch->new_mode, new_name, 4024 patch->old_mode, old_name); 4025 } 4026 } 4027 4028 if (!state->unsafe_paths && check_unsafe_path(patch)) 4029 return -128; 4030 4031 /* 4032 * An attempt to read from or delete a path that is beyond a 4033 * symbolic link will be prevented by load_patch_target() that 4034 * is called at the beginning of apply_data() so we do not 4035 * have to worry about a patch marked with "is_delete" bit 4036 * here. We however need to make sure that the patch result 4037 * is not deposited to a path that is beyond a symbolic link 4038 * here. 4039 */ 4040 if (!patch->is_delete && path_is_beyond_symlink(state, patch->new_name)) 4041 return error(_("affected file '%s' is beyond a symbolic link"), 4042 patch->new_name); 4043 4044 if (apply_data(state, patch, &st, ce) < 0) 4045 return error(_("%s: patch does not apply"), name); 4046 patch->rejected = 0; 4047 return 0; 4048} 4049 4050static int check_patch_list(struct apply_state *state, struct patch *patch) 4051{ 4052 int err = 0; 4053 4054 prepare_symlink_changes(state, patch); 4055 prepare_fn_table(state, patch); 4056 while (patch) { 4057 int res; 4058 if (state->apply_verbosity > verbosity_normal) 4059 say_patch_name(stderr, 4060 _("Checking patch %s..."), patch); 4061 res = check_patch(state, patch); 4062 if (res == -128) 4063 return -128; 4064 err |= res; 4065 patch = patch->next; 4066 } 4067 return err; 4068} 4069 4070static int read_apply_cache(struct apply_state *state) 4071{ 4072 if (state->index_file) 4073 return read_index_from(state->repo->index, state->index_file, 4074 repo_get_git_dir(the_repository)); 4075 else 4076 return repo_read_index(state->repo); 4077} 4078 4079/* This function tries to read the object name from the current index */ 4080static int get_current_oid(struct apply_state *state, const char *path, 4081 struct object_id *oid) 4082{ 4083 int pos; 4084 4085 if (read_apply_cache(state) < 0) 4086 return -1; 4087 pos = index_name_pos(state->repo->index, path, strlen(path)); 4088 if (pos < 0) 4089 return -1; 4090 oidcpy(oid, &state->repo->index->cache[pos]->oid); 4091 return 0; 4092} 4093 4094static int preimage_oid_in_gitlink_patch(struct patch *p, struct object_id *oid) 4095{ 4096 /* 4097 * A usable gitlink patch has only one fragment (hunk) that looks like: 4098 * @@ -1 +1 @@ 4099 * -Subproject commit <old sha1> 4100 * +Subproject commit <new sha1> 4101 * or 4102 * @@ -1 +0,0 @@ 4103 * -Subproject commit <old sha1> 4104 * for a removal patch. 4105 */ 4106 struct fragment *hunk = p->fragments; 4107 static const char heading[] = "-Subproject commit "; 4108 char *preimage; 4109 4110 if (/* does the patch have only one hunk? */ 4111 hunk && !hunk->next && 4112 /* is its preimage one line? */ 4113 hunk->oldpos == 1 && hunk->oldlines == 1 && 4114 /* does preimage begin with the heading? */ 4115 (preimage = memchr(hunk->patch, '\n', hunk->size)) != NULL && 4116 starts_with(++preimage, heading) && 4117 /* does it record full SHA-1? */ 4118 !get_oid_hex(preimage + sizeof(heading) - 1, oid) && 4119 preimage[sizeof(heading) + the_hash_algo->hexsz - 1] == '\n' && 4120 /* does the abbreviated name on the index line agree with it? */ 4121 starts_with(preimage + sizeof(heading) - 1, p->old_oid_prefix)) 4122 return 0; /* it all looks fine */ 4123 4124 /* we may have full object name on the index line */ 4125 return get_oid_hex(p->old_oid_prefix, oid); 4126} 4127 4128/* Build an index that contains just the files needed for a 3way merge */ 4129static int build_fake_ancestor(struct apply_state *state, struct patch *list) 4130{ 4131 struct patch *patch; 4132 struct index_state result = INDEX_STATE_INIT(state->repo); 4133 struct lock_file lock = LOCK_INIT; 4134 int res; 4135 4136 /* Once we start supporting the reverse patch, it may be 4137 * worth showing the new sha1 prefix, but until then... 4138 */ 4139 for (patch = list; patch; patch = patch->next) { 4140 struct object_id oid; 4141 struct cache_entry *ce; 4142 const char *name; 4143 4144 name = patch->old_name ? patch->old_name : patch->new_name; 4145 if (0 < patch->is_new) 4146 continue; 4147 4148 if (S_ISGITLINK(patch->old_mode)) { 4149 if (!preimage_oid_in_gitlink_patch(patch, &oid)) 4150 ; /* ok, the textual part looks sane */ 4151 else 4152 return error(_("sha1 information is lacking or " 4153 "useless for submodule %s"), name); 4154 } else if (!repo_get_oid_blob(the_repository, patch->old_oid_prefix, &oid)) { 4155 ; /* ok */ 4156 } else if (!patch->lines_added && !patch->lines_deleted) { 4157 /* mode-only change: update the current */ 4158 if (get_current_oid(state, patch->old_name, &oid)) 4159 return error(_("mode change for %s, which is not " 4160 "in current HEAD"), name); 4161 } else 4162 return error(_("sha1 information is lacking or useless " 4163 "(%s)."), name); 4164 4165 ce = make_cache_entry(&result, patch->old_mode, &oid, name, 0, 0); 4166 if (!ce) 4167 return error(_("make_cache_entry failed for path '%s'"), 4168 name); 4169 if (add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD)) { 4170 discard_cache_entry(ce); 4171 return error(_("could not add %s to temporary index"), 4172 name); 4173 } 4174 } 4175 4176 hold_lock_file_for_update(&lock, state->fake_ancestor, LOCK_DIE_ON_ERROR); 4177 res = write_locked_index(&result, &lock, COMMIT_LOCK); 4178 discard_index(&result); 4179 4180 if (res) 4181 return error(_("could not write temporary index to %s"), 4182 state->fake_ancestor); 4183 4184 return 0; 4185} 4186 4187static void stat_patch_list(struct apply_state *state, struct patch *patch) 4188{ 4189 int files, adds, dels; 4190 4191 for (files = adds = dels = 0 ; patch ; patch = patch->next) { 4192 files++; 4193 adds += patch->lines_added; 4194 dels += patch->lines_deleted; 4195 show_stats(state, patch); 4196 } 4197 4198 print_stat_summary(stdout, files, adds, dels); 4199} 4200 4201static void numstat_patch_list(struct apply_state *state, 4202 struct patch *patch) 4203{ 4204 for ( ; patch; patch = patch->next) { 4205 const char *name; 4206 name = patch->new_name ? patch->new_name : patch->old_name; 4207 if (patch->is_binary) 4208 printf("-\t-\t"); 4209 else 4210 printf("%d\t%d\t", patch->lines_added, patch->lines_deleted); 4211 write_name_quoted(name, stdout, state->line_termination); 4212 } 4213} 4214 4215static void show_file_mode_name(const char *newdelete, unsigned int mode, const char *name) 4216{ 4217 if (mode) 4218 printf(" %s mode %06o %s\n", newdelete, mode, name); 4219 else 4220 printf(" %s %s\n", newdelete, name); 4221} 4222 4223static void show_mode_change(struct patch *p, int show_name) 4224{ 4225 if (p->old_mode && p->new_mode && p->old_mode != p->new_mode) { 4226 if (show_name) 4227 printf(" mode change %06o => %06o %s\n", 4228 p->old_mode, p->new_mode, p->new_name); 4229 else 4230 printf(" mode change %06o => %06o\n", 4231 p->old_mode, p->new_mode); 4232 } 4233} 4234 4235static void show_rename_copy(struct patch *p) 4236{ 4237 const char *renamecopy = p->is_rename ? "rename" : "copy"; 4238 const char *old_name, *new_name; 4239 4240 /* Find common prefix */ 4241 old_name = p->old_name; 4242 new_name = p->new_name; 4243 while (1) { 4244 const char *slash_old, *slash_new; 4245 slash_old = strchr(old_name, '/'); 4246 slash_new = strchr(new_name, '/'); 4247 if (!slash_old || 4248 !slash_new || 4249 slash_old - old_name != slash_new - new_name || 4250 memcmp(old_name, new_name, slash_new - new_name)) 4251 break; 4252 old_name = slash_old + 1; 4253 new_name = slash_new + 1; 4254 } 4255 /* p->old_name through old_name is the common prefix, and old_name and 4256 * new_name through the end of names are renames 4257 */ 4258 if (old_name != p->old_name) 4259 printf(" %s %.*s{%s => %s} (%d%%)\n", renamecopy, 4260 (int)(old_name - p->old_name), p->old_name, 4261 old_name, new_name, p->score); 4262 else 4263 printf(" %s %s => %s (%d%%)\n", renamecopy, 4264 p->old_name, p->new_name, p->score); 4265 show_mode_change(p, 0); 4266} 4267 4268static void summary_patch_list(struct patch *patch) 4269{ 4270 struct patch *p; 4271 4272 for (p = patch; p; p = p->next) { 4273 if (p->is_new) 4274 show_file_mode_name("create", p->new_mode, p->new_name); 4275 else if (p->is_delete) 4276 show_file_mode_name("delete", p->old_mode, p->old_name); 4277 else { 4278 if (p->is_rename || p->is_copy) 4279 show_rename_copy(p); 4280 else { 4281 if (p->score) { 4282 printf(" rewrite %s (%d%%)\n", 4283 p->new_name, p->score); 4284 show_mode_change(p, 0); 4285 } 4286 else 4287 show_mode_change(p, 1); 4288 } 4289 } 4290 } 4291} 4292 4293static void patch_stats(struct apply_state *state, struct patch *patch) 4294{ 4295 int lines = patch->lines_added + patch->lines_deleted; 4296 4297 if (lines > state->max_change) 4298 state->max_change = lines; 4299 if (patch->old_name) { 4300 int len = quote_c_style(patch->old_name, NULL, NULL, 0); 4301 if (!len) 4302 len = strlen(patch->old_name); 4303 if (len > state->max_len) 4304 state->max_len = len; 4305 } 4306 if (patch->new_name) { 4307 int len = quote_c_style(patch->new_name, NULL, NULL, 0); 4308 if (!len) 4309 len = strlen(patch->new_name); 4310 if (len > state->max_len) 4311 state->max_len = len; 4312 } 4313} 4314 4315static int remove_file(struct apply_state *state, struct patch *patch, int rmdir_empty) 4316{ 4317 if (state->update_index && !state->ita_only) { 4318 if (remove_file_from_index(state->repo->index, patch->old_name) < 0) 4319 return error(_("unable to remove %s from index"), patch->old_name); 4320 } 4321 if (!state->cached) { 4322 if (!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) { 4323 remove_path(patch->old_name); 4324 } 4325 } 4326 return 0; 4327} 4328 4329static int add_index_file(struct apply_state *state, 4330 const char *path, 4331 unsigned mode, 4332 void *buf, 4333 unsigned long size) 4334{ 4335 struct stat st; 4336 struct cache_entry *ce; 4337 int namelen = strlen(path); 4338 4339 ce = make_empty_cache_entry(state->repo->index, namelen); 4340 memcpy(ce->name, path, namelen); 4341 ce->ce_mode = create_ce_mode(mode); 4342 ce->ce_flags = create_ce_flags(0); 4343 ce->ce_namelen = namelen; 4344 if (state->ita_only) { 4345 ce->ce_flags |= CE_INTENT_TO_ADD; 4346 set_object_name_for_intent_to_add_entry(ce); 4347 } else if (S_ISGITLINK(mode)) { 4348 const char *s; 4349 4350 if (!skip_prefix(buf, "Subproject commit ", &s) || 4351 get_oid_hex(s, &ce->oid)) { 4352 discard_cache_entry(ce); 4353 return error(_("corrupt patch for submodule %s"), path); 4354 } 4355 } else { 4356 if (!state->cached) { 4357 if (lstat(path, &st) < 0) { 4358 discard_cache_entry(ce); 4359 return error_errno(_("unable to stat newly " 4360 "created file '%s'"), 4361 path); 4362 } 4363 fill_stat_cache_info(state->repo->index, ce, &st); 4364 } 4365 if (odb_write_object(the_repository->objects, buf, size, 4366 OBJ_BLOB, &ce->oid) < 0) { 4367 discard_cache_entry(ce); 4368 return error(_("unable to create backing store " 4369 "for newly created file %s"), path); 4370 } 4371 } 4372 if (add_index_entry(state->repo->index, ce, ADD_CACHE_OK_TO_ADD) < 0) { 4373 discard_cache_entry(ce); 4374 return error(_("unable to add cache entry for %s"), path); 4375 } 4376 4377 return 0; 4378} 4379 4380/* 4381 * Returns: 4382 * -1 if an unrecoverable error happened 4383 * 0 if everything went well 4384 * 1 if a recoverable error happened 4385 */ 4386static int try_create_file(struct apply_state *state, const char *path, 4387 unsigned int mode, const char *buf, 4388 unsigned long size) 4389{ 4390 int fd, res; 4391 struct strbuf nbuf = STRBUF_INIT; 4392 4393 if (S_ISGITLINK(mode)) { 4394 struct stat st; 4395 if (!lstat(path, &st) && S_ISDIR(st.st_mode)) 4396 return 0; 4397 return !!mkdir(path, 0777); 4398 } 4399 4400 if (has_symlinks && S_ISLNK(mode)) 4401 /* Although buf:size is counted string, it also is NUL 4402 * terminated. 4403 */ 4404 return !!symlink(buf, path); 4405 4406 fd = open(path, O_CREAT | O_EXCL | O_WRONLY, (mode & 0100) ? 0777 : 0666); 4407 if (fd < 0) 4408 return 1; 4409 4410 if (convert_to_working_tree(state->repo->index, path, buf, size, &nbuf, NULL)) { 4411 size = nbuf.len; 4412 buf = nbuf.buf; 4413 } 4414 4415 res = write_in_full(fd, buf, size) < 0; 4416 if (res) 4417 error_errno(_("failed to write to '%s'"), path); 4418 strbuf_release(&nbuf); 4419 4420 if (close(fd) < 0 && !res) 4421 return error_errno(_("closing file '%s'"), path); 4422 4423 return res ? -1 : 0; 4424} 4425 4426/* 4427 * We optimistically assume that the directories exist, 4428 * which is true 99% of the time anyway. If they don't, 4429 * we create them and try again. 4430 * 4431 * Returns: 4432 * -1 on error 4433 * 0 otherwise 4434 */ 4435static int create_one_file(struct apply_state *state, 4436 char *path, 4437 unsigned mode, 4438 const char *buf, 4439 unsigned long size) 4440{ 4441 char *newpath = NULL; 4442 int res; 4443 4444 if (state->cached) 4445 return 0; 4446 4447 /* 4448 * We already try to detect whether files are beyond a symlink in our 4449 * up-front checks. But in the case where symlinks are created by any 4450 * of the intermediate hunks it can happen that our up-front checks 4451 * didn't yet see the symlink, but at the point of arriving here there 4452 * in fact is one. We thus repeat the check for symlinks here. 4453 * 4454 * Note that this does not make the up-front check obsolete as the 4455 * failure mode is different: 4456 * 4457 * - The up-front checks cause us to abort before we have written 4458 * anything into the working directory. So when we exit this way the 4459 * working directory remains clean. 4460 * 4461 * - The checks here happen in the middle of the action where we have 4462 * already started to apply the patch. The end result will be a dirty 4463 * working directory. 4464 * 4465 * Ideally, we should update the up-front checks to catch what would 4466 * happen when we apply the patch before we damage the working tree. 4467 * We have all the information necessary to do so. But for now, as a 4468 * part of embargoed security work, having this check would serve as a 4469 * reasonable first step. 4470 */ 4471 if (path_is_beyond_symlink(state, path)) 4472 return error(_("affected file '%s' is beyond a symbolic link"), path); 4473 4474 res = try_create_file(state, path, mode, buf, size); 4475 if (res < 0) 4476 return -1; 4477 if (!res) 4478 return 0; 4479 4480 if (errno == ENOENT) { 4481 if (safe_create_leading_directories_no_share(path)) 4482 return 0; 4483 res = try_create_file(state, path, mode, buf, size); 4484 if (res < 0) 4485 return -1; 4486 if (!res) 4487 return 0; 4488 } 4489 4490 if (errno == EEXIST || errno == EACCES) { 4491 /* We may be trying to create a file where a directory 4492 * used to be. 4493 */ 4494 struct stat st; 4495 if (!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path))) 4496 errno = EEXIST; 4497 } 4498 4499 if (errno == EEXIST) { 4500 unsigned int nr = getpid(); 4501 4502 for (;;) { 4503 newpath = mkpathdup("%s~%u", path, nr); 4504 res = try_create_file(state, newpath, mode, buf, size); 4505 if (res < 0) 4506 goto out; 4507 if (!res) { 4508 if (!rename(newpath, path)) 4509 goto out; 4510 unlink_or_warn(newpath); 4511 break; 4512 } 4513 if (errno != EEXIST) 4514 break; 4515 ++nr; 4516 FREE_AND_NULL(newpath); 4517 } 4518 } 4519 res = error_errno(_("unable to write file '%s' mode %o"), path, mode); 4520out: 4521 free(newpath); 4522 return res; 4523} 4524 4525static int add_conflicted_stages_file(struct apply_state *state, 4526 struct patch *patch) 4527{ 4528 int stage, namelen; 4529 unsigned mode; 4530 struct cache_entry *ce; 4531 4532 if (!state->update_index) 4533 return 0; 4534 namelen = strlen(patch->new_name); 4535 mode = patch->new_mode ? patch->new_mode : (S_IFREG | 0644); 4536 4537 remove_file_from_index(state->repo->index, patch->new_name); 4538 for (stage = 1; stage < 4; stage++) { 4539 if (is_null_oid(&patch->threeway_stage[stage - 1])) 4540 continue; 4541 ce = make_empty_cache_entry(state->repo->index, namelen); 4542 memcpy(ce->name, patch->new_name, namelen); 4543 ce->ce_mode = create_ce_mode(mode); 4544 ce->ce_flags = create_ce_flags(stage); 4545 ce->ce_namelen = namelen; 4546 oidcpy(&ce->oid, &patch->threeway_stage[stage - 1]); 4547 if (add_index_entry(state->repo->index, ce, ADD_CACHE_OK_TO_ADD) < 0) { 4548 discard_cache_entry(ce); 4549 return error(_("unable to add cache entry for %s"), 4550 patch->new_name); 4551 } 4552 } 4553 4554 return 0; 4555} 4556 4557static int create_file(struct apply_state *state, struct patch *patch) 4558{ 4559 char *path = patch->new_name; 4560 unsigned mode = patch->new_mode; 4561 unsigned long size = patch->resultsize; 4562 char *buf = patch->result; 4563 4564 if (!mode) 4565 mode = S_IFREG | 0644; 4566 if (create_one_file(state, path, mode, buf, size)) 4567 return -1; 4568 4569 if (patch->conflicted_threeway) 4570 return add_conflicted_stages_file(state, patch); 4571 else if (state->check_index || (state->ita_only && patch->is_new > 0)) 4572 return add_index_file(state, path, mode, buf, size); 4573 return 0; 4574} 4575 4576/* phase zero is to remove, phase one is to create */ 4577static int write_out_one_result(struct apply_state *state, 4578 struct patch *patch, 4579 int phase) 4580{ 4581 if (patch->is_delete > 0) { 4582 if (phase == 0) 4583 return remove_file(state, patch, 1); 4584 return 0; 4585 } 4586 if (patch->is_new > 0 || patch->is_copy) { 4587 if (phase == 1) 4588 return create_file(state, patch); 4589 return 0; 4590 } 4591 /* 4592 * Rename or modification boils down to the same 4593 * thing: remove the old, write the new 4594 */ 4595 if (phase == 0) 4596 return remove_file(state, patch, patch->is_rename); 4597 if (phase == 1) 4598 return create_file(state, patch); 4599 return 0; 4600} 4601 4602static int write_out_one_reject(struct apply_state *state, struct patch *patch) 4603{ 4604 FILE *rej; 4605 char *namebuf; 4606 struct fragment *frag; 4607 int fd, cnt = 0; 4608 struct strbuf sb = STRBUF_INIT; 4609 4610 for (cnt = 0, frag = patch->fragments; frag; frag = frag->next) { 4611 if (!frag->rejected) 4612 continue; 4613 cnt++; 4614 } 4615 4616 if (!cnt) { 4617 if (state->apply_verbosity > verbosity_normal) 4618 say_patch_name(stderr, 4619 _("Applied patch %s cleanly."), patch); 4620 return 0; 4621 } 4622 4623 /* This should not happen, because a removal patch that leaves 4624 * contents are marked "rejected" at the patch level. 4625 */ 4626 if (!patch->new_name) 4627 die(_("internal error")); 4628 4629 /* Say this even without --verbose */ 4630 strbuf_addf(&sb, Q_("Applying patch %%s with %d reject...", 4631 "Applying patch %%s with %d rejects...", 4632 cnt), 4633 cnt); 4634 if (state->apply_verbosity > verbosity_silent) 4635 say_patch_name(stderr, sb.buf, patch); 4636 strbuf_release(&sb); 4637 4638 namebuf = xstrfmt("%s.rej", patch->new_name); 4639 4640 fd = open(namebuf, O_CREAT | O_EXCL | O_WRONLY, 0666); 4641 if (fd < 0) { 4642 if (errno != EEXIST) { 4643 error_errno(_("cannot open %s"), namebuf); 4644 goto error; 4645 } 4646 if (unlink(namebuf)) { 4647 error_errno(_("cannot unlink '%s'"), namebuf); 4648 goto error; 4649 } 4650 fd = open(namebuf, O_CREAT | O_EXCL | O_WRONLY, 0666); 4651 if (fd < 0) { 4652 error_errno(_("cannot open %s"), namebuf); 4653 goto error; 4654 } 4655 } 4656 rej = fdopen(fd, "w"); 4657 if (!rej) { 4658 error_errno(_("cannot open %s"), namebuf); 4659 close(fd); 4660 goto error; 4661 } 4662 4663 /* Normal git tools never deal with .rej, so do not pretend 4664 * this is a git patch by saying --git or giving extended 4665 * headers. While at it, maybe please "kompare" that wants 4666 * the trailing TAB and some garbage at the end of line ;-). 4667 */ 4668 fprintf(rej, "diff a/%s b/%s\t(rejected hunks)\n", 4669 patch->new_name, patch->new_name); 4670 for (cnt = 1, frag = patch->fragments; 4671 frag; 4672 cnt++, frag = frag->next) { 4673 if (!frag->rejected) { 4674 if (state->apply_verbosity > verbosity_silent) 4675 fprintf_ln(stderr, _("Hunk #%d applied cleanly."), cnt); 4676 continue; 4677 } 4678 if (state->apply_verbosity > verbosity_silent) 4679 fprintf_ln(stderr, _("Rejected hunk #%d."), cnt); 4680 fprintf(rej, "%.*s", frag->size, frag->patch); 4681 if (frag->patch[frag->size-1] != '\n') 4682 fputc('\n', rej); 4683 } 4684 fclose(rej); 4685error: 4686 free(namebuf); 4687 return -1; 4688} 4689 4690/* 4691 * Returns: 4692 * -1 if an error happened 4693 * 0 if the patch applied cleanly 4694 * 1 if the patch did not apply cleanly 4695 */ 4696static int write_out_results(struct apply_state *state, struct patch *list) 4697{ 4698 int phase; 4699 int errs = 0; 4700 struct patch *l; 4701 struct string_list cpath = STRING_LIST_INIT_DUP; 4702 4703 for (phase = 0; phase < 2; phase++) { 4704 l = list; 4705 while (l) { 4706 if (l->rejected) 4707 errs = 1; 4708 else { 4709 if (write_out_one_result(state, l, phase)) { 4710 string_list_clear(&cpath, 0); 4711 return -1; 4712 } 4713 if (phase == 1) { 4714 if (write_out_one_reject(state, l)) 4715 errs = 1; 4716 if (l->conflicted_threeway) { 4717 string_list_append(&cpath, l->new_name); 4718 errs = 1; 4719 } 4720 } 4721 } 4722 l = l->next; 4723 } 4724 } 4725 4726 if (cpath.nr) { 4727 struct string_list_item *item; 4728 4729 string_list_sort(&cpath); 4730 if (state->apply_verbosity > verbosity_silent) { 4731 for_each_string_list_item(item, &cpath) 4732 fprintf(stderr, "U %s\n", item->string); 4733 } 4734 string_list_clear(&cpath, 0); 4735 4736 /* 4737 * rerere relies on the partially merged result being in the working 4738 * tree with conflict markers, but that isn't written with --cached. 4739 */ 4740 if (!state->cached) 4741 repo_rerere(state->repo, 0); 4742 } 4743 4744 return errs; 4745} 4746 4747/* 4748 * Try to apply a patch. 4749 * 4750 * Returns: 4751 * -128 if a bad error happened (like patch unreadable) 4752 * -1 if patch did not apply and user cannot deal with it 4753 * 0 if the patch applied 4754 * 1 if the patch did not apply but user might fix it 4755 */ 4756static int apply_patch(struct apply_state *state, 4757 int fd, 4758 const char *filename, 4759 int options) 4760{ 4761 size_t offset; 4762 struct strbuf buf = STRBUF_INIT; /* owns the patch text */ 4763 struct patch *list = NULL, **listp = &list; 4764 int skipped_patch = 0; 4765 int res = 0; 4766 int flush_attributes = 0; 4767 4768 state->patch_input_file = filename; 4769 if (read_patch_file(&buf, fd) < 0) 4770 return -128; 4771 offset = 0; 4772 while (offset < buf.len) { 4773 struct patch *patch; 4774 int nr; 4775 4776 CALLOC_ARRAY(patch, 1); 4777 patch->inaccurate_eof = !!(options & APPLY_OPT_INACCURATE_EOF); 4778 patch->recount = !!(options & APPLY_OPT_RECOUNT); 4779 nr = parse_chunk(state, buf.buf + offset, buf.len - offset, patch); 4780 if (nr < 0) { 4781 free_patch(patch); 4782 if (nr == -128) { 4783 res = -128; 4784 goto end; 4785 } 4786 break; 4787 } 4788 if (state->apply_in_reverse) 4789 reverse_patches(patch); 4790 if (use_patch(state, patch)) { 4791 patch_stats(state, patch); 4792 if (!list || !state->apply_in_reverse) { 4793 *listp = patch; 4794 listp = &patch->next; 4795 } else { 4796 patch->next = list; 4797 list = patch; 4798 } 4799 4800 if ((patch->new_name && 4801 ends_with_path_components(patch->new_name, 4802 GITATTRIBUTES_FILE)) || 4803 (patch->old_name && 4804 ends_with_path_components(patch->old_name, 4805 GITATTRIBUTES_FILE))) 4806 flush_attributes = 1; 4807 } 4808 else { 4809 if (state->apply_verbosity > verbosity_normal) 4810 say_patch_name(stderr, _("Skipped patch '%s'."), patch); 4811 free_patch(patch); 4812 skipped_patch++; 4813 } 4814 offset += nr; 4815 } 4816 4817 if (!list && !skipped_patch) { 4818 if (!state->allow_empty) { 4819 error(_("No valid patches in input (allow with \"--allow-empty\")")); 4820 res = -128; 4821 } 4822 goto end; 4823 } 4824 4825 if (state->whitespace_error && (state->ws_error_action == die_on_ws_error)) 4826 state->apply = 0; 4827 4828 state->update_index = (state->check_index || state->ita_only) && state->apply; 4829 if (state->update_index && !is_lock_file_locked(&state->lock_file)) { 4830 if (state->index_file) 4831 hold_lock_file_for_update(&state->lock_file, 4832 state->index_file, 4833 LOCK_DIE_ON_ERROR); 4834 else 4835 repo_hold_locked_index(state->repo, &state->lock_file, 4836 LOCK_DIE_ON_ERROR); 4837 } 4838 4839 if ((state->check_index || state->update_index) && read_apply_cache(state) < 0) { 4840 error(_("unable to read index file")); 4841 res = -128; 4842 goto end; 4843 } 4844 4845 if (state->check || state->apply) { 4846 int r = check_patch_list(state, list); 4847 if (r == -128) { 4848 res = -128; 4849 goto end; 4850 } 4851 if (r < 0 && !state->apply_with_reject) { 4852 res = -1; 4853 goto end; 4854 } 4855 } 4856 4857 if (state->apply) { 4858 int write_res = write_out_results(state, list); 4859 if (write_res < 0) { 4860 res = -128; 4861 goto end; 4862 } 4863 if (write_res > 0) { 4864 /* with --3way, we still need to write the index out */ 4865 res = state->apply_with_reject ? -1 : 1; 4866 goto end; 4867 } 4868 } 4869 4870 if (state->fake_ancestor && 4871 build_fake_ancestor(state, list)) { 4872 res = -128; 4873 goto end; 4874 } 4875 4876 if (state->diffstat && state->apply_verbosity > verbosity_silent) 4877 stat_patch_list(state, list); 4878 4879 if (state->numstat && state->apply_verbosity > verbosity_silent) 4880 numstat_patch_list(state, list); 4881 4882 if (state->summary && state->apply_verbosity > verbosity_silent) 4883 summary_patch_list(list); 4884 4885 if (flush_attributes) 4886 reset_parsed_attributes(); 4887end: 4888 free_patch_list(list); 4889 strbuf_release(&buf); 4890 string_list_clear(&state->fn_table, 0); 4891 return res; 4892} 4893 4894static int apply_option_parse_exclude(const struct option *opt, 4895 const char *arg, int unset) 4896{ 4897 struct apply_state *state = opt->value; 4898 4899 BUG_ON_OPT_NEG(unset); 4900 4901 add_name_limit(state, arg, 1); 4902 return 0; 4903} 4904 4905static int apply_option_parse_include(const struct option *opt, 4906 const char *arg, int unset) 4907{ 4908 struct apply_state *state = opt->value; 4909 4910 BUG_ON_OPT_NEG(unset); 4911 4912 add_name_limit(state, arg, 0); 4913 state->has_include = 1; 4914 return 0; 4915} 4916 4917static int apply_option_parse_p(const struct option *opt, 4918 const char *arg, 4919 int unset) 4920{ 4921 struct apply_state *state = opt->value; 4922 4923 BUG_ON_OPT_NEG(unset); 4924 4925 state->p_value = atoi(arg); 4926 state->p_value_known = 1; 4927 return 0; 4928} 4929 4930static int apply_option_parse_space_change(const struct option *opt, 4931 const char *arg, int unset) 4932{ 4933 struct apply_state *state = opt->value; 4934 4935 BUG_ON_OPT_ARG(arg); 4936 4937 if (unset) 4938 state->ws_ignore_action = ignore_ws_none; 4939 else 4940 state->ws_ignore_action = ignore_ws_change; 4941 return 0; 4942} 4943 4944static int apply_option_parse_whitespace(const struct option *opt, 4945 const char *arg, int unset) 4946{ 4947 struct apply_state *state = opt->value; 4948 4949 BUG_ON_OPT_NEG(unset); 4950 4951 state->whitespace_option = arg; 4952 if (parse_whitespace_option(state, arg)) 4953 return -1; 4954 return 0; 4955} 4956 4957static int apply_option_parse_directory(const struct option *opt, 4958 const char *arg, int unset) 4959{ 4960 struct apply_state *state = opt->value; 4961 4962 BUG_ON_OPT_NEG(unset); 4963 4964 strbuf_reset(&state->root); 4965 strbuf_addstr(&state->root, arg); 4966 strbuf_complete(&state->root, '/'); 4967 return 0; 4968} 4969 4970int apply_all_patches(struct apply_state *state, 4971 int argc, 4972 const char **argv, 4973 int options) 4974{ 4975 int i; 4976 int res; 4977 int errs = 0; 4978 int read_stdin = 1; 4979 4980 for (i = 0; i < argc; i++) { 4981 const char *arg = argv[i]; 4982 char *to_free = NULL; 4983 int fd; 4984 4985 if (!strcmp(arg, "-")) { 4986 res = apply_patch(state, 0, "<stdin>", options); 4987 if (res < 0) 4988 goto end; 4989 errs |= res; 4990 read_stdin = 0; 4991 continue; 4992 } else 4993 arg = to_free = prefix_filename(state->prefix, arg); 4994 4995 fd = open(arg, O_RDONLY); 4996 if (fd < 0) { 4997 error(_("can't open patch '%s': %s"), arg, strerror(errno)); 4998 res = -128; 4999 free(to_free); 5000 goto end; 5001 } 5002 read_stdin = 0; 5003 set_default_whitespace_mode(state); 5004 res = apply_patch(state, fd, arg, options); 5005 close(fd); 5006 free(to_free); 5007 if (res < 0) 5008 goto end; 5009 errs |= res; 5010 } 5011 set_default_whitespace_mode(state); 5012 if (read_stdin) { 5013 res = apply_patch(state, 0, "<stdin>", options); 5014 if (res < 0) 5015 goto end; 5016 errs |= res; 5017 } 5018 5019 if (state->whitespace_error) { 5020 if (state->squelch_whitespace_errors && 5021 state->squelch_whitespace_errors < state->whitespace_error) { 5022 int squelched = 5023 state->whitespace_error - state->squelch_whitespace_errors; 5024 warning(Q_("squelched %d whitespace error", 5025 "squelched %d whitespace errors", 5026 squelched), 5027 squelched); 5028 } 5029 if (state->ws_error_action == die_on_ws_error) { 5030 error(Q_("%d line adds whitespace errors.", 5031 "%d lines add whitespace errors.", 5032 state->whitespace_error), 5033 state->whitespace_error); 5034 res = -128; 5035 goto end; 5036 } 5037 if (state->applied_after_fixing_ws && state->apply) 5038 warning(Q_("%d line applied after" 5039 " fixing whitespace errors.", 5040 "%d lines applied after" 5041 " fixing whitespace errors.", 5042 state->applied_after_fixing_ws), 5043 state->applied_after_fixing_ws); 5044 else if (state->whitespace_error) 5045 warning(Q_("%d line adds whitespace errors.", 5046 "%d lines add whitespace errors.", 5047 state->whitespace_error), 5048 state->whitespace_error); 5049 } 5050 5051 if (state->update_index) { 5052 res = write_locked_index(state->repo->index, &state->lock_file, COMMIT_LOCK); 5053 if (res) { 5054 error(_("Unable to write new index file")); 5055 res = -128; 5056 goto end; 5057 } 5058 } 5059 5060 res = !!errs; 5061 5062end: 5063 rollback_lock_file(&state->lock_file); 5064 5065 if (state->apply_verbosity <= verbosity_silent) { 5066 set_error_routine(state->saved_error_routine); 5067 set_warn_routine(state->saved_warn_routine); 5068 } 5069 5070 if (res > -1) 5071 return res; 5072 return (res == -1 ? 1 : 128); 5073} 5074 5075int apply_parse_options(int argc, const char **argv, 5076 struct apply_state *state, 5077 int *force_apply, int *options, 5078 const char * const *apply_usage) 5079{ 5080 struct option builtin_apply_options[] = { 5081 OPT_CALLBACK_F(0, "exclude", state, N_("path"), 5082 N_("don't apply changes matching the given path"), 5083 PARSE_OPT_NONEG, apply_option_parse_exclude), 5084 OPT_CALLBACK_F(0, "include", state, N_("path"), 5085 N_("apply changes matching the given path"), 5086 PARSE_OPT_NONEG, apply_option_parse_include), 5087 OPT_CALLBACK('p', NULL, state, N_("num"), 5088 N_("remove <num> leading slashes from traditional diff paths"), 5089 apply_option_parse_p), 5090 OPT_BOOL(0, "no-add", &state->no_add, 5091 N_("ignore additions made by the patch")), 5092 OPT_BOOL(0, "stat", &state->diffstat, 5093 N_("instead of applying the patch, output diffstat for the input")), 5094 OPT_NOOP_NOARG(0, "allow-binary-replacement"), 5095 OPT_NOOP_NOARG(0, "binary"), 5096 OPT_BOOL(0, "numstat", &state->numstat, 5097 N_("show number of added and deleted lines in decimal notation")), 5098 OPT_BOOL(0, "summary", &state->summary, 5099 N_("instead of applying the patch, output a summary for the input")), 5100 OPT_BOOL(0, "check", &state->check, 5101 N_("instead of applying the patch, see if the patch is applicable")), 5102 OPT_BOOL(0, "index", &state->check_index, 5103 N_("make sure the patch is applicable to the current index")), 5104 OPT_BOOL('N', "intent-to-add", &state->ita_only, 5105 N_("mark new files with `git add --intent-to-add`")), 5106 OPT_BOOL(0, "cached", &state->cached, 5107 N_("apply a patch without touching the working tree")), 5108 OPT_BOOL_F(0, "unsafe-paths", &state->unsafe_paths, 5109 N_("accept a patch that touches outside the working area"), 5110 PARSE_OPT_NOCOMPLETE), 5111 OPT_BOOL(0, "apply", force_apply, 5112 N_("also apply the patch (use with --stat/--summary/--check)")), 5113 OPT_BOOL('3', "3way", &state->threeway, 5114 N_( "attempt three-way merge, fall back on normal patch if that fails")), 5115 OPT_SET_INT_F(0, "ours", &state->merge_variant, 5116 N_("for conflicts, use our version"), 5117 XDL_MERGE_FAVOR_OURS, PARSE_OPT_NONEG), 5118 OPT_SET_INT_F(0, "theirs", &state->merge_variant, 5119 N_("for conflicts, use their version"), 5120 XDL_MERGE_FAVOR_THEIRS, PARSE_OPT_NONEG), 5121 OPT_SET_INT_F(0, "union", &state->merge_variant, 5122 N_("for conflicts, use a union version"), 5123 XDL_MERGE_FAVOR_UNION, PARSE_OPT_NONEG), 5124 OPT_FILENAME(0, "build-fake-ancestor", &state->fake_ancestor, 5125 N_("build a temporary index based on embedded index information")), 5126 /* Think twice before adding "--nul" synonym to this */ 5127 OPT_SET_INT('z', NULL, &state->line_termination, 5128 N_("paths are separated with NUL character"), '\0'), 5129 OPT_UNSIGNED('C', NULL, &state->p_context, 5130 N_("ensure at least <n> lines of context match")), 5131 OPT_CALLBACK(0, "whitespace", state, N_("action"), 5132 N_("detect new or modified lines that have whitespace errors"), 5133 apply_option_parse_whitespace), 5134 OPT_CALLBACK_F(0, "ignore-space-change", state, NULL, 5135 N_("ignore changes in whitespace when finding context"), 5136 PARSE_OPT_NOARG, apply_option_parse_space_change), 5137 OPT_CALLBACK_F(0, "ignore-whitespace", state, NULL, 5138 N_("ignore changes in whitespace when finding context"), 5139 PARSE_OPT_NOARG, apply_option_parse_space_change), 5140 OPT_BOOL('R', "reverse", &state->apply_in_reverse, 5141 N_("apply the patch in reverse")), 5142 OPT_BOOL(0, "unidiff-zero", &state->unidiff_zero, 5143 N_("don't expect at least one line of context")), 5144 OPT_BOOL(0, "reject", &state->apply_with_reject, 5145 N_("leave the rejected hunks in corresponding *.rej files")), 5146 OPT_BOOL(0, "allow-overlap", &state->allow_overlap, 5147 N_("allow overlapping hunks")), 5148 OPT__VERBOSITY(&state->apply_verbosity), 5149 OPT_BIT(0, "inaccurate-eof", options, 5150 N_("tolerate incorrectly detected missing new-line at the end of file"), 5151 APPLY_OPT_INACCURATE_EOF), 5152 OPT_BIT(0, "recount", options, 5153 N_("do not trust the line counts in the hunk headers"), 5154 APPLY_OPT_RECOUNT), 5155 OPT_CALLBACK(0, "directory", state, N_("root"), 5156 N_("prepend <root> to all filenames"), 5157 apply_option_parse_directory), 5158 OPT_BOOL(0, "allow-empty", &state->allow_empty, 5159 N_("don't return error for empty patches")), 5160 OPT_END() 5161 }; 5162 5163 argc = parse_options(argc, argv, state->prefix, builtin_apply_options, apply_usage, 0); 5164 5165 if (state->merge_variant && !state->threeway) 5166 die(_("--ours, --theirs, and --union require --3way")); 5167 5168 return argc; 5169}