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