Git fork
at reftables-rust 6814 lines 193 kB view raw
1#define USE_THE_REPOSITORY_VARIABLE 2#define DISABLE_SIGN_COMPARE_WARNINGS 3 4#include "git-compat-util.h" 5#include "abspath.h" 6#include "advice.h" 7#include "config.h" 8#include "copy.h" 9#include "environment.h" 10#include "gettext.h" 11#include "hex.h" 12#include "lockfile.h" 13#include "dir.h" 14#include "object-file.h" 15#include "object-name.h" 16#include "odb.h" 17#include "object.h" 18#include "pager.h" 19#include "commit.h" 20#include "sequencer.h" 21#include "run-command.h" 22#include "hook.h" 23#include "utf8.h" 24#include "cache-tree.h" 25#include "diff.h" 26#include "path.h" 27#include "revision.h" 28#include "rerere.h" 29#include "merge.h" 30#include "merge-ort.h" 31#include "merge-ort-wrappers.h" 32#include "refs.h" 33#include "sparse-index.h" 34#include "strvec.h" 35#include "quote.h" 36#include "trailer.h" 37#include "log-tree.h" 38#include "wt-status.h" 39#include "hashmap.h" 40#include "notes-utils.h" 41#include "sigchain.h" 42#include "unpack-trees.h" 43#include "oidmap.h" 44#include "oidset.h" 45#include "commit-slab.h" 46#include "alias.h" 47#include "commit-reach.h" 48#include "rebase-interactive.h" 49#include "reset.h" 50#include "branch.h" 51 52#define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION" 53 54/* 55 * To accommodate common filesystem limitations, where the loose refs' file 56 * names must not exceed `NAME_MAX`, the labels generated by `git rebase 57 * --rebase-merges` need to be truncated if the corresponding commit subjects 58 * are too long. 59 * Add some margin to stay clear from reaching `NAME_MAX`. 60 */ 61#define GIT_MAX_LABEL_LENGTH ((NAME_MAX) - (LOCK_SUFFIX_LEN) - 16) 62 63static const char sign_off_header[] = "Signed-off-by: "; 64static const char cherry_picked_prefix[] = "(cherry picked from commit "; 65 66GIT_PATH_FUNC(git_path_commit_editmsg, "COMMIT_EDITMSG") 67 68static GIT_PATH_FUNC(git_path_seq_dir, "sequencer") 69 70static GIT_PATH_FUNC(git_path_todo_file, "sequencer/todo") 71static GIT_PATH_FUNC(git_path_opts_file, "sequencer/opts") 72static GIT_PATH_FUNC(git_path_head_file, "sequencer/head") 73static GIT_PATH_FUNC(git_path_abort_safety_file, "sequencer/abort-safety") 74 75static GIT_PATH_FUNC(rebase_path, "rebase-merge") 76/* 77 * The file containing rebase commands, comments, and empty lines. 78 * This file is created by "git rebase -i" then edited by the user. As 79 * the lines are processed, they are removed from the front of this 80 * file and written to the tail of 'done'. 81 */ 82GIT_PATH_FUNC(rebase_path_todo, "rebase-merge/git-rebase-todo") 83GIT_PATH_FUNC(rebase_path_todo_backup, "rebase-merge/git-rebase-todo.backup") 84 85GIT_PATH_FUNC(rebase_path_dropped, "rebase-merge/dropped") 86 87/* 88 * The rebase command lines that have already been processed. A line 89 * is moved here when it is first handled, before any associated user 90 * actions. 91 */ 92static GIT_PATH_FUNC(rebase_path_done, "rebase-merge/done") 93/* 94 * The file to keep track of how many commands were already processed (e.g. 95 * for the prompt). 96 */ 97static GIT_PATH_FUNC(rebase_path_msgnum, "rebase-merge/msgnum") 98/* 99 * The file to keep track of how many commands are to be processed in total 100 * (e.g. for the prompt). 101 */ 102static GIT_PATH_FUNC(rebase_path_msgtotal, "rebase-merge/end") 103/* 104 * The commit message that is planned to be used for any changes that 105 * need to be committed following a user interaction. 106 */ 107static GIT_PATH_FUNC(rebase_path_message, "rebase-merge/message") 108/* 109 * The file into which is accumulated the suggested commit message for 110 * squash/fixup commands. When the first of a series of squash/fixups 111 * is seen, the file is created and the commit message from the 112 * previous commit and from the first squash/fixup commit are written 113 * to it. The commit message for each subsequent squash/fixup commit 114 * is appended to the file as it is processed. 115 */ 116static GIT_PATH_FUNC(rebase_path_squash_msg, "rebase-merge/message-squash") 117/* 118 * If the current series of squash/fixups has not yet included a squash 119 * command, then this file exists and holds the commit message of the 120 * original "pick" commit. (If the series ends without a "squash" 121 * command, then this can be used as the commit message of the combined 122 * commit without opening the editor.) 123 */ 124static GIT_PATH_FUNC(rebase_path_fixup_msg, "rebase-merge/message-fixup") 125/* 126 * This file contains the list fixup/squash commands that have been 127 * accumulated into message-fixup or message-squash so far. 128 */ 129static GIT_PATH_FUNC(rebase_path_current_fixups, "rebase-merge/current-fixups") 130/* 131 * A script to set the GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL, and 132 * GIT_AUTHOR_DATE that will be used for the commit that is currently 133 * being rebased. 134 */ 135static GIT_PATH_FUNC(rebase_path_author_script, "rebase-merge/author-script") 136/* 137 * When an "edit" rebase command is being processed, the SHA1 of the 138 * commit to be edited is recorded in this file. When "git rebase 139 * --continue" is executed, if there are any staged changes then they 140 * will be amended to the HEAD commit, but only provided the HEAD 141 * commit is still the commit to be edited. When any other rebase 142 * command is processed, this file is deleted. 143 */ 144static GIT_PATH_FUNC(rebase_path_amend, "rebase-merge/amend") 145/* 146 * When we stop at a given patch via the "edit" command, this file contains 147 * the commit object name of the corresponding patch. 148 */ 149static GIT_PATH_FUNC(rebase_path_stopped_sha, "rebase-merge/stopped-sha") 150/* 151 * When we stop for the user to resolve conflicts this file contains 152 * the patch of the commit that is being picked. 153 */ 154static GIT_PATH_FUNC(rebase_path_patch, "rebase-merge/patch") 155/* 156 * For the post-rewrite hook, we make a list of rewritten commits and 157 * their new sha1s. The rewritten-pending list keeps the sha1s of 158 * commits that have been processed, but not committed yet, 159 * e.g. because they are waiting for a 'squash' command. 160 */ 161static GIT_PATH_FUNC(rebase_path_rewritten_list, "rebase-merge/rewritten-list") 162static GIT_PATH_FUNC(rebase_path_rewritten_pending, 163 "rebase-merge/rewritten-pending") 164 165/* 166 * The path of the file containing the OID of the "squash onto" commit, i.e. 167 * the dummy commit used for `reset [new root]`. 168 */ 169static GIT_PATH_FUNC(rebase_path_squash_onto, "rebase-merge/squash-onto") 170 171/* 172 * The path of the file listing refs that need to be deleted after the rebase 173 * finishes. This is used by the `label` command to record the need for cleanup. 174 */ 175static GIT_PATH_FUNC(rebase_path_refs_to_delete, "rebase-merge/refs-to-delete") 176 177/* 178 * The update-refs file stores a list of refs that will be updated at the end 179 * of the rebase sequence. The 'update-ref <ref>' commands in the todo file 180 * update the OIDs for the refs in this file, but the refs are not updated 181 * until the end of the rebase sequence. 182 * 183 * rebase_path_update_refs() returns the path to this file for a given 184 * worktree directory. For the current worktree, pass the_repository->gitdir. 185 */ 186static char *rebase_path_update_refs(const char *wt_git_dir) 187{ 188 return xstrfmt("%s/rebase-merge/update-refs", wt_git_dir); 189} 190 191/* 192 * The following files are written by git-rebase just after parsing the 193 * command-line. 194 */ 195static GIT_PATH_FUNC(rebase_path_gpg_sign_opt, "rebase-merge/gpg_sign_opt") 196static GIT_PATH_FUNC(rebase_path_cdate_is_adate, "rebase-merge/cdate_is_adate") 197static GIT_PATH_FUNC(rebase_path_ignore_date, "rebase-merge/ignore_date") 198static GIT_PATH_FUNC(rebase_path_orig_head, "rebase-merge/orig-head") 199static GIT_PATH_FUNC(rebase_path_verbose, "rebase-merge/verbose") 200static GIT_PATH_FUNC(rebase_path_quiet, "rebase-merge/quiet") 201static GIT_PATH_FUNC(rebase_path_signoff, "rebase-merge/signoff") 202static GIT_PATH_FUNC(rebase_path_head_name, "rebase-merge/head-name") 203static GIT_PATH_FUNC(rebase_path_onto, "rebase-merge/onto") 204static GIT_PATH_FUNC(rebase_path_autostash, "rebase-merge/autostash") 205static GIT_PATH_FUNC(rebase_path_strategy, "rebase-merge/strategy") 206static GIT_PATH_FUNC(rebase_path_strategy_opts, "rebase-merge/strategy_opts") 207static GIT_PATH_FUNC(rebase_path_allow_rerere_autoupdate, "rebase-merge/allow_rerere_autoupdate") 208static GIT_PATH_FUNC(rebase_path_reschedule_failed_exec, "rebase-merge/reschedule-failed-exec") 209static GIT_PATH_FUNC(rebase_path_no_reschedule_failed_exec, "rebase-merge/no-reschedule-failed-exec") 210static GIT_PATH_FUNC(rebase_path_drop_redundant_commits, "rebase-merge/drop_redundant_commits") 211static GIT_PATH_FUNC(rebase_path_keep_redundant_commits, "rebase-merge/keep_redundant_commits") 212 213/* 214 * A 'struct replay_ctx' represents the private state of the sequencer. 215 */ 216struct replay_ctx { 217 /* 218 * The commit message that will be used except at the end of a 219 * chain of fixup and squash commands. 220 */ 221 struct strbuf message; 222 /* 223 * The list of completed fixup and squash commands in the 224 * current chain. 225 */ 226 struct strbuf current_fixups; 227 /* 228 * The number of completed fixup and squash commands in the 229 * current chain. 230 */ 231 int current_fixup_count; 232 /* 233 * Whether message contains a commit message. 234 */ 235 unsigned have_message :1; 236}; 237 238struct replay_ctx* replay_ctx_new(void) 239{ 240 struct replay_ctx *ctx = xcalloc(1, sizeof(*ctx)); 241 242 strbuf_init(&ctx->current_fixups, 0); 243 strbuf_init(&ctx->message, 0); 244 245 return ctx; 246} 247 248/** 249 * A 'struct update_refs_record' represents a value in the update-refs 250 * list. We use a string_list to map refs to these (before, after) pairs. 251 */ 252struct update_ref_record { 253 struct object_id before; 254 struct object_id after; 255}; 256 257static struct update_ref_record *init_update_ref_record(const char *ref) 258{ 259 struct update_ref_record *rec; 260 261 CALLOC_ARRAY(rec, 1); 262 263 oidcpy(&rec->before, null_oid(the_hash_algo)); 264 oidcpy(&rec->after, null_oid(the_hash_algo)); 265 266 /* This may fail, but that's fine, we will keep the null OID. */ 267 refs_read_ref(get_main_ref_store(the_repository), ref, &rec->before); 268 269 return rec; 270} 271 272static int git_sequencer_config(const char *k, const char *v, 273 const struct config_context *ctx, void *cb) 274{ 275 struct replay_opts *opts = cb; 276 277 if (!strcmp(k, "commit.cleanup")) { 278 if (!v) 279 return config_error_nonbool(k); 280 281 if (!strcmp(v, "verbatim")) { 282 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE; 283 opts->explicit_cleanup = 1; 284 } else if (!strcmp(v, "whitespace")) { 285 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SPACE; 286 opts->explicit_cleanup = 1; 287 } else if (!strcmp(v, "strip")) { 288 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_ALL; 289 opts->explicit_cleanup = 1; 290 } else if (!strcmp(v, "scissors")) { 291 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SCISSORS; 292 opts->explicit_cleanup = 1; 293 } else { 294 warning(_("invalid commit message cleanup mode '%s'"), 295 v); 296 } 297 298 return 0; 299 } 300 301 if (!strcmp(k, "commit.gpgsign")) { 302 free(opts->gpg_sign); 303 opts->gpg_sign = git_config_bool(k, v) ? xstrdup("") : NULL; 304 return 0; 305 } 306 307 if (!opts->default_strategy && !strcmp(k, "pull.twohead")) { 308 int ret = git_config_string(&opts->default_strategy, k, v); 309 if (ret == 0) { 310 /* 311 * pull.twohead is allowed to be multi-valued; we only 312 * care about the first value. 313 */ 314 char *tmp = strchr(opts->default_strategy, ' '); 315 if (tmp) 316 *tmp = '\0'; 317 } 318 return ret; 319 } 320 321 if (opts->action == REPLAY_REVERT && !strcmp(k, "revert.reference")) 322 opts->commit_use_reference = git_config_bool(k, v); 323 324 return git_diff_basic_config(k, v, ctx, NULL); 325} 326 327void sequencer_init_config(struct replay_opts *opts) 328{ 329 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE; 330 repo_config(the_repository, git_sequencer_config, opts); 331} 332 333static inline int is_rebase_i(const struct replay_opts *opts) 334{ 335 return opts->action == REPLAY_INTERACTIVE_REBASE; 336} 337 338static const char *get_dir(const struct replay_opts *opts) 339{ 340 if (is_rebase_i(opts)) 341 return rebase_path(); 342 return git_path_seq_dir(); 343} 344 345static const char *get_todo_path(const struct replay_opts *opts) 346{ 347 if (is_rebase_i(opts)) 348 return rebase_path_todo(); 349 return git_path_todo_file(); 350} 351 352/* 353 * Returns 0 for non-conforming footer 354 * Returns 1 for conforming footer 355 * Returns 2 when sob exists within conforming footer 356 * Returns 3 when sob exists within conforming footer as last entry 357 */ 358static int has_conforming_footer(struct strbuf *sb, struct strbuf *sob, 359 size_t ignore_footer) 360{ 361 struct trailer_iterator iter; 362 size_t i = 0; 363 int found_sob = 0, found_sob_last = 0; 364 char saved_char; 365 366 if (ignore_footer) { 367 saved_char = sb->buf[sb->len - ignore_footer]; 368 sb->buf[sb->len - ignore_footer] = '\0'; 369 } 370 371 trailer_iterator_init(&iter, sb->buf); 372 373 if (ignore_footer) 374 sb->buf[sb->len - ignore_footer] = saved_char; 375 376 while (trailer_iterator_advance(&iter)) { 377 i++; 378 if (sob && !strncmp(iter.raw, sob->buf, sob->len)) 379 found_sob = i; 380 } 381 trailer_iterator_release(&iter); 382 383 if (!i) 384 return 0; 385 386 found_sob_last = (int)i == found_sob; 387 388 if (found_sob_last) 389 return 3; 390 if (found_sob) 391 return 2; 392 return 1; 393} 394 395static const char *gpg_sign_opt_quoted(struct replay_opts *opts) 396{ 397 static struct strbuf buf = STRBUF_INIT; 398 399 strbuf_reset(&buf); 400 if (opts->gpg_sign) 401 sq_quotef(&buf, "-S%s", opts->gpg_sign); 402 return buf.buf; 403} 404 405static void replay_ctx_release(struct replay_ctx *ctx) 406{ 407 strbuf_release(&ctx->current_fixups); 408 strbuf_release(&ctx->message); 409} 410 411void replay_opts_release(struct replay_opts *opts) 412{ 413 struct replay_ctx *ctx = opts->ctx; 414 415 free(opts->gpg_sign); 416 free(opts->reflog_action); 417 free(opts->default_strategy); 418 free(opts->strategy); 419 strvec_clear (&opts->xopts); 420 if (opts->revs) 421 release_revisions(opts->revs); 422 free(opts->revs); 423 replay_ctx_release(ctx); 424 free(opts->ctx); 425} 426 427int sequencer_remove_state(struct replay_opts *opts) 428{ 429 struct strbuf buf = STRBUF_INIT; 430 int ret = 0; 431 432 if (is_rebase_i(opts) && 433 strbuf_read_file(&buf, rebase_path_refs_to_delete(), 0) > 0) { 434 char *p = buf.buf; 435 while (*p) { 436 char *eol = strchr(p, '\n'); 437 if (eol) 438 *eol = '\0'; 439 if (refs_delete_ref(get_main_ref_store(the_repository), "(rebase) cleanup", p, NULL, 0) < 0) { 440 warning(_("could not delete '%s'"), p); 441 ret = -1; 442 } 443 if (!eol) 444 break; 445 p = eol + 1; 446 } 447 } 448 449 strbuf_reset(&buf); 450 strbuf_addstr(&buf, get_dir(opts)); 451 if (remove_dir_recursively(&buf, 0)) 452 ret = error(_("could not remove '%s'"), buf.buf); 453 strbuf_release(&buf); 454 455 return ret; 456} 457 458static const char *action_name(const struct replay_opts *opts) 459{ 460 switch (opts->action) { 461 case REPLAY_REVERT: 462 return N_("revert"); 463 case REPLAY_PICK: 464 return N_("cherry-pick"); 465 case REPLAY_INTERACTIVE_REBASE: 466 return N_("rebase"); 467 } 468 die(_("unknown action: %d"), opts->action); 469} 470 471struct commit_message { 472 char *parent_label; 473 char *label; 474 char *subject; 475 const char *message; 476}; 477 478static const char *short_commit_name(struct repository *r, struct commit *commit) 479{ 480 return repo_find_unique_abbrev(r, &commit->object.oid, DEFAULT_ABBREV); 481} 482 483static int get_message(struct commit *commit, struct commit_message *out) 484{ 485 const char *abbrev, *subject; 486 int subject_len; 487 488 out->message = repo_logmsg_reencode(the_repository, commit, NULL, 489 get_commit_output_encoding()); 490 abbrev = short_commit_name(the_repository, commit); 491 492 subject_len = find_commit_subject(out->message, &subject); 493 494 out->subject = xmemdupz(subject, subject_len); 495 out->label = xstrfmt("%s (%s)", abbrev, out->subject); 496 out->parent_label = xstrfmt("parent of %s", out->label); 497 498 return 0; 499} 500 501static void free_message(struct commit *commit, struct commit_message *msg) 502{ 503 free(msg->parent_label); 504 free(msg->label); 505 free(msg->subject); 506 repo_unuse_commit_buffer(the_repository, commit, msg->message); 507} 508 509const char *rebase_resolvemsg = 510N_("Resolve all conflicts manually, mark them as resolved with\n" 511"\"git add/rm <conflicted_files>\", then run \"git rebase --continue\".\n" 512"You can instead skip this commit: run \"git rebase --skip\".\n" 513"To abort and get back to the state before \"git rebase\", run " 514"\"git rebase --abort\"."); 515 516static void print_advice(struct repository *r, int show_hint, 517 struct replay_opts *opts) 518{ 519 const char *msg; 520 521 if (is_rebase_i(opts)) 522 msg = rebase_resolvemsg; 523 else 524 msg = getenv("GIT_CHERRY_PICK_HELP"); 525 526 if (msg) { 527 advise_if_enabled(ADVICE_MERGE_CONFLICT, "%s", msg); 528 /* 529 * A conflict has occurred but the porcelain 530 * (typically rebase --interactive) wants to take care 531 * of the commit itself so remove CHERRY_PICK_HEAD 532 */ 533 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD", 534 NULL, REF_NO_DEREF); 535 return; 536 } 537 538 if (show_hint) { 539 if (opts->no_commit) 540 advise_if_enabled(ADVICE_MERGE_CONFLICT, 541 _("after resolving the conflicts, mark the corrected paths\n" 542 "with 'git add <paths>' or 'git rm <paths>'")); 543 else if (opts->action == REPLAY_PICK) 544 advise_if_enabled(ADVICE_MERGE_CONFLICT, 545 _("After resolving the conflicts, mark them with\n" 546 "\"git add/rm <pathspec>\", then run\n" 547 "\"git cherry-pick --continue\".\n" 548 "You can instead skip this commit with \"git cherry-pick --skip\".\n" 549 "To abort and get back to the state before \"git cherry-pick\",\n" 550 "run \"git cherry-pick --abort\".")); 551 else if (opts->action == REPLAY_REVERT) 552 advise_if_enabled(ADVICE_MERGE_CONFLICT, 553 _("After resolving the conflicts, mark them with\n" 554 "\"git add/rm <pathspec>\", then run\n" 555 "\"git revert --continue\".\n" 556 "You can instead skip this commit with \"git revert --skip\".\n" 557 "To abort and get back to the state before \"git revert\",\n" 558 "run \"git revert --abort\".")); 559 else 560 BUG("unexpected pick action in print_advice()"); 561 } 562} 563 564static int write_message(const void *buf, size_t len, const char *filename, 565 int append_eol) 566{ 567 struct lock_file msg_file = LOCK_INIT; 568 569 int msg_fd = hold_lock_file_for_update(&msg_file, filename, 0); 570 if (msg_fd < 0) 571 return error_errno(_("could not lock '%s'"), filename); 572 if (write_in_full(msg_fd, buf, len) < 0) { 573 error_errno(_("could not write to '%s'"), filename); 574 rollback_lock_file(&msg_file); 575 return -1; 576 } 577 if (append_eol && write(msg_fd, "\n", 1) < 0) { 578 error_errno(_("could not write eol to '%s'"), filename); 579 rollback_lock_file(&msg_file); 580 return -1; 581 } 582 if (commit_lock_file(&msg_file) < 0) 583 return error(_("failed to finalize '%s'"), filename); 584 585 return 0; 586} 587 588int read_oneliner(struct strbuf *buf, 589 const char *path, unsigned flags) 590{ 591 int orig_len = buf->len; 592 593 if (strbuf_read_file(buf, path, 0) < 0) { 594 if ((flags & READ_ONELINER_WARN_MISSING) || 595 (errno != ENOENT && errno != ENOTDIR)) 596 warning_errno(_("could not read '%s'"), path); 597 return 0; 598 } 599 600 if (buf->len > orig_len && buf->buf[buf->len - 1] == '\n') { 601 if (--buf->len > orig_len && buf->buf[buf->len - 1] == '\r') 602 --buf->len; 603 buf->buf[buf->len] = '\0'; 604 } 605 606 if ((flags & READ_ONELINER_SKIP_IF_EMPTY) && buf->len == orig_len) 607 return 0; 608 609 return 1; 610} 611 612static struct tree *empty_tree(struct repository *r) 613{ 614 return lookup_tree(r, the_hash_algo->empty_tree); 615} 616 617static int error_dirty_index(struct repository *repo, struct replay_opts *opts) 618{ 619 if (repo_read_index_unmerged(repo)) 620 return error_resolve_conflict(action_name(opts)); 621 622 error(_("your local changes would be overwritten by %s."), 623 _(action_name(opts))); 624 625 if (advice_enabled(ADVICE_COMMIT_BEFORE_MERGE)) 626 advise(_("commit your changes or stash them to proceed.")); 627 return -1; 628} 629 630static void update_abort_safety_file(void) 631{ 632 struct object_id head; 633 634 /* Do nothing on a single-pick */ 635 if (!file_exists(git_path_seq_dir())) 636 return; 637 638 if (!repo_get_oid(the_repository, "HEAD", &head)) 639 write_file(git_path_abort_safety_file(), "%s", oid_to_hex(&head)); 640 else 641 write_file(git_path_abort_safety_file(), "%s", ""); 642} 643 644static int fast_forward_to(struct repository *r, 645 const struct object_id *to, 646 const struct object_id *from, 647 int unborn, 648 struct replay_opts *opts) 649{ 650 struct ref_transaction *transaction; 651 struct strbuf sb = STRBUF_INIT; 652 struct strbuf err = STRBUF_INIT; 653 654 repo_read_index(r); 655 if (checkout_fast_forward(r, from, to, 1)) 656 return -1; /* the callee should have complained already */ 657 658 strbuf_addf(&sb, "%s: fast-forward", action_name(opts)); 659 660 transaction = ref_store_transaction_begin(get_main_ref_store(the_repository), 661 0, &err); 662 if (!transaction || 663 ref_transaction_update(transaction, "HEAD", 664 to, unborn && !is_rebase_i(opts) ? 665 null_oid(the_hash_algo) : from, NULL, NULL, 666 0, sb.buf, &err) || 667 ref_transaction_commit(transaction, &err)) { 668 ref_transaction_free(transaction); 669 error("%s", err.buf); 670 strbuf_release(&sb); 671 strbuf_release(&err); 672 return -1; 673 } 674 675 strbuf_release(&sb); 676 strbuf_release(&err); 677 ref_transaction_free(transaction); 678 update_abort_safety_file(); 679 return 0; 680} 681 682enum commit_msg_cleanup_mode get_cleanup_mode(const char *cleanup_arg, 683 int use_editor) 684{ 685 if (!cleanup_arg || !strcmp(cleanup_arg, "default")) 686 return use_editor ? COMMIT_MSG_CLEANUP_ALL : 687 COMMIT_MSG_CLEANUP_SPACE; 688 else if (!strcmp(cleanup_arg, "verbatim")) 689 return COMMIT_MSG_CLEANUP_NONE; 690 else if (!strcmp(cleanup_arg, "whitespace")) 691 return COMMIT_MSG_CLEANUP_SPACE; 692 else if (!strcmp(cleanup_arg, "strip")) 693 return COMMIT_MSG_CLEANUP_ALL; 694 else if (!strcmp(cleanup_arg, "scissors")) 695 return use_editor ? COMMIT_MSG_CLEANUP_SCISSORS : 696 COMMIT_MSG_CLEANUP_SPACE; 697 else 698 die(_("Invalid cleanup mode %s"), cleanup_arg); 699} 700 701/* 702 * NB using int rather than enum cleanup_mode to stop clang's 703 * -Wtautological-constant-out-of-range-compare complaining that the comparison 704 * is always true. 705 */ 706static const char *describe_cleanup_mode(int cleanup_mode) 707{ 708 static const char *modes[] = { "whitespace", 709 "verbatim", 710 "scissors", 711 "strip" }; 712 713 if (cleanup_mode < ARRAY_SIZE(modes)) 714 return modes[cleanup_mode]; 715 716 BUG("invalid cleanup_mode provided (%d)", cleanup_mode); 717} 718 719void append_conflicts_hint(struct index_state *istate, 720 struct strbuf *msgbuf, enum commit_msg_cleanup_mode cleanup_mode) 721{ 722 int i; 723 724 if (cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS) { 725 strbuf_addch(msgbuf, '\n'); 726 wt_status_append_cut_line(msgbuf); 727 strbuf_addstr(msgbuf, comment_line_str); 728 } 729 730 strbuf_addch(msgbuf, '\n'); 731 strbuf_commented_addf(msgbuf, comment_line_str, "Conflicts:\n"); 732 for (i = 0; i < istate->cache_nr;) { 733 const struct cache_entry *ce = istate->cache[i++]; 734 if (ce_stage(ce)) { 735 strbuf_commented_addf(msgbuf, comment_line_str, 736 "\t%s\n", ce->name); 737 while (i < istate->cache_nr && 738 !strcmp(ce->name, istate->cache[i]->name)) 739 i++; 740 } 741 } 742} 743 744static int do_recursive_merge(struct repository *r, 745 struct commit *base, struct commit *next, 746 const char *base_label, const char *next_label, 747 struct object_id *head, struct strbuf *msgbuf, 748 struct replay_opts *opts) 749{ 750 struct merge_options o; 751 struct merge_result result; 752 struct tree *next_tree, *base_tree, *head_tree; 753 int clean, show_output; 754 int i; 755 struct lock_file index_lock = LOCK_INIT; 756 757 if (repo_hold_locked_index(r, &index_lock, LOCK_REPORT_ON_ERROR) < 0) 758 return -1; 759 760 repo_read_index(r); 761 762 init_ui_merge_options(&o, r); 763 o.ancestor = base ? base_label : "(empty tree)"; 764 o.branch1 = "HEAD"; 765 o.branch2 = next ? next_label : "(empty tree)"; 766 if (is_rebase_i(opts)) 767 o.buffer_output = 2; 768 o.show_rename_progress = 1; 769 770 head_tree = parse_tree_indirect(head); 771 if (!head_tree) 772 return error(_("unable to read tree (%s)"), oid_to_hex(head)); 773 next_tree = next ? repo_get_commit_tree(r, next) : empty_tree(r); 774 base_tree = base ? repo_get_commit_tree(r, base) : empty_tree(r); 775 776 for (i = 0; i < opts->xopts.nr; i++) 777 parse_merge_opt(&o, opts->xopts.v[i]); 778 779 memset(&result, 0, sizeof(result)); 780 merge_incore_nonrecursive(&o, base_tree, head_tree, next_tree, &result); 781 show_output = !is_rebase_i(opts) || !result.clean; 782 /* 783 * TODO: merge_switch_to_result will update index/working tree; 784 * we only really want to do that if !result.clean || this is 785 * the final patch to be picked. But determining this is the 786 * final patch would take some work, and "head_tree" would need 787 * to be replace with the tree the index matched before we 788 * started doing any picks. 789 */ 790 merge_switch_to_result(&o, head_tree, &result, 1, show_output); 791 clean = result.clean; 792 if (clean < 0) { 793 rollback_lock_file(&index_lock); 794 return clean; 795 } 796 797 if (write_locked_index(r->index, &index_lock, 798 COMMIT_LOCK | SKIP_IF_UNCHANGED)) 799 /* 800 * TRANSLATORS: %s will be "revert", "cherry-pick" or 801 * "rebase". 802 */ 803 return error(_("%s: Unable to write new index file"), 804 _(action_name(opts))); 805 806 if (!clean) 807 append_conflicts_hint(r->index, msgbuf, 808 opts->default_msg_cleanup); 809 810 return !clean; 811} 812 813static struct object_id *get_cache_tree_oid(struct index_state *istate) 814{ 815 if (!cache_tree_fully_valid(istate->cache_tree)) 816 if (cache_tree_update(istate, 0)) { 817 error(_("unable to update cache tree")); 818 return NULL; 819 } 820 821 return &istate->cache_tree->oid; 822} 823 824static int is_index_unchanged(struct repository *r) 825{ 826 struct object_id head_oid, *cache_tree_oid; 827 const struct object_id *head_tree_oid; 828 struct commit *head_commit; 829 struct index_state *istate = r->index; 830 const char *head_name; 831 832 if (!refs_resolve_ref_unsafe(get_main_ref_store(the_repository), "HEAD", RESOLVE_REF_READING, &head_oid, NULL)) { 833 /* Check to see if this is an unborn branch */ 834 head_name = refs_resolve_ref_unsafe(get_main_ref_store(the_repository), 835 "HEAD", 836 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE, 837 &head_oid, NULL); 838 if (!head_name || 839 !starts_with(head_name, "refs/heads/") || 840 !is_null_oid(&head_oid)) 841 return error(_("could not resolve HEAD commit")); 842 head_tree_oid = the_hash_algo->empty_tree; 843 } else { 844 head_commit = lookup_commit(r, &head_oid); 845 846 /* 847 * If head_commit is NULL, check_commit, called from 848 * lookup_commit, would have indicated that head_commit is not 849 * a commit object already. repo_parse_commit() will return failure 850 * without further complaints in such a case. Otherwise, if 851 * the commit is invalid, repo_parse_commit() will complain. So 852 * there is nothing for us to say here. Just return failure. 853 */ 854 if (repo_parse_commit(r, head_commit)) 855 return -1; 856 857 head_tree_oid = get_commit_tree_oid(head_commit); 858 } 859 860 if (!(cache_tree_oid = get_cache_tree_oid(istate))) 861 return -1; 862 863 return oideq(cache_tree_oid, head_tree_oid); 864} 865 866static int write_author_script(const char *message) 867{ 868 struct strbuf buf = STRBUF_INIT; 869 const char *eol; 870 int res; 871 872 for (;;) 873 if (!*message || starts_with(message, "\n")) { 874missing_author: 875 /* Missing 'author' line? */ 876 unlink(rebase_path_author_script()); 877 return 0; 878 } else if (skip_prefix(message, "author ", &message)) 879 break; 880 else if ((eol = strchr(message, '\n'))) 881 message = eol + 1; 882 else 883 goto missing_author; 884 885 strbuf_addstr(&buf, "GIT_AUTHOR_NAME='"); 886 while (*message && *message != '\n' && *message != '\r') 887 if (skip_prefix(message, " <", &message)) 888 break; 889 else if (*message != '\'') 890 strbuf_addch(&buf, *(message++)); 891 else 892 strbuf_addf(&buf, "'\\%c'", *(message++)); 893 strbuf_addstr(&buf, "'\nGIT_AUTHOR_EMAIL='"); 894 while (*message && *message != '\n' && *message != '\r') 895 if (skip_prefix(message, "> ", &message)) 896 break; 897 else if (*message != '\'') 898 strbuf_addch(&buf, *(message++)); 899 else 900 strbuf_addf(&buf, "'\\%c'", *(message++)); 901 strbuf_addstr(&buf, "'\nGIT_AUTHOR_DATE='@"); 902 while (*message && *message != '\n' && *message != '\r') 903 if (*message != '\'') 904 strbuf_addch(&buf, *(message++)); 905 else 906 strbuf_addf(&buf, "'\\%c'", *(message++)); 907 strbuf_addch(&buf, '\''); 908 res = write_message(buf.buf, buf.len, rebase_path_author_script(), 1); 909 strbuf_release(&buf); 910 return res; 911} 912 913/** 914 * Take a series of KEY='VALUE' lines where VALUE part is 915 * sq-quoted, and append <KEY, VALUE> at the end of the string list 916 */ 917static int parse_key_value_squoted(char *buf, struct string_list *list) 918{ 919 while (*buf) { 920 struct string_list_item *item; 921 char *np; 922 char *cp = strchr(buf, '='); 923 if (!cp) { 924 np = strchrnul(buf, '\n'); 925 return error(_("no key present in '%.*s'"), 926 (int) (np - buf), buf); 927 } 928 np = strchrnul(cp, '\n'); 929 *cp++ = '\0'; 930 item = string_list_append(list, buf); 931 932 buf = np + (*np == '\n'); 933 *np = '\0'; 934 cp = sq_dequote(cp); 935 if (!cp) 936 return error(_("unable to dequote value of '%s'"), 937 item->string); 938 item->util = xstrdup(cp); 939 } 940 return 0; 941} 942 943/** 944 * Reads and parses the state directory's "author-script" file, and sets name, 945 * email and date accordingly. 946 * Returns 0 on success, -1 if the file could not be parsed. 947 * 948 * The author script is of the format: 949 * 950 * GIT_AUTHOR_NAME='$author_name' 951 * GIT_AUTHOR_EMAIL='$author_email' 952 * GIT_AUTHOR_DATE='$author_date' 953 * 954 * where $author_name, $author_email and $author_date are quoted. We are strict 955 * with our parsing, as the file was meant to be eval'd in the now-removed 956 * git-am.sh/git-rebase--interactive.sh scripts, and thus if the file differs 957 * from what this function expects, it is better to bail out than to do 958 * something that the user does not expect. 959 */ 960int read_author_script(const char *path, char **name, char **email, char **date, 961 int allow_missing) 962{ 963 struct strbuf buf = STRBUF_INIT; 964 struct string_list kv = STRING_LIST_INIT_DUP; 965 int retval = -1; /* assume failure */ 966 int i, name_i = -2, email_i = -2, date_i = -2, err = 0; 967 968 if (strbuf_read_file(&buf, path, 256) <= 0) { 969 strbuf_release(&buf); 970 if (errno == ENOENT && allow_missing) 971 return 0; 972 else 973 return error_errno(_("could not open '%s' for reading"), 974 path); 975 } 976 977 if (parse_key_value_squoted(buf.buf, &kv)) 978 goto finish; 979 980 for (i = 0; i < kv.nr; i++) { 981 if (!strcmp(kv.items[i].string, "GIT_AUTHOR_NAME")) { 982 if (name_i != -2) 983 name_i = error(_("'GIT_AUTHOR_NAME' already given")); 984 else 985 name_i = i; 986 } else if (!strcmp(kv.items[i].string, "GIT_AUTHOR_EMAIL")) { 987 if (email_i != -2) 988 email_i = error(_("'GIT_AUTHOR_EMAIL' already given")); 989 else 990 email_i = i; 991 } else if (!strcmp(kv.items[i].string, "GIT_AUTHOR_DATE")) { 992 if (date_i != -2) 993 date_i = error(_("'GIT_AUTHOR_DATE' already given")); 994 else 995 date_i = i; 996 } else { 997 err = error(_("unknown variable '%s'"), 998 kv.items[i].string); 999 } 1000 } 1001 if (name_i == -2) 1002 error(_("missing 'GIT_AUTHOR_NAME'")); 1003 if (email_i == -2) 1004 error(_("missing 'GIT_AUTHOR_EMAIL'")); 1005 if (date_i == -2) 1006 error(_("missing 'GIT_AUTHOR_DATE'")); 1007 if (name_i < 0 || email_i < 0 || date_i < 0 || err) 1008 goto finish; 1009 *name = kv.items[name_i].util; 1010 *email = kv.items[email_i].util; 1011 *date = kv.items[date_i].util; 1012 retval = 0; 1013finish: 1014 string_list_clear(&kv, !!retval); 1015 strbuf_release(&buf); 1016 return retval; 1017} 1018 1019/* 1020 * Read a GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL AND GIT_AUTHOR_DATE from a 1021 * file with shell quoting into struct strvec. Returns -1 on 1022 * error, 0 otherwise. 1023 */ 1024static int read_env_script(struct strvec *env) 1025{ 1026 char *name, *email, *date; 1027 1028 if (read_author_script(rebase_path_author_script(), 1029 &name, &email, &date, 0)) 1030 return -1; 1031 1032 strvec_pushf(env, "GIT_AUTHOR_NAME=%s", name); 1033 strvec_pushf(env, "GIT_AUTHOR_EMAIL=%s", email); 1034 strvec_pushf(env, "GIT_AUTHOR_DATE=%s", date); 1035 free(name); 1036 free(email); 1037 free(date); 1038 1039 return 0; 1040} 1041 1042static char *get_author(const char *message) 1043{ 1044 size_t len; 1045 const char *a; 1046 1047 a = find_commit_header(message, "author", &len); 1048 if (a) 1049 return xmemdupz(a, len); 1050 1051 return NULL; 1052} 1053 1054static const char *author_date_from_env(const struct strvec *env) 1055{ 1056 int i; 1057 const char *date; 1058 1059 for (i = 0; i < env->nr; i++) 1060 if (skip_prefix(env->v[i], 1061 "GIT_AUTHOR_DATE=", &date)) 1062 return date; 1063 /* 1064 * If GIT_AUTHOR_DATE is missing we should have already errored out when 1065 * reading the script 1066 */ 1067 BUG("GIT_AUTHOR_DATE missing from author script"); 1068} 1069 1070static const char staged_changes_advice[] = 1071N_("you have staged changes in your working tree\n" 1072"If these changes are meant to be squashed into the previous commit, run:\n" 1073"\n" 1074" git commit --amend %s\n" 1075"\n" 1076"If they are meant to go into a new commit, run:\n" 1077"\n" 1078" git commit %s\n" 1079"\n" 1080"In both cases, once you're done, continue with:\n" 1081"\n" 1082" git rebase --continue\n"); 1083 1084#define ALLOW_EMPTY (1<<0) 1085#define EDIT_MSG (1<<1) 1086#define AMEND_MSG (1<<2) 1087#define CLEANUP_MSG (1<<3) 1088#define VERIFY_MSG (1<<4) 1089#define CREATE_ROOT_COMMIT (1<<5) 1090 1091static int run_command_silent_on_success(struct child_process *cmd) 1092{ 1093 struct strbuf buf = STRBUF_INIT; 1094 int rc; 1095 1096 cmd->stdout_to_stderr = 1; 1097 rc = pipe_command(cmd, 1098 NULL, 0, 1099 NULL, 0, 1100 &buf, 0); 1101 1102 if (rc) 1103 fputs(buf.buf, stderr); 1104 strbuf_release(&buf); 1105 return rc; 1106} 1107 1108/* 1109 * If we are cherry-pick, and if the merge did not result in 1110 * hand-editing, we will hit this commit and inherit the original 1111 * author date and name. 1112 * 1113 * If we are revert, or if our cherry-pick results in a hand merge, 1114 * we had better say that the current user is responsible for that. 1115 * 1116 * An exception is when run_git_commit() is called during an 1117 * interactive rebase: in that case, we will want to retain the 1118 * author metadata. 1119 */ 1120static int run_git_commit(const char *defmsg, 1121 const char *reflog_action, 1122 struct replay_opts *opts, 1123 unsigned int flags) 1124{ 1125 struct child_process cmd = CHILD_PROCESS_INIT; 1126 1127 cmd.git_cmd = 1; 1128 1129 if (is_rebase_i(opts) && 1130 ((opts->committer_date_is_author_date && !opts->ignore_date) || 1131 !(!defmsg && (flags & AMEND_MSG))) && 1132 read_env_script(&cmd.env)) { 1133 const char *gpg_opt = gpg_sign_opt_quoted(opts); 1134 1135 return error(_(staged_changes_advice), 1136 gpg_opt, gpg_opt); 1137 } 1138 1139 strvec_pushf(&cmd.env, GIT_REFLOG_ACTION "=%s", reflog_action); 1140 1141 if (opts->committer_date_is_author_date) 1142 strvec_pushf(&cmd.env, "GIT_COMMITTER_DATE=%s", 1143 opts->ignore_date ? 1144 "" : 1145 author_date_from_env(&cmd.env)); 1146 if (opts->ignore_date) 1147 strvec_push(&cmd.env, "GIT_AUTHOR_DATE="); 1148 1149 strvec_push(&cmd.args, "commit"); 1150 1151 if (!(flags & VERIFY_MSG)) 1152 strvec_push(&cmd.args, "-n"); 1153 if ((flags & AMEND_MSG)) 1154 strvec_push(&cmd.args, "--amend"); 1155 if (opts->gpg_sign) 1156 strvec_pushf(&cmd.args, "-S%s", opts->gpg_sign); 1157 else 1158 strvec_push(&cmd.args, "--no-gpg-sign"); 1159 if (defmsg) 1160 strvec_pushl(&cmd.args, "-F", defmsg, NULL); 1161 else if (!(flags & EDIT_MSG)) 1162 strvec_pushl(&cmd.args, "-C", "HEAD", NULL); 1163 if ((flags & CLEANUP_MSG)) 1164 strvec_push(&cmd.args, "--cleanup=strip"); 1165 if ((flags & EDIT_MSG)) 1166 strvec_push(&cmd.args, "-e"); 1167 else if (!(flags & CLEANUP_MSG) && 1168 !opts->signoff && !opts->record_origin && 1169 !opts->explicit_cleanup) 1170 strvec_push(&cmd.args, "--cleanup=verbatim"); 1171 1172 if ((flags & ALLOW_EMPTY)) 1173 strvec_push(&cmd.args, "--allow-empty"); 1174 1175 if (!(flags & EDIT_MSG)) 1176 strvec_push(&cmd.args, "--allow-empty-message"); 1177 1178 if (is_rebase_i(opts) && !(flags & EDIT_MSG)) 1179 return run_command_silent_on_success(&cmd); 1180 else 1181 return run_command(&cmd); 1182} 1183 1184static int rest_is_empty(const struct strbuf *sb, int start) 1185{ 1186 int i, eol; 1187 const char *nl; 1188 1189 /* Check if the rest is just whitespace and Signed-off-by's. */ 1190 for (i = start; i < sb->len; i++) { 1191 nl = memchr(sb->buf + i, '\n', sb->len - i); 1192 if (nl) 1193 eol = nl - sb->buf; 1194 else 1195 eol = sb->len; 1196 1197 if (strlen(sign_off_header) <= eol - i && 1198 starts_with(sb->buf + i, sign_off_header)) { 1199 i = eol; 1200 continue; 1201 } 1202 while (i < eol) 1203 if (!isspace(sb->buf[i++])) 1204 return 0; 1205 } 1206 1207 return 1; 1208} 1209 1210void cleanup_message(struct strbuf *msgbuf, 1211 enum commit_msg_cleanup_mode cleanup_mode, int verbose) 1212{ 1213 if (verbose || /* Truncate the message just before the diff, if any. */ 1214 cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS) 1215 strbuf_setlen(msgbuf, wt_status_locate_end(msgbuf->buf, msgbuf->len)); 1216 if (cleanup_mode != COMMIT_MSG_CLEANUP_NONE) 1217 strbuf_stripspace(msgbuf, 1218 cleanup_mode == COMMIT_MSG_CLEANUP_ALL ? comment_line_str : NULL); 1219} 1220 1221/* 1222 * Find out if the message in the strbuf contains only whitespace and 1223 * Signed-off-by lines. 1224 */ 1225int message_is_empty(const struct strbuf *sb, 1226 enum commit_msg_cleanup_mode cleanup_mode) 1227{ 1228 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len) 1229 return 0; 1230 return rest_is_empty(sb, 0); 1231} 1232 1233/* 1234 * See if the user edited the message in the editor or left what 1235 * was in the template intact 1236 */ 1237int template_untouched(const struct strbuf *sb, const char *template_file, 1238 enum commit_msg_cleanup_mode cleanup_mode) 1239{ 1240 struct strbuf tmpl = STRBUF_INIT; 1241 const char *start; 1242 1243 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len) 1244 return 0; 1245 1246 if (!template_file || strbuf_read_file(&tmpl, template_file, 0) <= 0) 1247 return 0; 1248 1249 strbuf_stripspace(&tmpl, 1250 cleanup_mode == COMMIT_MSG_CLEANUP_ALL ? comment_line_str : NULL); 1251 if (!skip_prefix(sb->buf, tmpl.buf, &start)) 1252 start = sb->buf; 1253 strbuf_release(&tmpl); 1254 return rest_is_empty(sb, start - sb->buf); 1255} 1256 1257int update_head_with_reflog(const struct commit *old_head, 1258 const struct object_id *new_head, 1259 const char *action, const struct strbuf *msg, 1260 struct strbuf *err) 1261{ 1262 struct ref_transaction *transaction; 1263 struct strbuf sb = STRBUF_INIT; 1264 const char *nl; 1265 int ret = 0; 1266 1267 if (action) { 1268 strbuf_addstr(&sb, action); 1269 strbuf_addstr(&sb, ": "); 1270 } 1271 1272 nl = strchr(msg->buf, '\n'); 1273 if (nl) { 1274 strbuf_add(&sb, msg->buf, nl + 1 - msg->buf); 1275 } else { 1276 strbuf_addbuf(&sb, msg); 1277 strbuf_addch(&sb, '\n'); 1278 } 1279 1280 transaction = ref_store_transaction_begin(get_main_ref_store(the_repository), 1281 0, err); 1282 if (!transaction || 1283 ref_transaction_update(transaction, "HEAD", new_head, 1284 old_head ? &old_head->object.oid : null_oid(the_hash_algo), 1285 NULL, NULL, 0, sb.buf, err) || 1286 ref_transaction_commit(transaction, err)) { 1287 ret = -1; 1288 } 1289 ref_transaction_free(transaction); 1290 strbuf_release(&sb); 1291 1292 return ret; 1293} 1294 1295static int run_rewrite_hook(const struct object_id *oldoid, 1296 const struct object_id *newoid) 1297{ 1298 struct child_process proc = CHILD_PROCESS_INIT; 1299 int code; 1300 struct strbuf sb = STRBUF_INIT; 1301 const char *hook_path = find_hook(the_repository, "post-rewrite"); 1302 1303 if (!hook_path) 1304 return 0; 1305 1306 strvec_pushl(&proc.args, hook_path, "amend", NULL); 1307 proc.in = -1; 1308 proc.stdout_to_stderr = 1; 1309 proc.trace2_hook_name = "post-rewrite"; 1310 1311 code = start_command(&proc); 1312 if (code) 1313 return code; 1314 strbuf_addf(&sb, "%s %s\n", oid_to_hex(oldoid), oid_to_hex(newoid)); 1315 sigchain_push(SIGPIPE, SIG_IGN); 1316 write_in_full(proc.in, sb.buf, sb.len); 1317 close(proc.in); 1318 strbuf_release(&sb); 1319 sigchain_pop(SIGPIPE); 1320 return finish_command(&proc); 1321} 1322 1323void commit_post_rewrite(struct repository *r, 1324 const struct commit *old_head, 1325 const struct object_id *new_head) 1326{ 1327 struct notes_rewrite_cfg *cfg; 1328 1329 cfg = init_copy_notes_for_rewrite("amend"); 1330 if (cfg) { 1331 /* we are amending, so old_head is not NULL */ 1332 copy_note_for_rewrite(cfg, &old_head->object.oid, new_head); 1333 finish_copy_notes_for_rewrite(r, cfg, "Notes added by 'git commit --amend'"); 1334 } 1335 run_rewrite_hook(&old_head->object.oid, new_head); 1336} 1337 1338static int run_prepare_commit_msg_hook(struct repository *r, 1339 struct strbuf *msg, 1340 const char *commit) 1341{ 1342 int ret = 0; 1343 const char *name, *arg1 = NULL, *arg2 = NULL; 1344 1345 name = git_path_commit_editmsg(); 1346 if (write_message(msg->buf, msg->len, name, 0)) 1347 return -1; 1348 1349 if (commit) { 1350 arg1 = "commit"; 1351 arg2 = commit; 1352 } else { 1353 arg1 = "message"; 1354 } 1355 if (run_commit_hook(0, r->index_file, NULL, "prepare-commit-msg", name, 1356 arg1, arg2, NULL)) 1357 ret = error(_("'prepare-commit-msg' hook failed")); 1358 1359 return ret; 1360} 1361 1362static const char implicit_ident_advice_noconfig[] = 1363N_("Your name and email address were configured automatically based\n" 1364"on your username and hostname. Please check that they are accurate.\n" 1365"You can suppress this message by setting them explicitly. Run the\n" 1366"following command and follow the instructions in your editor to edit\n" 1367"your configuration file:\n" 1368"\n" 1369" git config --global --edit\n" 1370"\n" 1371"After doing this, you may fix the identity used for this commit with:\n" 1372"\n" 1373" git commit --amend --reset-author\n"); 1374 1375static const char implicit_ident_advice_config[] = 1376N_("Your name and email address were configured automatically based\n" 1377"on your username and hostname. Please check that they are accurate.\n" 1378"You can suppress this message by setting them explicitly:\n" 1379"\n" 1380" git config --global user.name \"Your Name\"\n" 1381" git config --global user.email you@example.com\n" 1382"\n" 1383"After doing this, you may fix the identity used for this commit with:\n" 1384"\n" 1385" git commit --amend --reset-author\n"); 1386 1387static const char *implicit_ident_advice(void) 1388{ 1389 char *user_config = interpolate_path("~/.gitconfig", 0); 1390 char *xdg_config = xdg_config_home("config"); 1391 int config_exists = file_exists(user_config) || file_exists(xdg_config); 1392 1393 free(user_config); 1394 free(xdg_config); 1395 1396 if (config_exists) 1397 return _(implicit_ident_advice_config); 1398 else 1399 return _(implicit_ident_advice_noconfig); 1400 1401} 1402 1403void print_commit_summary(struct repository *r, 1404 const char *prefix, 1405 const struct object_id *oid, 1406 unsigned int flags) 1407{ 1408 struct rev_info rev; 1409 struct commit *commit; 1410 struct strbuf format = STRBUF_INIT; 1411 const char *head; 1412 struct pretty_print_context pctx = {0}; 1413 struct strbuf author_ident = STRBUF_INIT; 1414 struct strbuf committer_ident = STRBUF_INIT; 1415 struct ref_store *refs; 1416 1417 commit = lookup_commit(r, oid); 1418 if (!commit) 1419 die(_("couldn't look up newly created commit")); 1420 if (repo_parse_commit(r, commit)) 1421 die(_("could not parse newly created commit")); 1422 1423 strbuf_addstr(&format, "format:%h] %s"); 1424 1425 repo_format_commit_message(r, commit, "%an <%ae>", &author_ident, 1426 &pctx); 1427 repo_format_commit_message(r, commit, "%cn <%ce>", &committer_ident, 1428 &pctx); 1429 if (strbuf_cmp(&author_ident, &committer_ident)) { 1430 strbuf_addstr(&format, "\n Author: "); 1431 strbuf_addbuf_percentquote(&format, &author_ident); 1432 } 1433 if (flags & SUMMARY_SHOW_AUTHOR_DATE) { 1434 struct strbuf date = STRBUF_INIT; 1435 1436 repo_format_commit_message(r, commit, "%ad", &date, &pctx); 1437 strbuf_addstr(&format, "\n Date: "); 1438 strbuf_addbuf_percentquote(&format, &date); 1439 strbuf_release(&date); 1440 } 1441 if (!committer_ident_sufficiently_given()) { 1442 strbuf_addstr(&format, "\n Committer: "); 1443 strbuf_addbuf_percentquote(&format, &committer_ident); 1444 if (advice_enabled(ADVICE_IMPLICIT_IDENTITY)) { 1445 strbuf_addch(&format, '\n'); 1446 strbuf_addstr(&format, implicit_ident_advice()); 1447 } 1448 } 1449 strbuf_release(&author_ident); 1450 strbuf_release(&committer_ident); 1451 1452 repo_init_revisions(r, &rev, prefix); 1453 setup_revisions(0, NULL, &rev, NULL); 1454 1455 rev.diff = 1; 1456 rev.diffopt.output_format = 1457 DIFF_FORMAT_SHORTSTAT | DIFF_FORMAT_SUMMARY; 1458 1459 rev.verbose_header = 1; 1460 rev.show_root_diff = 1; 1461 get_commit_format(format.buf, &rev); 1462 rev.always_show_header = 0; 1463 rev.diffopt.detect_rename = DIFF_DETECT_RENAME; 1464 diff_setup_done(&rev.diffopt); 1465 1466 refs = get_main_ref_store(r); 1467 head = refs_resolve_ref_unsafe(refs, "HEAD", 0, NULL, NULL); 1468 if (!head) 1469 die(_("unable to resolve HEAD after creating commit")); 1470 if (!strcmp(head, "HEAD")) 1471 head = _("detached HEAD"); 1472 else 1473 skip_prefix(head, "refs/heads/", &head); 1474 printf("[%s%s ", head, (flags & SUMMARY_INITIAL_COMMIT) ? 1475 _(" (root-commit)") : ""); 1476 1477 if (!log_tree_commit(&rev, commit)) { 1478 rev.always_show_header = 1; 1479 rev.use_terminator = 1; 1480 log_tree_commit(&rev, commit); 1481 } 1482 1483 release_revisions(&rev); 1484 strbuf_release(&format); 1485} 1486 1487static int parse_head(struct repository *r, struct commit **head) 1488{ 1489 struct commit *current_head; 1490 struct object_id oid; 1491 1492 if (repo_get_oid(r, "HEAD", &oid)) { 1493 current_head = NULL; 1494 } else { 1495 current_head = lookup_commit_reference(r, &oid); 1496 if (!current_head) 1497 return error(_("could not parse HEAD")); 1498 if (!oideq(&oid, &current_head->object.oid)) { 1499 warning(_("HEAD %s is not a commit!"), 1500 oid_to_hex(&oid)); 1501 } 1502 if (repo_parse_commit(r, current_head)) 1503 return error(_("could not parse HEAD commit")); 1504 } 1505 *head = current_head; 1506 1507 return 0; 1508} 1509 1510/* 1511 * Try to commit without forking 'git commit'. In some cases we need 1512 * to run 'git commit' to display an error message 1513 * 1514 * Returns: 1515 * -1 - error unable to commit 1516 * 0 - success 1517 * 1 - run 'git commit' 1518 */ 1519static int try_to_commit(struct repository *r, 1520 struct strbuf *msg, const char *author, 1521 const char *reflog_action, 1522 struct replay_opts *opts, unsigned int flags, 1523 struct object_id *oid) 1524{ 1525 struct object_id tree; 1526 struct commit *current_head = NULL; 1527 struct commit_list *parents = NULL; 1528 struct commit_extra_header *extra = NULL; 1529 struct strbuf err = STRBUF_INIT; 1530 struct strbuf commit_msg = STRBUF_INIT; 1531 char *amend_author = NULL; 1532 const char *committer = NULL; 1533 const char *hook_commit = NULL; 1534 enum commit_msg_cleanup_mode cleanup; 1535 int res = 0; 1536 1537 if (parse_head(r, &current_head)) 1538 return -1; 1539 1540 if (flags & AMEND_MSG) { 1541 const char *exclude_gpgsig[] = { "gpgsig", "gpgsig-sha256", NULL }; 1542 const char *out_enc = get_commit_output_encoding(); 1543 const char *message = repo_logmsg_reencode(r, current_head, 1544 NULL, out_enc); 1545 1546 if (!msg) { 1547 const char *orig_message = NULL; 1548 1549 find_commit_subject(message, &orig_message); 1550 msg = &commit_msg; 1551 strbuf_addstr(msg, orig_message); 1552 hook_commit = "HEAD"; 1553 } 1554 author = amend_author = get_author(message); 1555 repo_unuse_commit_buffer(r, current_head, 1556 message); 1557 if (!author) { 1558 res = error(_("unable to parse commit author")); 1559 goto out; 1560 } 1561 parents = copy_commit_list(current_head->parents); 1562 extra = read_commit_extra_headers(current_head, exclude_gpgsig); 1563 } else if (current_head && 1564 (!(flags & CREATE_ROOT_COMMIT) || (flags & AMEND_MSG))) { 1565 commit_list_insert(current_head, &parents); 1566 } 1567 1568 if (write_index_as_tree(&tree, r->index, r->index_file, 0, NULL)) { 1569 res = error(_("git write-tree failed to write a tree")); 1570 goto out; 1571 } 1572 1573 if (!(flags & ALLOW_EMPTY)) { 1574 struct commit *first_parent = current_head; 1575 1576 if (flags & AMEND_MSG) { 1577 if (current_head->parents) { 1578 first_parent = current_head->parents->item; 1579 if (repo_parse_commit(r, first_parent)) { 1580 res = error(_("could not parse HEAD commit")); 1581 goto out; 1582 } 1583 } else { 1584 first_parent = NULL; 1585 } 1586 } 1587 if (oideq(first_parent 1588 ? get_commit_tree_oid(first_parent) 1589 : the_hash_algo->empty_tree, 1590 &tree)) { 1591 res = 1; /* run 'git commit' to display error message */ 1592 goto out; 1593 } 1594 } 1595 1596 if (hook_exists(r, "prepare-commit-msg")) { 1597 res = run_prepare_commit_msg_hook(r, msg, hook_commit); 1598 if (res) 1599 goto out; 1600 if (strbuf_read_file(&commit_msg, git_path_commit_editmsg(), 1601 2048) < 0) { 1602 res = error_errno(_("unable to read commit message " 1603 "from '%s'"), 1604 git_path_commit_editmsg()); 1605 goto out; 1606 } 1607 msg = &commit_msg; 1608 } 1609 1610 if (flags & CLEANUP_MSG) 1611 cleanup = COMMIT_MSG_CLEANUP_ALL; 1612 else if ((opts->signoff || opts->record_origin) && 1613 !opts->explicit_cleanup) 1614 cleanup = COMMIT_MSG_CLEANUP_SPACE; 1615 else 1616 cleanup = opts->default_msg_cleanup; 1617 1618 if (cleanup != COMMIT_MSG_CLEANUP_NONE) 1619 strbuf_stripspace(msg, 1620 cleanup == COMMIT_MSG_CLEANUP_ALL ? comment_line_str : NULL); 1621 if ((flags & EDIT_MSG) && message_is_empty(msg, cleanup)) { 1622 res = 1; /* run 'git commit' to display error message */ 1623 goto out; 1624 } 1625 1626 if (opts->committer_date_is_author_date) { 1627 struct ident_split id; 1628 struct strbuf date = STRBUF_INIT; 1629 1630 if (!opts->ignore_date) { 1631 if (split_ident_line(&id, author, (int)strlen(author)) < 0) { 1632 res = error(_("invalid author identity '%s'"), 1633 author); 1634 goto out; 1635 } 1636 if (!id.date_begin) { 1637 res = error(_( 1638 "corrupt author: missing date information")); 1639 goto out; 1640 } 1641 strbuf_addf(&date, "@%.*s %.*s", 1642 (int)(id.date_end - id.date_begin), 1643 id.date_begin, 1644 (int)(id.tz_end - id.tz_begin), 1645 id.tz_begin); 1646 } else { 1647 reset_ident_date(); 1648 } 1649 committer = fmt_ident(getenv("GIT_COMMITTER_NAME"), 1650 getenv("GIT_COMMITTER_EMAIL"), 1651 WANT_COMMITTER_IDENT, 1652 opts->ignore_date ? NULL : date.buf, 1653 IDENT_STRICT); 1654 strbuf_release(&date); 1655 } else { 1656 reset_ident_date(); 1657 } 1658 1659 if (opts->ignore_date) { 1660 struct ident_split id; 1661 char *name, *email; 1662 1663 if (split_ident_line(&id, author, strlen(author)) < 0) { 1664 error(_("invalid author identity '%s'"), author); 1665 goto out; 1666 } 1667 name = xmemdupz(id.name_begin, id.name_end - id.name_begin); 1668 email = xmemdupz(id.mail_begin, id.mail_end - id.mail_begin); 1669 author = fmt_ident(name, email, WANT_AUTHOR_IDENT, NULL, 1670 IDENT_STRICT); 1671 free(name); 1672 free(email); 1673 } 1674 1675 if (commit_tree_extended(msg->buf, msg->len, &tree, parents, oid, 1676 author, committer, opts->gpg_sign, extra)) { 1677 res = error(_("failed to write commit object")); 1678 goto out; 1679 } 1680 1681 if (update_head_with_reflog(current_head, oid, reflog_action, 1682 msg, &err)) { 1683 res = error("%s", err.buf); 1684 goto out; 1685 } 1686 1687 run_commit_hook(0, r->index_file, NULL, "post-commit", NULL); 1688 if (flags & AMEND_MSG) 1689 commit_post_rewrite(r, current_head, oid); 1690 1691out: 1692 free_commit_extra_headers(extra); 1693 free_commit_list(parents); 1694 strbuf_release(&err); 1695 strbuf_release(&commit_msg); 1696 free(amend_author); 1697 1698 return res; 1699} 1700 1701static int write_rebase_head(struct object_id *oid) 1702{ 1703 if (refs_update_ref(get_main_ref_store(the_repository), "rebase", "REBASE_HEAD", oid, 1704 NULL, REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR)) 1705 return error(_("could not update %s"), "REBASE_HEAD"); 1706 1707 return 0; 1708} 1709 1710static int do_commit(struct repository *r, 1711 const char *msg_file, const char *author, 1712 const char *reflog_action, 1713 struct replay_opts *opts, unsigned int flags, 1714 struct object_id *oid) 1715{ 1716 int res = 1; 1717 1718 if (!(flags & EDIT_MSG) && !(flags & VERIFY_MSG)) { 1719 struct object_id oid; 1720 struct strbuf sb = STRBUF_INIT; 1721 1722 if (msg_file && strbuf_read_file(&sb, msg_file, 2048) < 0) 1723 return error_errno(_("unable to read commit message " 1724 "from '%s'"), 1725 msg_file); 1726 1727 res = try_to_commit(r, msg_file ? &sb : NULL, 1728 author, reflog_action, opts, flags, &oid); 1729 strbuf_release(&sb); 1730 if (!res) { 1731 refs_delete_ref(get_main_ref_store(r), "", 1732 "CHERRY_PICK_HEAD", NULL, REF_NO_DEREF); 1733 unlink(git_path_merge_msg(r)); 1734 if (!is_rebase_i(opts)) 1735 print_commit_summary(r, NULL, &oid, 1736 SUMMARY_SHOW_AUTHOR_DATE); 1737 return res; 1738 } 1739 } 1740 if (res == 1) { 1741 if (is_rebase_i(opts) && oid) 1742 if (write_rebase_head(oid)) 1743 return -1; 1744 return run_git_commit(msg_file, reflog_action, opts, flags); 1745 } 1746 1747 return res; 1748} 1749 1750static int is_original_commit_empty(struct commit *commit) 1751{ 1752 const struct object_id *ptree_oid; 1753 1754 if (repo_parse_commit(the_repository, commit)) 1755 return error(_("could not parse commit %s"), 1756 oid_to_hex(&commit->object.oid)); 1757 if (commit->parents) { 1758 struct commit *parent = commit->parents->item; 1759 if (repo_parse_commit(the_repository, parent)) 1760 return error(_("could not parse parent commit %s"), 1761 oid_to_hex(&parent->object.oid)); 1762 ptree_oid = get_commit_tree_oid(parent); 1763 } else { 1764 ptree_oid = the_hash_algo->empty_tree; /* commit is root */ 1765 } 1766 1767 return oideq(ptree_oid, get_commit_tree_oid(commit)); 1768} 1769 1770/* 1771 * Should empty commits be allowed? Return status: 1772 * <0: Error in is_index_unchanged(r) or is_original_commit_empty(commit) 1773 * 0: Halt on empty commit 1774 * 1: Allow empty commit 1775 * 2: Drop empty commit 1776 */ 1777static int allow_empty(struct repository *r, 1778 struct replay_opts *opts, 1779 struct commit *commit) 1780{ 1781 int index_unchanged, originally_empty; 1782 1783 /* 1784 * For a commit that is initially empty, allow_empty determines if it 1785 * should be kept or not 1786 * 1787 * For a commit that becomes empty, keep_redundant_commits and 1788 * drop_redundant_commits determine whether the commit should be kept or 1789 * dropped. If neither is specified, halt. 1790 */ 1791 index_unchanged = is_index_unchanged(r); 1792 if (index_unchanged < 0) 1793 return index_unchanged; 1794 if (!index_unchanged) 1795 return 0; /* we do not have to say --allow-empty */ 1796 1797 originally_empty = is_original_commit_empty(commit); 1798 if (originally_empty < 0) 1799 return originally_empty; 1800 if (originally_empty) 1801 return opts->allow_empty; 1802 else if (opts->keep_redundant_commits) 1803 return 1; 1804 else if (opts->drop_redundant_commits) 1805 return 2; 1806 else 1807 return 0; 1808} 1809 1810static struct { 1811 char c; 1812 const char *str; 1813} todo_command_info[] = { 1814 [TODO_PICK] = { 'p', "pick" }, 1815 [TODO_REVERT] = { 0, "revert" }, 1816 [TODO_EDIT] = { 'e', "edit" }, 1817 [TODO_REWORD] = { 'r', "reword" }, 1818 [TODO_FIXUP] = { 'f', "fixup" }, 1819 [TODO_SQUASH] = { 's', "squash" }, 1820 [TODO_EXEC] = { 'x', "exec" }, 1821 [TODO_BREAK] = { 'b', "break" }, 1822 [TODO_LABEL] = { 'l', "label" }, 1823 [TODO_RESET] = { 't', "reset" }, 1824 [TODO_MERGE] = { 'm', "merge" }, 1825 [TODO_UPDATE_REF] = { 'u', "update-ref" }, 1826 [TODO_NOOP] = { 0, "noop" }, 1827 [TODO_DROP] = { 'd', "drop" }, 1828 [TODO_COMMENT] = { 0, NULL }, 1829}; 1830 1831static const char *command_to_string(const enum todo_command command) 1832{ 1833 if (command < TODO_COMMENT) 1834 return todo_command_info[command].str; 1835 if (command == TODO_COMMENT) 1836 return comment_line_str; 1837 die(_("unknown command: %d"), command); 1838} 1839 1840static char command_to_char(const enum todo_command command) 1841{ 1842 if (command < TODO_COMMENT) 1843 return todo_command_info[command].c; 1844 return 0; 1845} 1846 1847static int is_noop(const enum todo_command command) 1848{ 1849 return TODO_NOOP <= command; 1850} 1851 1852static int is_fixup(enum todo_command command) 1853{ 1854 return command == TODO_FIXUP || command == TODO_SQUASH; 1855} 1856 1857/* Does this command create a (non-merge) commit? */ 1858static int is_pick_or_similar(enum todo_command command) 1859{ 1860 switch (command) { 1861 case TODO_PICK: 1862 case TODO_REVERT: 1863 case TODO_EDIT: 1864 case TODO_REWORD: 1865 case TODO_FIXUP: 1866 case TODO_SQUASH: 1867 return 1; 1868 default: 1869 return 0; 1870 } 1871} 1872 1873enum todo_item_flags { 1874 TODO_EDIT_MERGE_MSG = (1 << 0), 1875 TODO_REPLACE_FIXUP_MSG = (1 << 1), 1876 TODO_EDIT_FIXUP_MSG = (1 << 2), 1877}; 1878 1879static const char first_commit_msg_str[] = N_("This is the 1st commit message:"); 1880static const char nth_commit_msg_fmt[] = N_("This is the commit message #%d:"); 1881static const char skip_first_commit_msg_str[] = N_("The 1st commit message will be skipped:"); 1882static const char skip_nth_commit_msg_fmt[] = N_("The commit message #%d will be skipped:"); 1883static const char combined_commit_msg_fmt[] = N_("This is a combination of %d commits."); 1884 1885static int is_fixup_flag(enum todo_command command, unsigned flag) 1886{ 1887 return command == TODO_FIXUP && ((flag & TODO_REPLACE_FIXUP_MSG) || 1888 (flag & TODO_EDIT_FIXUP_MSG)); 1889} 1890 1891/* 1892 * Wrapper around strbuf_add_commented_lines() which avoids double 1893 * commenting commit subjects. 1894 */ 1895static void add_commented_lines(struct strbuf *buf, const void *str, size_t len) 1896{ 1897 const char *s = str; 1898 while (starts_with_mem(s, len, comment_line_str)) { 1899 size_t count; 1900 const char *n = memchr(s, '\n', len); 1901 if (!n) 1902 count = len; 1903 else 1904 count = n - s + 1; 1905 strbuf_add(buf, s, count); 1906 s += count; 1907 len -= count; 1908 } 1909 strbuf_add_commented_lines(buf, s, len, comment_line_str); 1910} 1911 1912/* Does the current fixup chain contain a squash command? */ 1913static int seen_squash(struct replay_ctx *ctx) 1914{ 1915 return starts_with(ctx->current_fixups.buf, "squash") || 1916 strstr(ctx->current_fixups.buf, "\nsquash"); 1917} 1918 1919static void update_comment_bufs(struct strbuf *buf1, struct strbuf *buf2, int n) 1920{ 1921 strbuf_setlen(buf1, strlen(comment_line_str) + 1); 1922 strbuf_addf(buf1, _(nth_commit_msg_fmt), n); 1923 strbuf_addch(buf1, '\n'); 1924 strbuf_setlen(buf2, strlen(comment_line_str) + 1); 1925 strbuf_addf(buf2, _(skip_nth_commit_msg_fmt), n); 1926 strbuf_addch(buf2, '\n'); 1927} 1928 1929/* 1930 * Comment out any un-commented commit messages, updating the message comments 1931 * to say they will be skipped but do not comment out the empty lines that 1932 * surround commit messages and their comments. 1933 */ 1934static void update_squash_message_for_fixup(struct strbuf *msg) 1935{ 1936 void (*copy_lines)(struct strbuf *, const void *, size_t) = strbuf_add; 1937 struct strbuf buf1 = STRBUF_INIT, buf2 = STRBUF_INIT; 1938 const char *s, *start; 1939 char *orig_msg; 1940 size_t orig_msg_len; 1941 int i = 1; 1942 1943 strbuf_add_commented_lines(&buf1, _(first_commit_msg_str), 1944 strlen(_(first_commit_msg_str)), 1945 comment_line_str); 1946 strbuf_add_commented_lines(&buf2, _(skip_first_commit_msg_str), 1947 strlen(_(skip_first_commit_msg_str)), 1948 comment_line_str); 1949 s = start = orig_msg = strbuf_detach(msg, &orig_msg_len); 1950 while (s) { 1951 const char *next; 1952 size_t off; 1953 if (skip_prefix(s, buf1.buf, &next)) { 1954 /* 1955 * Copy the last message, preserving the blank line 1956 * preceding the current line 1957 */ 1958 off = (s > start + 1 && s[-2] == '\n') ? 1 : 0; 1959 copy_lines(msg, start, s - start - off); 1960 if (off) 1961 strbuf_addch(msg, '\n'); 1962 /* 1963 * The next message needs to be commented out but the 1964 * message header is already commented out so just copy 1965 * it and the blank line that follows it. 1966 */ 1967 strbuf_addbuf(msg, &buf2); 1968 if (*next == '\n') 1969 strbuf_addch(msg, *next++); 1970 start = s = next; 1971 copy_lines = add_commented_lines; 1972 update_comment_bufs(&buf1, &buf2, ++i); 1973 } else if (skip_prefix(s, buf2.buf, &next)) { 1974 off = (s > start + 1 && s[-2] == '\n') ? 1 : 0; 1975 copy_lines(msg, start, s - start - off); 1976 start = s - off; 1977 s = next; 1978 copy_lines = strbuf_add; 1979 update_comment_bufs(&buf1, &buf2, ++i); 1980 } else { 1981 s = strchr(s, '\n'); 1982 if (s) 1983 s++; 1984 } 1985 } 1986 copy_lines(msg, start, orig_msg_len - (start - orig_msg)); 1987 free(orig_msg); 1988 strbuf_release(&buf1); 1989 strbuf_release(&buf2); 1990} 1991 1992static int append_squash_message(struct strbuf *buf, const char *body, 1993 enum todo_command command, struct replay_opts *opts, 1994 unsigned flag) 1995{ 1996 struct replay_ctx *ctx = opts->ctx; 1997 const char *fixup_msg; 1998 size_t commented_len = 0, fixup_off; 1999 /* 2000 * amend is non-interactive and not normally used with fixup! 2001 * or squash! commits, so only comment out those subjects when 2002 * squashing commit messages. 2003 */ 2004 if (starts_with(body, "amend!") || 2005 ((command == TODO_SQUASH || seen_squash(ctx)) && 2006 (starts_with(body, "squash!") || starts_with(body, "fixup!")))) 2007 commented_len = commit_subject_length(body); 2008 2009 strbuf_addf(buf, "\n%s ", comment_line_str); 2010 strbuf_addf(buf, _(nth_commit_msg_fmt), 2011 ++ctx->current_fixup_count + 1); 2012 strbuf_addstr(buf, "\n\n"); 2013 strbuf_add_commented_lines(buf, body, commented_len, comment_line_str); 2014 /* buf->buf may be reallocated so store an offset into the buffer */ 2015 fixup_off = buf->len; 2016 strbuf_addstr(buf, body + commented_len); 2017 2018 /* fixup -C after squash behaves like squash */ 2019 if (is_fixup_flag(command, flag) && !seen_squash(ctx)) { 2020 /* 2021 * We're replacing the commit message so we need to 2022 * append the Signed-off-by: trailer if the user 2023 * requested '--signoff'. 2024 */ 2025 if (opts->signoff) 2026 append_signoff(buf, 0, 0); 2027 2028 if ((command == TODO_FIXUP) && 2029 (flag & TODO_REPLACE_FIXUP_MSG) && 2030 (file_exists(rebase_path_fixup_msg()) || 2031 !file_exists(rebase_path_squash_msg()))) { 2032 fixup_msg = skip_blank_lines(buf->buf + fixup_off); 2033 if (write_message(fixup_msg, strlen(fixup_msg), 2034 rebase_path_fixup_msg(), 0) < 0) 2035 return error(_("cannot write '%s'"), 2036 rebase_path_fixup_msg()); 2037 } else { 2038 unlink(rebase_path_fixup_msg()); 2039 } 2040 } else { 2041 unlink(rebase_path_fixup_msg()); 2042 } 2043 2044 return 0; 2045} 2046 2047static int update_squash_messages(struct repository *r, 2048 enum todo_command command, 2049 struct commit *commit, 2050 struct replay_opts *opts, 2051 unsigned flag) 2052{ 2053 struct replay_ctx *ctx = opts->ctx; 2054 struct strbuf buf = STRBUF_INIT; 2055 int res = 0; 2056 const char *message, *body; 2057 const char *encoding = get_commit_output_encoding(); 2058 2059 if (!is_fixup(command)) 2060 BUG("not a FIXUP or SQUASH %d", command); 2061 2062 if (ctx->current_fixup_count > 0) { 2063 struct strbuf header = STRBUF_INIT; 2064 char *eol; 2065 2066 if (strbuf_read_file(&buf, rebase_path_squash_msg(), 9) <= 0) 2067 return error(_("could not read '%s'"), 2068 rebase_path_squash_msg()); 2069 2070 eol = !starts_with(buf.buf, comment_line_str) ? 2071 buf.buf : strchrnul(buf.buf, '\n'); 2072 2073 strbuf_addf(&header, "%s ", comment_line_str); 2074 strbuf_addf(&header, _(combined_commit_msg_fmt), 2075 ctx->current_fixup_count + 2); 2076 strbuf_splice(&buf, 0, eol - buf.buf, header.buf, header.len); 2077 strbuf_release(&header); 2078 if (is_fixup_flag(command, flag) && !seen_squash(ctx)) 2079 update_squash_message_for_fixup(&buf); 2080 } else { 2081 struct object_id head; 2082 struct commit *head_commit; 2083 const char *head_message, *body; 2084 2085 if (repo_get_oid(r, "HEAD", &head)) 2086 return error(_("need a HEAD to fixup")); 2087 if (!(head_commit = lookup_commit_reference(r, &head))) 2088 return error(_("could not read HEAD")); 2089 if (!(head_message = repo_logmsg_reencode(r, head_commit, NULL, 2090 encoding))) 2091 return error(_("could not read HEAD's commit message")); 2092 2093 find_commit_subject(head_message, &body); 2094 if (command == TODO_FIXUP && !flag && write_message(body, strlen(body), 2095 rebase_path_fixup_msg(), 0) < 0) { 2096 repo_unuse_commit_buffer(r, head_commit, head_message); 2097 return error(_("cannot write '%s'"), rebase_path_fixup_msg()); 2098 } 2099 strbuf_addf(&buf, "%s ", comment_line_str); 2100 strbuf_addf(&buf, _(combined_commit_msg_fmt), 2); 2101 strbuf_addf(&buf, "\n%s ", comment_line_str); 2102 strbuf_addstr(&buf, is_fixup_flag(command, flag) ? 2103 _(skip_first_commit_msg_str) : 2104 _(first_commit_msg_str)); 2105 strbuf_addstr(&buf, "\n\n"); 2106 if (is_fixup_flag(command, flag)) 2107 strbuf_add_commented_lines(&buf, body, strlen(body), 2108 comment_line_str); 2109 else 2110 strbuf_addstr(&buf, body); 2111 2112 repo_unuse_commit_buffer(r, head_commit, head_message); 2113 } 2114 2115 if (!(message = repo_logmsg_reencode(r, commit, NULL, encoding))) 2116 return error(_("could not read commit message of %s"), 2117 oid_to_hex(&commit->object.oid)); 2118 find_commit_subject(message, &body); 2119 2120 if (command == TODO_SQUASH || is_fixup_flag(command, flag)) { 2121 res = append_squash_message(&buf, body, command, opts, flag); 2122 } else if (command == TODO_FIXUP) { 2123 strbuf_addf(&buf, "\n%s ", comment_line_str); 2124 strbuf_addf(&buf, _(skip_nth_commit_msg_fmt), 2125 ++ctx->current_fixup_count + 1); 2126 strbuf_addstr(&buf, "\n\n"); 2127 strbuf_add_commented_lines(&buf, body, strlen(body), 2128 comment_line_str); 2129 } 2130 repo_unuse_commit_buffer(r, commit, message); 2131 2132 if (!res) 2133 res = write_message(buf.buf, buf.len, rebase_path_squash_msg(), 2134 0); 2135 strbuf_release(&buf); 2136 2137 if (!res) { 2138 strbuf_addf(&ctx->current_fixups, "%s%s %s", 2139 ctx->current_fixups.len ? "\n" : "", 2140 command_to_string(command), 2141 oid_to_hex(&commit->object.oid)); 2142 res = write_message(ctx->current_fixups.buf, 2143 ctx->current_fixups.len, 2144 rebase_path_current_fixups(), 0); 2145 } 2146 2147 return res; 2148} 2149 2150static void flush_rewritten_pending(void) 2151{ 2152 struct strbuf buf = STRBUF_INIT; 2153 struct object_id newoid; 2154 FILE *out; 2155 2156 if (strbuf_read_file(&buf, rebase_path_rewritten_pending(), (GIT_MAX_HEXSZ + 1) * 2) > 0 && 2157 !repo_get_oid(the_repository, "HEAD", &newoid) && 2158 (out = fopen_or_warn(rebase_path_rewritten_list(), "a"))) { 2159 char *bol = buf.buf, *eol; 2160 2161 while (*bol) { 2162 eol = strchrnul(bol, '\n'); 2163 fprintf(out, "%.*s %s\n", (int)(eol - bol), 2164 bol, oid_to_hex(&newoid)); 2165 if (!*eol) 2166 break; 2167 bol = eol + 1; 2168 } 2169 fclose(out); 2170 unlink(rebase_path_rewritten_pending()); 2171 } 2172 strbuf_release(&buf); 2173} 2174 2175static void record_in_rewritten(struct object_id *oid, 2176 enum todo_command next_command) 2177{ 2178 FILE *out = fopen_or_warn(rebase_path_rewritten_pending(), "a"); 2179 2180 if (!out) 2181 return; 2182 2183 fprintf(out, "%s\n", oid_to_hex(oid)); 2184 fclose(out); 2185 2186 if (!is_fixup(next_command)) 2187 flush_rewritten_pending(); 2188} 2189 2190static int should_edit(struct replay_opts *opts) { 2191 if (opts->edit < 0) 2192 /* 2193 * Note that we only handle the case of non-conflicted 2194 * commits; continue_single_pick() handles the conflicted 2195 * commits itself instead of calling this function. 2196 */ 2197 return (opts->action == REPLAY_REVERT && isatty(0)) ? 1 : 0; 2198 return opts->edit; 2199} 2200 2201static void refer_to_commit(struct replay_opts *opts, 2202 struct strbuf *msgbuf, struct commit *commit) 2203{ 2204 if (opts->commit_use_reference) { 2205 struct pretty_print_context ctx = { 2206 .abbrev = DEFAULT_ABBREV, 2207 .date_mode.type = DATE_SHORT, 2208 }; 2209 repo_format_commit_message(the_repository, commit, 2210 "%h (%s, %ad)", msgbuf, &ctx); 2211 } else { 2212 strbuf_addstr(msgbuf, oid_to_hex(&commit->object.oid)); 2213 } 2214} 2215 2216static const char *sequencer_reflog_action(struct replay_opts *opts) 2217{ 2218 if (!opts->reflog_action) { 2219 opts->reflog_action = getenv(GIT_REFLOG_ACTION); 2220 opts->reflog_action = 2221 xstrdup(opts->reflog_action ? opts->reflog_action 2222 : action_name(opts)); 2223 } 2224 2225 return opts->reflog_action; 2226} 2227 2228__attribute__((format (printf, 3, 4))) 2229static const char *reflog_message(struct replay_opts *opts, 2230 const char *sub_action, const char *fmt, ...) 2231{ 2232 va_list ap; 2233 static struct strbuf buf = STRBUF_INIT; 2234 2235 va_start(ap, fmt); 2236 strbuf_reset(&buf); 2237 strbuf_addstr(&buf, sequencer_reflog_action(opts)); 2238 if (sub_action) 2239 strbuf_addf(&buf, " (%s)", sub_action); 2240 if (fmt) { 2241 strbuf_addstr(&buf, ": "); 2242 strbuf_vaddf(&buf, fmt, ap); 2243 } 2244 va_end(ap); 2245 2246 return buf.buf; 2247} 2248 2249static int do_pick_commit(struct repository *r, 2250 struct todo_item *item, 2251 struct replay_opts *opts, 2252 int final_fixup, int *check_todo) 2253{ 2254 struct replay_ctx *ctx = opts->ctx; 2255 unsigned int flags = should_edit(opts) ? EDIT_MSG : 0; 2256 const char *msg_file = should_edit(opts) ? NULL : git_path_merge_msg(r); 2257 struct object_id head; 2258 struct commit *base, *next, *parent; 2259 const char *base_label, *next_label, *reflog_action; 2260 char *author = NULL; 2261 struct commit_message msg = { NULL, NULL, NULL, NULL }; 2262 int res, unborn = 0, reword = 0, allow, drop_commit; 2263 enum todo_command command = item->command; 2264 struct commit *commit = item->commit; 2265 2266 if (is_rebase_i(opts)) 2267 reflog_action = reflog_message( 2268 opts, command_to_string(item->command), NULL); 2269 else 2270 reflog_action = sequencer_reflog_action(opts); 2271 2272 if (opts->no_commit) { 2273 /* 2274 * We do not intend to commit immediately. We just want to 2275 * merge the differences in, so let's compute the tree 2276 * that represents the "current" state for the merge machinery 2277 * to work on. 2278 */ 2279 if (write_index_as_tree(&head, r->index, r->index_file, 0, NULL)) 2280 return error(_("your index file is unmerged.")); 2281 } else { 2282 unborn = repo_get_oid(r, "HEAD", &head); 2283 /* Do we want to generate a root commit? */ 2284 if (is_pick_or_similar(command) && opts->have_squash_onto && 2285 oideq(&head, &opts->squash_onto)) { 2286 if (is_fixup(command)) 2287 return error(_("cannot fixup root commit")); 2288 flags |= CREATE_ROOT_COMMIT; 2289 unborn = 1; 2290 } else if (unborn) 2291 oidcpy(&head, the_hash_algo->empty_tree); 2292 if (index_differs_from(r, unborn ? empty_tree_oid_hex(the_repository->hash_algo) : "HEAD", 2293 NULL, 0)) 2294 return error_dirty_index(r, opts); 2295 } 2296 discard_index(r->index); 2297 2298 if (!commit->parents) 2299 parent = NULL; 2300 else if (commit->parents->next) { 2301 /* Reverting or cherry-picking a merge commit */ 2302 int cnt; 2303 struct commit_list *p; 2304 2305 if (!opts->mainline) 2306 return error(_("commit %s is a merge but no -m option was given."), 2307 oid_to_hex(&commit->object.oid)); 2308 2309 for (cnt = 1, p = commit->parents; 2310 cnt != opts->mainline && p; 2311 cnt++) 2312 p = p->next; 2313 if (cnt != opts->mainline || !p) 2314 return error(_("commit %s does not have parent %d"), 2315 oid_to_hex(&commit->object.oid), opts->mainline); 2316 parent = p->item; 2317 } else if (1 < opts->mainline) 2318 /* 2319 * Non-first parent explicitly specified as mainline for 2320 * non-merge commit 2321 */ 2322 return error(_("commit %s does not have parent %d"), 2323 oid_to_hex(&commit->object.oid), opts->mainline); 2324 else 2325 parent = commit->parents->item; 2326 2327 if (get_message(commit, &msg) != 0) 2328 return error(_("cannot get commit message for %s"), 2329 oid_to_hex(&commit->object.oid)); 2330 2331 if (opts->allow_ff && !is_fixup(command) && 2332 ((parent && oideq(&parent->object.oid, &head)) || 2333 (!parent && unborn))) { 2334 if (is_rebase_i(opts)) 2335 write_author_script(msg.message); 2336 res = fast_forward_to(r, &commit->object.oid, &head, unborn, 2337 opts); 2338 if (res || command != TODO_REWORD) 2339 goto leave; 2340 reword = 1; 2341 msg_file = NULL; 2342 goto fast_forward_edit; 2343 } 2344 if (parent && repo_parse_commit(r, parent) < 0) 2345 /* TRANSLATORS: The first %s will be a "todo" command like 2346 "revert" or "pick", the second %s a SHA1. */ 2347 return error(_("%s: cannot parse parent commit %s"), 2348 command_to_string(command), 2349 oid_to_hex(&parent->object.oid)); 2350 2351 /* 2352 * "commit" is an existing commit. We would want to apply 2353 * the difference it introduces since its first parent "prev" 2354 * on top of the current HEAD if we are cherry-pick. Or the 2355 * reverse of it if we are revert. 2356 */ 2357 2358 if (command == TODO_REVERT) { 2359 const char *orig_subject; 2360 2361 base = commit; 2362 base_label = msg.label; 2363 next = parent; 2364 next_label = msg.parent_label; 2365 if (opts->commit_use_reference) { 2366 strbuf_commented_addf(&ctx->message, comment_line_str, 2367 "*** SAY WHY WE ARE REVERTING ON THE TITLE LINE ***"); 2368 } else if (skip_prefix(msg.subject, "Revert \"", &orig_subject) && 2369 /* 2370 * We don't touch pre-existing repeated reverts, because 2371 * theoretically these can be nested arbitrarily deeply, 2372 * thus requiring excessive complexity to deal with. 2373 */ 2374 !starts_with(orig_subject, "Revert \"")) { 2375 strbuf_addstr(&ctx->message, "Reapply \""); 2376 strbuf_addstr(&ctx->message, orig_subject); 2377 strbuf_addstr(&ctx->message, "\n"); 2378 } else { 2379 strbuf_addstr(&ctx->message, "Revert \""); 2380 strbuf_addstr(&ctx->message, msg.subject); 2381 strbuf_addstr(&ctx->message, "\"\n"); 2382 } 2383 strbuf_addstr(&ctx->message, "\nThis reverts commit "); 2384 refer_to_commit(opts, &ctx->message, commit); 2385 2386 if (commit->parents && commit->parents->next) { 2387 strbuf_addstr(&ctx->message, ", reversing\nchanges made to "); 2388 refer_to_commit(opts, &ctx->message, parent); 2389 } 2390 strbuf_addstr(&ctx->message, ".\n"); 2391 } else { 2392 const char *p; 2393 2394 base = parent; 2395 base_label = msg.parent_label; 2396 next = commit; 2397 next_label = msg.label; 2398 2399 /* Append the commit log message to ctx->message. */ 2400 if (find_commit_subject(msg.message, &p)) 2401 strbuf_addstr(&ctx->message, p); 2402 2403 if (opts->record_origin) { 2404 strbuf_complete_line(&ctx->message); 2405 if (!has_conforming_footer(&ctx->message, NULL, 0)) 2406 strbuf_addch(&ctx->message, '\n'); 2407 strbuf_addstr(&ctx->message, cherry_picked_prefix); 2408 strbuf_addstr(&ctx->message, oid_to_hex(&commit->object.oid)); 2409 strbuf_addstr(&ctx->message, ")\n"); 2410 } 2411 if (!is_fixup(command)) 2412 author = get_author(msg.message); 2413 } 2414 ctx->have_message = 1; 2415 2416 if (command == TODO_REWORD) 2417 reword = 1; 2418 else if (is_fixup(command)) { 2419 if (update_squash_messages(r, command, commit, 2420 opts, item->flags)) { 2421 res = -1; 2422 goto leave; 2423 } 2424 flags |= AMEND_MSG; 2425 if (!final_fixup) 2426 msg_file = rebase_path_squash_msg(); 2427 else if (file_exists(rebase_path_fixup_msg())) { 2428 msg_file = rebase_path_fixup_msg(); 2429 } else { 2430 const char *dest = git_path_squash_msg(r); 2431 unlink(dest); 2432 if (copy_file(dest, rebase_path_squash_msg(), 0666)) { 2433 res = error(_("could not copy '%s' to '%s'"), 2434 rebase_path_squash_msg(), dest); 2435 goto leave; 2436 } 2437 unlink(git_path_merge_msg(r)); 2438 msg_file = dest; 2439 flags |= EDIT_MSG; 2440 } 2441 } 2442 2443 if (opts->signoff && !is_fixup(command)) 2444 append_signoff(&ctx->message, 0, 0); 2445 2446 if (is_rebase_i(opts) && write_author_script(msg.message) < 0) 2447 res = -1; 2448 else if (!opts->strategy || 2449 !strcmp(opts->strategy, "recursive") || 2450 !strcmp(opts->strategy, "ort") || 2451 command == TODO_REVERT) { 2452 res = do_recursive_merge(r, base, next, base_label, next_label, 2453 &head, &ctx->message, opts); 2454 if (res < 0) 2455 goto leave; 2456 2457 res |= write_message(ctx->message.buf, ctx->message.len, 2458 git_path_merge_msg(r), 0); 2459 } else { 2460 struct commit_list *common = NULL; 2461 struct commit_list *remotes = NULL; 2462 2463 res = write_message(ctx->message.buf, ctx->message.len, 2464 git_path_merge_msg(r), 0); 2465 2466 commit_list_insert(base, &common); 2467 commit_list_insert(next, &remotes); 2468 res |= try_merge_command(r, opts->strategy, 2469 opts->xopts.nr, opts->xopts.v, 2470 common, oid_to_hex(&head), remotes); 2471 free_commit_list(common); 2472 free_commit_list(remotes); 2473 } 2474 2475 /* 2476 * If the merge was clean or if it failed due to conflict, we write 2477 * CHERRY_PICK_HEAD for the subsequent invocation of commit to use. 2478 * However, if the merge did not even start, then we don't want to 2479 * write it at all. 2480 */ 2481 if ((command == TODO_PICK || command == TODO_REWORD || 2482 command == TODO_EDIT) && !opts->no_commit && 2483 (res == 0 || res == 1) && 2484 refs_update_ref(get_main_ref_store(the_repository), NULL, "CHERRY_PICK_HEAD", &commit->object.oid, NULL, 2485 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR)) 2486 res = -1; 2487 if (command == TODO_REVERT && ((opts->no_commit && res == 0) || res == 1) && 2488 refs_update_ref(get_main_ref_store(the_repository), NULL, "REVERT_HEAD", &commit->object.oid, NULL, 2489 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR)) 2490 res = -1; 2491 2492 if (res) { 2493 error(command == TODO_REVERT 2494 ? _("could not revert %s... %s") 2495 : _("could not apply %s... %s"), 2496 short_commit_name(r, commit), msg.subject); 2497 print_advice(r, res == 1, opts); 2498 repo_rerere(r, opts->allow_rerere_auto); 2499 goto leave; 2500 } 2501 2502 drop_commit = 0; 2503 allow = allow_empty(r, opts, commit); 2504 if (allow < 0) { 2505 res = allow; 2506 goto leave; 2507 } else if (allow == 1) { 2508 flags |= ALLOW_EMPTY; 2509 } else if (allow == 2) { 2510 drop_commit = 1; 2511 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD", 2512 NULL, REF_NO_DEREF); 2513 unlink(git_path_merge_msg(r)); 2514 refs_delete_ref(get_main_ref_store(r), "", "AUTO_MERGE", 2515 NULL, REF_NO_DEREF); 2516 fprintf(stderr, 2517 _("dropping %s %s -- patch contents already upstream\n"), 2518 oid_to_hex(&commit->object.oid), msg.subject); 2519 } /* else allow == 0 and there's nothing special to do */ 2520 if (!opts->no_commit && !drop_commit) { 2521 if (author || command == TODO_REVERT || (flags & AMEND_MSG)) 2522 res = do_commit(r, msg_file, author, reflog_action, 2523 opts, flags, 2524 commit? &commit->object.oid : NULL); 2525 else 2526 res = error(_("unable to parse commit author")); 2527 *check_todo = !!(flags & EDIT_MSG); 2528 if (!res && reword) { 2529fast_forward_edit: 2530 /* 2531 * To reword we amend the commit we just 2532 * picked or fast-forwarded. As the commit has 2533 * already been picked we want to use the same 2534 * set of commit flags regardless of how we 2535 * got here. 2536 */ 2537 flags = EDIT_MSG | VERIFY_MSG | AMEND_MSG | ALLOW_EMPTY; 2538 res = run_git_commit(NULL, reflog_action, opts, flags); 2539 *check_todo = 1; 2540 } 2541 } 2542 2543 2544 if (!res && final_fixup) { 2545 unlink(rebase_path_fixup_msg()); 2546 unlink(rebase_path_squash_msg()); 2547 unlink(rebase_path_current_fixups()); 2548 strbuf_reset(&ctx->current_fixups); 2549 ctx->current_fixup_count = 0; 2550 } 2551 2552leave: 2553 free_message(commit, &msg); 2554 free(author); 2555 update_abort_safety_file(); 2556 2557 return res; 2558} 2559 2560static int prepare_revs(struct replay_opts *opts) 2561{ 2562 /* 2563 * picking (but not reverting) ranges (but not individual revisions) 2564 * should be done in reverse 2565 */ 2566 if (opts->action == REPLAY_PICK && !opts->revs->no_walk) 2567 opts->revs->reverse ^= 1; 2568 2569 if (prepare_revision_walk(opts->revs)) 2570 return error(_("revision walk setup failed")); 2571 2572 return 0; 2573} 2574 2575static int read_and_refresh_cache(struct repository *r, 2576 struct replay_opts *opts) 2577{ 2578 struct lock_file index_lock = LOCK_INIT; 2579 int index_fd = repo_hold_locked_index(r, &index_lock, 0); 2580 if (repo_read_index(r) < 0) { 2581 rollback_lock_file(&index_lock); 2582 return error(_("git %s: failed to read the index"), 2583 action_name(opts)); 2584 } 2585 refresh_index(r->index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL); 2586 2587 if (index_fd >= 0) { 2588 if (write_locked_index(r->index, &index_lock, 2589 COMMIT_LOCK | SKIP_IF_UNCHANGED)) { 2590 return error(_("git %s: failed to refresh the index"), 2591 action_name(opts)); 2592 } 2593 } 2594 2595 /* 2596 * If we are resolving merges in any way other than "ort", then 2597 * expand the sparse index. 2598 */ 2599 if (opts->strategy && strcmp(opts->strategy, "ort")) 2600 ensure_full_index(r->index); 2601 return 0; 2602} 2603 2604void todo_list_release(struct todo_list *todo_list) 2605{ 2606 strbuf_release(&todo_list->buf); 2607 FREE_AND_NULL(todo_list->items); 2608 todo_list->nr = todo_list->alloc = 0; 2609} 2610 2611static struct todo_item *append_new_todo(struct todo_list *todo_list) 2612{ 2613 ALLOC_GROW(todo_list->items, todo_list->nr + 1, todo_list->alloc); 2614 return todo_list->items + todo_list->nr++; 2615} 2616 2617const char *todo_item_get_arg(struct todo_list *todo_list, 2618 struct todo_item *item) 2619{ 2620 return todo_list->buf.buf + item->arg_offset; 2621} 2622 2623static int is_command(enum todo_command command, const char **bol) 2624{ 2625 const char *str = todo_command_info[command].str; 2626 const char nick = todo_command_info[command].c; 2627 const char *p = *bol; 2628 2629 if ((skip_prefix(p, str, &p) || (nick && *p++ == nick)) && 2630 (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r' || !*p)) { 2631 *bol = p; 2632 return 1; 2633 } 2634 return 0; 2635} 2636 2637static int check_label_or_ref_arg(enum todo_command command, const char *arg) 2638{ 2639 switch (command) { 2640 case TODO_LABEL: 2641 /* 2642 * '#' is not a valid label as the merge command uses it to 2643 * separate merge parents from the commit subject. 2644 */ 2645 if (!strcmp(arg, "#") || 2646 check_refname_format(arg, REFNAME_ALLOW_ONELEVEL)) 2647 return error(_("'%s' is not a valid label"), arg); 2648 break; 2649 2650 case TODO_UPDATE_REF: 2651 if (check_refname_format(arg, REFNAME_ALLOW_ONELEVEL)) 2652 return error(_("'%s' is not a valid refname"), arg); 2653 if (check_refname_format(arg, 0)) 2654 return error(_("update-ref requires a fully qualified " 2655 "refname e.g. refs/heads/%s"), arg); 2656 break; 2657 2658 default: 2659 BUG("unexpected todo_command"); 2660 } 2661 2662 return 0; 2663} 2664 2665static int check_merge_commit_insn(enum todo_command command) 2666{ 2667 switch(command) { 2668 case TODO_PICK: 2669 error(_("'%s' does not accept merge commits"), 2670 todo_command_info[command].str); 2671 advise_if_enabled(ADVICE_REBASE_TODO_ERROR, _( 2672 /* 2673 * TRANSLATORS: 'pick' and 'merge -C' should not be 2674 * translated. 2675 */ 2676 "'pick' does not take a merge commit. If you wanted to\n" 2677 "replay the merge, use 'merge -C' on the commit.")); 2678 return -1; 2679 2680 case TODO_REWORD: 2681 error(_("'%s' does not accept merge commits"), 2682 todo_command_info[command].str); 2683 advise_if_enabled(ADVICE_REBASE_TODO_ERROR, _( 2684 /* 2685 * TRANSLATORS: 'reword' and 'merge -c' should not be 2686 * translated. 2687 */ 2688 "'reword' does not take a merge commit. If you wanted to\n" 2689 "replay the merge and reword the commit message, use\n" 2690 "'merge -c' on the commit")); 2691 return -1; 2692 2693 case TODO_EDIT: 2694 error(_("'%s' does not accept merge commits"), 2695 todo_command_info[command].str); 2696 advise_if_enabled(ADVICE_REBASE_TODO_ERROR, _( 2697 /* 2698 * TRANSLATORS: 'edit', 'merge -C' and 'break' should 2699 * not be translated. 2700 */ 2701 "'edit' does not take a merge commit. If you wanted to\n" 2702 "replay the merge, use 'merge -C' on the commit, and then\n" 2703 "'break' to give the control back to you so that you can\n" 2704 "do 'git commit --amend && git rebase --continue'.")); 2705 return -1; 2706 2707 case TODO_FIXUP: 2708 case TODO_SQUASH: 2709 return error(_("cannot squash merge commit into another commit")); 2710 2711 case TODO_MERGE: 2712 case TODO_DROP: 2713 return 0; 2714 2715 default: 2716 BUG("unexpected todo_command"); 2717 } 2718} 2719 2720static int parse_insn_line(struct repository *r, struct replay_opts *opts, 2721 struct todo_item *item, const char *buf, 2722 const char *bol, char *eol) 2723{ 2724 struct object_id commit_oid; 2725 char *end_of_object_name; 2726 int i, saved, status, padding; 2727 2728 item->flags = 0; 2729 2730 /* left-trim */ 2731 bol += strspn(bol, " \t"); 2732 2733 if (bol == eol || *bol == '\r' || starts_with_mem(bol, eol - bol, comment_line_str)) { 2734 item->command = TODO_COMMENT; 2735 item->commit = NULL; 2736 item->arg_offset = bol - buf; 2737 item->arg_len = eol - bol; 2738 return 0; 2739 } 2740 2741 for (i = 0; i < TODO_COMMENT; i++) 2742 if (is_command(i, &bol)) { 2743 item->command = i; 2744 break; 2745 } 2746 if (i >= TODO_COMMENT) 2747 return error(_("invalid command '%.*s'"), 2748 (int)strcspn(bol, " \t\r\n"), bol); 2749 2750 /* Eat up extra spaces/ tabs before object name */ 2751 padding = strspn(bol, " \t"); 2752 bol += padding; 2753 2754 if (item->command == TODO_NOOP || item->command == TODO_BREAK) { 2755 if (bol != eol) 2756 return error(_("%s does not accept arguments: '%s'"), 2757 command_to_string(item->command), bol); 2758 item->commit = NULL; 2759 item->arg_offset = bol - buf; 2760 item->arg_len = eol - bol; 2761 return 0; 2762 } 2763 2764 if (!padding) 2765 return error(_("missing arguments for %s"), 2766 command_to_string(item->command)); 2767 2768 if (item->command == TODO_EXEC || item->command == TODO_LABEL || 2769 item->command == TODO_RESET || item->command == TODO_UPDATE_REF) { 2770 int ret = 0; 2771 2772 item->commit = NULL; 2773 item->arg_offset = bol - buf; 2774 item->arg_len = (int)(eol - bol); 2775 if (item->command == TODO_LABEL || 2776 item->command == TODO_UPDATE_REF) { 2777 saved = *eol; 2778 *eol = '\0'; 2779 ret = check_label_or_ref_arg(item->command, bol); 2780 *eol = saved; 2781 } 2782 return ret; 2783 } 2784 2785 if (item->command == TODO_FIXUP) { 2786 if (skip_prefix(bol, "-C", &bol)) { 2787 bol += strspn(bol, " \t"); 2788 item->flags |= TODO_REPLACE_FIXUP_MSG; 2789 } else if (skip_prefix(bol, "-c", &bol)) { 2790 bol += strspn(bol, " \t"); 2791 item->flags |= TODO_EDIT_FIXUP_MSG; 2792 } 2793 } 2794 2795 if (item->command == TODO_MERGE) { 2796 if (skip_prefix(bol, "-C", &bol)) 2797 bol += strspn(bol, " \t"); 2798 else if (skip_prefix(bol, "-c", &bol)) { 2799 bol += strspn(bol, " \t"); 2800 item->flags |= TODO_EDIT_MERGE_MSG; 2801 } else { 2802 item->flags |= TODO_EDIT_MERGE_MSG; 2803 item->commit = NULL; 2804 item->arg_offset = bol - buf; 2805 item->arg_len = (int)(eol - bol); 2806 return 0; 2807 } 2808 } 2809 2810 end_of_object_name = (char *) bol + strcspn(bol, " \t\n"); 2811 saved = *end_of_object_name; 2812 *end_of_object_name = '\0'; 2813 status = repo_get_oid(r, bol, &commit_oid); 2814 if (status < 0) 2815 error(_("could not parse '%s'"), bol); /* return later */ 2816 *end_of_object_name = saved; 2817 2818 bol = end_of_object_name + strspn(end_of_object_name, " \t"); 2819 item->arg_offset = bol - buf; 2820 item->arg_len = (int)(eol - bol); 2821 2822 if (status < 0) 2823 return status; 2824 2825 item->commit = lookup_commit_reference(r, &commit_oid); 2826 if (!item->commit) 2827 return -1; 2828 if (is_rebase_i(opts) && 2829 item->commit->parents && item->commit->parents->next) 2830 return check_merge_commit_insn(item->command); 2831 return 0; 2832} 2833 2834int sequencer_get_last_command(struct repository *r UNUSED, enum replay_action *action) 2835{ 2836 const char *todo_file, *bol; 2837 struct strbuf buf = STRBUF_INIT; 2838 int ret = 0; 2839 2840 todo_file = git_path_todo_file(); 2841 if (strbuf_read_file(&buf, todo_file, 0) < 0) { 2842 if (errno == ENOENT || errno == ENOTDIR) 2843 return -1; 2844 else 2845 return error_errno("unable to open '%s'", todo_file); 2846 } 2847 bol = buf.buf + strspn(buf.buf, " \t\r\n"); 2848 if (is_command(TODO_PICK, &bol) && (*bol == ' ' || *bol == '\t')) 2849 *action = REPLAY_PICK; 2850 else if (is_command(TODO_REVERT, &bol) && 2851 (*bol == ' ' || *bol == '\t')) 2852 *action = REPLAY_REVERT; 2853 else 2854 ret = -1; 2855 2856 strbuf_release(&buf); 2857 2858 return ret; 2859} 2860 2861int todo_list_parse_insn_buffer(struct repository *r, struct replay_opts *opts, 2862 char *buf, struct todo_list *todo_list) 2863{ 2864 struct todo_item *item; 2865 char *p = buf, *next_p; 2866 int i, res = 0, fixup_okay = file_exists(rebase_path_done()); 2867 2868 todo_list->current = todo_list->nr = todo_list->total_nr = 0; 2869 2870 for (i = 1; *p; i++, p = next_p) { 2871 char *eol = strchrnul(p, '\n'); 2872 2873 next_p = *eol ? eol + 1 /* skip LF */ : eol; 2874 2875 if (p != eol && eol[-1] == '\r') 2876 eol--; /* strip Carriage Return */ 2877 2878 item = append_new_todo(todo_list); 2879 item->offset_in_buf = p - todo_list->buf.buf; 2880 if (parse_insn_line(r, opts, item, buf, p, eol)) { 2881 res = error(_("invalid line %d: %.*s"), 2882 i, (int)(eol - p), p); 2883 item->command = TODO_COMMENT + 1; 2884 item->arg_offset = p - buf; 2885 item->arg_len = (int)(eol - p); 2886 item->commit = NULL; 2887 } 2888 2889 if (item->command != TODO_COMMENT) 2890 todo_list->total_nr++; 2891 2892 if (fixup_okay) 2893 ; /* do nothing */ 2894 else if (is_fixup(item->command)) 2895 res = error(_("cannot '%s' without a previous commit"), 2896 command_to_string(item->command)); 2897 else if (!is_noop(item->command)) 2898 fixup_okay = 1; 2899 } 2900 2901 return res; 2902} 2903 2904static int count_commands(struct todo_list *todo_list) 2905{ 2906 int count = 0, i; 2907 2908 for (i = 0; i < todo_list->nr; i++) 2909 if (todo_list->items[i].command != TODO_COMMENT) 2910 count++; 2911 2912 return count; 2913} 2914 2915static int get_item_line_offset(struct todo_list *todo_list, int index) 2916{ 2917 return index < todo_list->nr ? 2918 todo_list->items[index].offset_in_buf : todo_list->buf.len; 2919} 2920 2921static const char *get_item_line(struct todo_list *todo_list, int index) 2922{ 2923 return todo_list->buf.buf + get_item_line_offset(todo_list, index); 2924} 2925 2926static int get_item_line_length(struct todo_list *todo_list, int index) 2927{ 2928 return get_item_line_offset(todo_list, index + 1) 2929 - get_item_line_offset(todo_list, index); 2930} 2931 2932static ssize_t strbuf_read_file_or_whine(struct strbuf *sb, const char *path) 2933{ 2934 int fd; 2935 ssize_t len; 2936 2937 fd = open(path, O_RDONLY); 2938 if (fd < 0) 2939 return error_errno(_("could not open '%s'"), path); 2940 len = strbuf_read(sb, fd, 0); 2941 close(fd); 2942 if (len < 0) 2943 return error(_("could not read '%s'."), path); 2944 return len; 2945} 2946 2947static int have_finished_the_last_pick(void) 2948{ 2949 struct strbuf buf = STRBUF_INIT; 2950 const char *eol; 2951 const char *todo_path = git_path_todo_file(); 2952 int ret = 0; 2953 2954 if (strbuf_read_file(&buf, todo_path, 0) < 0) { 2955 if (errno == ENOENT) { 2956 return 0; 2957 } else { 2958 error_errno("unable to open '%s'", todo_path); 2959 return 0; 2960 } 2961 } 2962 /* If there is only one line then we are done */ 2963 eol = strchr(buf.buf, '\n'); 2964 if (!eol || !eol[1]) 2965 ret = 1; 2966 2967 strbuf_release(&buf); 2968 2969 return ret; 2970} 2971 2972void sequencer_post_commit_cleanup(struct repository *r, int verbose) 2973{ 2974 struct replay_opts opts = REPLAY_OPTS_INIT; 2975 int need_cleanup = 0; 2976 2977 if (refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD")) { 2978 if (!refs_delete_ref(get_main_ref_store(r), "", 2979 "CHERRY_PICK_HEAD", NULL, REF_NO_DEREF) && 2980 verbose) 2981 warning(_("cancelling a cherry picking in progress")); 2982 opts.action = REPLAY_PICK; 2983 need_cleanup = 1; 2984 } 2985 2986 if (refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) { 2987 if (!refs_delete_ref(get_main_ref_store(r), "", "REVERT_HEAD", 2988 NULL, REF_NO_DEREF) && 2989 verbose) 2990 warning(_("cancelling a revert in progress")); 2991 opts.action = REPLAY_REVERT; 2992 need_cleanup = 1; 2993 } 2994 2995 refs_delete_ref(get_main_ref_store(r), "", "AUTO_MERGE", 2996 NULL, REF_NO_DEREF); 2997 2998 if (!need_cleanup) 2999 goto out; 3000 3001 if (!have_finished_the_last_pick()) 3002 goto out; 3003 3004 sequencer_remove_state(&opts); 3005out: 3006 replay_opts_release(&opts); 3007} 3008 3009static void todo_list_write_total_nr(struct todo_list *todo_list) 3010{ 3011 FILE *f = fopen_or_warn(rebase_path_msgtotal(), "w"); 3012 3013 if (f) { 3014 fprintf(f, "%d\n", todo_list->total_nr); 3015 fclose(f); 3016 } 3017} 3018 3019static int read_populate_todo(struct repository *r, 3020 struct todo_list *todo_list, 3021 struct replay_opts *opts) 3022{ 3023 const char *todo_file = get_todo_path(opts); 3024 int res; 3025 3026 strbuf_reset(&todo_list->buf); 3027 if (strbuf_read_file_or_whine(&todo_list->buf, todo_file) < 0) 3028 return -1; 3029 3030 res = todo_list_parse_insn_buffer(r, opts, todo_list->buf.buf, todo_list); 3031 if (res) { 3032 if (is_rebase_i(opts)) 3033 return error(_("please fix this using " 3034 "'git rebase --edit-todo'.")); 3035 return error(_("unusable instruction sheet: '%s'"), todo_file); 3036 } 3037 3038 if (!todo_list->nr && 3039 (!is_rebase_i(opts) || !file_exists(rebase_path_done()))) 3040 return error(_("no commits parsed.")); 3041 3042 if (!is_rebase_i(opts)) { 3043 enum todo_command valid = 3044 opts->action == REPLAY_PICK ? TODO_PICK : TODO_REVERT; 3045 int i; 3046 3047 for (i = 0; i < todo_list->nr; i++) 3048 if (valid == todo_list->items[i].command) 3049 continue; 3050 else if (valid == TODO_PICK) 3051 return error(_("cannot cherry-pick during a revert.")); 3052 else 3053 return error(_("cannot revert during a cherry-pick.")); 3054 } 3055 3056 if (is_rebase_i(opts)) { 3057 struct todo_list done = TODO_LIST_INIT; 3058 3059 if (strbuf_read_file(&done.buf, rebase_path_done(), 0) > 0 && 3060 !todo_list_parse_insn_buffer(r, opts, done.buf.buf, &done)) 3061 todo_list->done_nr = count_commands(&done); 3062 else 3063 todo_list->done_nr = 0; 3064 3065 todo_list->total_nr = todo_list->done_nr 3066 + count_commands(todo_list); 3067 todo_list_release(&done); 3068 3069 todo_list_write_total_nr(todo_list); 3070 } 3071 3072 return 0; 3073} 3074 3075static int git_config_string_dup(char **dest, 3076 const char *var, const char *value) 3077{ 3078 if (!value) 3079 return config_error_nonbool(var); 3080 free(*dest); 3081 *dest = xstrdup(value); 3082 return 0; 3083} 3084 3085static int populate_opts_cb(const char *key, const char *value, 3086 const struct config_context *ctx, 3087 void *data) 3088{ 3089 struct replay_opts *opts = data; 3090 int error_flag = 1; 3091 3092 if (!value) 3093 error_flag = 0; 3094 else if (!strcmp(key, "options.no-commit")) 3095 opts->no_commit = git_config_bool_or_int(key, value, ctx->kvi, &error_flag); 3096 else if (!strcmp(key, "options.edit")) 3097 opts->edit = git_config_bool_or_int(key, value, ctx->kvi, &error_flag); 3098 else if (!strcmp(key, "options.allow-empty")) 3099 opts->allow_empty = 3100 git_config_bool_or_int(key, value, ctx->kvi, &error_flag); 3101 else if (!strcmp(key, "options.allow-empty-message")) 3102 opts->allow_empty_message = 3103 git_config_bool_or_int(key, value, ctx->kvi, &error_flag); 3104 else if (!strcmp(key, "options.drop-redundant-commits")) 3105 opts->drop_redundant_commits = 3106 git_config_bool_or_int(key, value, ctx->kvi, &error_flag); 3107 else if (!strcmp(key, "options.keep-redundant-commits")) 3108 opts->keep_redundant_commits = 3109 git_config_bool_or_int(key, value, ctx->kvi, &error_flag); 3110 else if (!strcmp(key, "options.signoff")) 3111 opts->signoff = git_config_bool_or_int(key, value, ctx->kvi, &error_flag); 3112 else if (!strcmp(key, "options.record-origin")) 3113 opts->record_origin = git_config_bool_or_int(key, value, ctx->kvi, &error_flag); 3114 else if (!strcmp(key, "options.allow-ff")) 3115 opts->allow_ff = git_config_bool_or_int(key, value, ctx->kvi, &error_flag); 3116 else if (!strcmp(key, "options.mainline")) 3117 opts->mainline = git_config_int(key, value, ctx->kvi); 3118 else if (!strcmp(key, "options.strategy")) 3119 git_config_string_dup(&opts->strategy, key, value); 3120 else if (!strcmp(key, "options.gpg-sign")) 3121 git_config_string_dup(&opts->gpg_sign, key, value); 3122 else if (!strcmp(key, "options.strategy-option")) { 3123 strvec_push(&opts->xopts, value); 3124 } else if (!strcmp(key, "options.allow-rerere-auto")) 3125 opts->allow_rerere_auto = 3126 git_config_bool_or_int(key, value, ctx->kvi, &error_flag) ? 3127 RERERE_AUTOUPDATE : RERERE_NOAUTOUPDATE; 3128 else if (!strcmp(key, "options.default-msg-cleanup")) { 3129 opts->explicit_cleanup = 1; 3130 opts->default_msg_cleanup = get_cleanup_mode(value, 1); 3131 } else 3132 return error(_("invalid key: %s"), key); 3133 3134 if (!error_flag) 3135 return error(_("invalid value for '%s': '%s'"), key, value); 3136 3137 return 0; 3138} 3139 3140static void parse_strategy_opts(struct replay_opts *opts, char *raw_opts) 3141{ 3142 int i; 3143 int count; 3144 const char **argv; 3145 char *strategy_opts_string = raw_opts; 3146 3147 if (*strategy_opts_string == ' ') 3148 strategy_opts_string++; 3149 3150 count = split_cmdline(strategy_opts_string, &argv); 3151 if (count < 0) 3152 BUG("could not split '%s': %s", strategy_opts_string, 3153 split_cmdline_strerror(count)); 3154 for (i = 0; i < count; i++) { 3155 const char *arg = argv[i]; 3156 3157 skip_prefix(arg, "--", &arg); 3158 strvec_push(&opts->xopts, arg); 3159 } 3160 free(argv); 3161} 3162 3163static void read_strategy_opts(struct replay_opts *opts, struct strbuf *buf) 3164{ 3165 strbuf_reset(buf); 3166 if (!read_oneliner(buf, rebase_path_strategy(), 0)) 3167 return; 3168 opts->strategy = strbuf_detach(buf, NULL); 3169 if (!read_oneliner(buf, rebase_path_strategy_opts(), 0)) 3170 return; 3171 3172 parse_strategy_opts(opts, buf->buf); 3173} 3174 3175static int read_populate_opts(struct replay_opts *opts) 3176{ 3177 struct replay_ctx *ctx = opts->ctx; 3178 3179 if (is_rebase_i(opts)) { 3180 struct strbuf buf = STRBUF_INIT; 3181 int ret = 0; 3182 3183 if (read_oneliner(&buf, rebase_path_gpg_sign_opt(), 3184 READ_ONELINER_SKIP_IF_EMPTY)) { 3185 if (!starts_with(buf.buf, "-S")) 3186 strbuf_reset(&buf); 3187 else { 3188 free(opts->gpg_sign); 3189 opts->gpg_sign = xstrdup(buf.buf + 2); 3190 } 3191 strbuf_reset(&buf); 3192 } 3193 3194 if (read_oneliner(&buf, rebase_path_allow_rerere_autoupdate(), 3195 READ_ONELINER_SKIP_IF_EMPTY)) { 3196 if (!strcmp(buf.buf, "--rerere-autoupdate")) 3197 opts->allow_rerere_auto = RERERE_AUTOUPDATE; 3198 else if (!strcmp(buf.buf, "--no-rerere-autoupdate")) 3199 opts->allow_rerere_auto = RERERE_NOAUTOUPDATE; 3200 strbuf_reset(&buf); 3201 } 3202 3203 if (file_exists(rebase_path_verbose())) 3204 opts->verbose = 1; 3205 3206 if (file_exists(rebase_path_quiet())) 3207 opts->quiet = 1; 3208 3209 if (file_exists(rebase_path_signoff())) { 3210 opts->allow_ff = 0; 3211 opts->signoff = 1; 3212 } 3213 3214 if (file_exists(rebase_path_cdate_is_adate())) { 3215 opts->allow_ff = 0; 3216 opts->committer_date_is_author_date = 1; 3217 } 3218 3219 if (file_exists(rebase_path_ignore_date())) { 3220 opts->allow_ff = 0; 3221 opts->ignore_date = 1; 3222 } 3223 3224 if (file_exists(rebase_path_reschedule_failed_exec())) 3225 opts->reschedule_failed_exec = 1; 3226 else if (file_exists(rebase_path_no_reschedule_failed_exec())) 3227 opts->reschedule_failed_exec = 0; 3228 3229 if (file_exists(rebase_path_drop_redundant_commits())) 3230 opts->drop_redundant_commits = 1; 3231 3232 if (file_exists(rebase_path_keep_redundant_commits())) 3233 opts->keep_redundant_commits = 1; 3234 3235 read_strategy_opts(opts, &buf); 3236 strbuf_reset(&buf); 3237 3238 if (read_oneliner(&ctx->current_fixups, 3239 rebase_path_current_fixups(), 3240 READ_ONELINER_SKIP_IF_EMPTY)) { 3241 const char *p = ctx->current_fixups.buf; 3242 ctx->current_fixup_count = 1; 3243 while ((p = strchr(p, '\n'))) { 3244 ctx->current_fixup_count++; 3245 p++; 3246 } 3247 } 3248 3249 if (read_oneliner(&buf, rebase_path_squash_onto(), 0)) { 3250 if (repo_get_oid_committish(the_repository, buf.buf, &opts->squash_onto) < 0) { 3251 ret = error(_("unusable squash-onto")); 3252 goto done_rebase_i; 3253 } 3254 opts->have_squash_onto = 1; 3255 } 3256 3257done_rebase_i: 3258 strbuf_release(&buf); 3259 return ret; 3260 } 3261 3262 if (!file_exists(git_path_opts_file())) 3263 return 0; 3264 /* 3265 * The function git_parse_source(), called from git_config_from_file(), 3266 * may die() in case of a syntactically incorrect file. We do not care 3267 * about this case, though, because we wrote that file ourselves, so we 3268 * are pretty certain that it is syntactically correct. 3269 */ 3270 if (git_config_from_file(populate_opts_cb, git_path_opts_file(), opts) < 0) 3271 return error(_("malformed options sheet: '%s'"), 3272 git_path_opts_file()); 3273 return 0; 3274} 3275 3276static void write_strategy_opts(struct replay_opts *opts) 3277{ 3278 struct strbuf buf = STRBUF_INIT; 3279 3280 /* 3281 * Quote strategy options so that they can be read correctly 3282 * by split_cmdline(). 3283 */ 3284 quote_cmdline(&buf, opts->xopts.v); 3285 write_file(rebase_path_strategy_opts(), "%s\n", buf.buf); 3286 strbuf_release(&buf); 3287} 3288 3289int write_basic_state(struct replay_opts *opts, const char *head_name, 3290 struct commit *onto, const struct object_id *orig_head) 3291{ 3292 if (head_name) 3293 write_file(rebase_path_head_name(), "%s\n", head_name); 3294 if (onto) 3295 write_file(rebase_path_onto(), "%s\n", 3296 oid_to_hex(&onto->object.oid)); 3297 if (orig_head) 3298 write_file(rebase_path_orig_head(), "%s\n", 3299 oid_to_hex(orig_head)); 3300 3301 if (opts->quiet) 3302 write_file(rebase_path_quiet(), "%s", ""); 3303 if (opts->verbose) 3304 write_file(rebase_path_verbose(), "%s", ""); 3305 if (opts->strategy) 3306 write_file(rebase_path_strategy(), "%s\n", opts->strategy); 3307 if (opts->xopts.nr > 0) 3308 write_strategy_opts(opts); 3309 3310 if (opts->allow_rerere_auto == RERERE_AUTOUPDATE) 3311 write_file(rebase_path_allow_rerere_autoupdate(), "--rerere-autoupdate\n"); 3312 else if (opts->allow_rerere_auto == RERERE_NOAUTOUPDATE) 3313 write_file(rebase_path_allow_rerere_autoupdate(), "--no-rerere-autoupdate\n"); 3314 3315 if (opts->gpg_sign) 3316 write_file(rebase_path_gpg_sign_opt(), "-S%s\n", opts->gpg_sign); 3317 if (opts->signoff) 3318 write_file(rebase_path_signoff(), "--signoff\n"); 3319 if (opts->drop_redundant_commits) 3320 write_file(rebase_path_drop_redundant_commits(), "%s", ""); 3321 if (opts->keep_redundant_commits) 3322 write_file(rebase_path_keep_redundant_commits(), "%s", ""); 3323 if (opts->committer_date_is_author_date) 3324 write_file(rebase_path_cdate_is_adate(), "%s", ""); 3325 if (opts->ignore_date) 3326 write_file(rebase_path_ignore_date(), "%s", ""); 3327 if (opts->reschedule_failed_exec) 3328 write_file(rebase_path_reschedule_failed_exec(), "%s", ""); 3329 else 3330 write_file(rebase_path_no_reschedule_failed_exec(), "%s", ""); 3331 3332 return 0; 3333} 3334 3335static int walk_revs_populate_todo(struct todo_list *todo_list, 3336 struct replay_opts *opts) 3337{ 3338 enum todo_command command = opts->action == REPLAY_PICK ? 3339 TODO_PICK : TODO_REVERT; 3340 const char *command_string = todo_command_info[command].str; 3341 const char *encoding; 3342 struct commit *commit; 3343 3344 if (prepare_revs(opts)) 3345 return -1; 3346 3347 encoding = get_log_output_encoding(); 3348 3349 while ((commit = get_revision(opts->revs))) { 3350 struct todo_item *item = append_new_todo(todo_list); 3351 const char *commit_buffer = repo_logmsg_reencode(the_repository, 3352 commit, NULL, 3353 encoding); 3354 const char *subject; 3355 int subject_len; 3356 3357 item->command = command; 3358 item->commit = commit; 3359 item->arg_offset = 0; 3360 item->arg_len = 0; 3361 item->offset_in_buf = todo_list->buf.len; 3362 subject_len = find_commit_subject(commit_buffer, &subject); 3363 strbuf_addf(&todo_list->buf, "%s %s %.*s\n", command_string, 3364 short_commit_name(the_repository, commit), 3365 subject_len, subject); 3366 repo_unuse_commit_buffer(the_repository, commit, 3367 commit_buffer); 3368 } 3369 3370 if (!todo_list->nr) 3371 return error(_("empty commit set passed")); 3372 3373 return 0; 3374} 3375 3376static int create_seq_dir(struct repository *r) 3377{ 3378 enum replay_action action; 3379 const char *in_progress_error = NULL; 3380 const char *in_progress_advice = NULL; 3381 unsigned int advise_skip = 3382 refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD") || 3383 refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD"); 3384 3385 if (!sequencer_get_last_command(r, &action)) { 3386 switch (action) { 3387 case REPLAY_REVERT: 3388 in_progress_error = _("revert is already in progress"); 3389 in_progress_advice = 3390 _("try \"git revert (--continue | %s--abort | --quit)\""); 3391 break; 3392 case REPLAY_PICK: 3393 in_progress_error = _("cherry-pick is already in progress"); 3394 in_progress_advice = 3395 _("try \"git cherry-pick (--continue | %s--abort | --quit)\""); 3396 break; 3397 default: 3398 BUG("unexpected action in create_seq_dir"); 3399 } 3400 } 3401 if (in_progress_error) { 3402 error("%s", in_progress_error); 3403 if (advice_enabled(ADVICE_SEQUENCER_IN_USE)) 3404 advise(in_progress_advice, 3405 advise_skip ? "--skip | " : ""); 3406 return -1; 3407 } 3408 if (mkdir(git_path_seq_dir(), 0777) < 0) 3409 return error_errno(_("could not create sequencer directory '%s'"), 3410 git_path_seq_dir()); 3411 3412 return 0; 3413} 3414 3415static int save_head(const char *head) 3416{ 3417 return write_message(head, strlen(head), git_path_head_file(), 1); 3418} 3419 3420static int rollback_is_safe(void) 3421{ 3422 struct strbuf sb = STRBUF_INIT; 3423 struct object_id expected_head, actual_head; 3424 3425 if (strbuf_read_file(&sb, git_path_abort_safety_file(), 0) >= 0) { 3426 strbuf_trim(&sb); 3427 if (get_oid_hex(sb.buf, &expected_head)) { 3428 strbuf_release(&sb); 3429 die(_("could not parse %s"), git_path_abort_safety_file()); 3430 } 3431 strbuf_release(&sb); 3432 } 3433 else if (errno == ENOENT) 3434 oidclr(&expected_head, the_repository->hash_algo); 3435 else 3436 die_errno(_("could not read '%s'"), git_path_abort_safety_file()); 3437 3438 if (repo_get_oid(the_repository, "HEAD", &actual_head)) 3439 oidclr(&actual_head, the_repository->hash_algo); 3440 3441 return oideq(&actual_head, &expected_head); 3442} 3443 3444static int reset_merge(const struct object_id *oid) 3445{ 3446 struct child_process cmd = CHILD_PROCESS_INIT; 3447 3448 cmd.git_cmd = 1; 3449 strvec_pushl(&cmd.args, "reset", "--merge", NULL); 3450 3451 if (!is_null_oid(oid)) 3452 strvec_push(&cmd.args, oid_to_hex(oid)); 3453 3454 return run_command(&cmd); 3455} 3456 3457static int rollback_single_pick(struct repository *r) 3458{ 3459 struct object_id head_oid; 3460 3461 if (!refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD") && 3462 !refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) 3463 return error(_("no cherry-pick or revert in progress")); 3464 if (refs_read_ref_full(get_main_ref_store(the_repository), "HEAD", 0, &head_oid, NULL)) 3465 return error(_("cannot resolve HEAD")); 3466 if (is_null_oid(&head_oid)) 3467 return error(_("cannot abort from a branch yet to be born")); 3468 return reset_merge(&head_oid); 3469} 3470 3471static int skip_single_pick(void) 3472{ 3473 struct object_id head; 3474 3475 if (refs_read_ref_full(get_main_ref_store(the_repository), "HEAD", 0, &head, NULL)) 3476 return error(_("cannot resolve HEAD")); 3477 return reset_merge(&head); 3478} 3479 3480int sequencer_rollback(struct repository *r, struct replay_opts *opts) 3481{ 3482 FILE *f; 3483 struct object_id oid; 3484 struct strbuf buf = STRBUF_INIT; 3485 const char *p; 3486 3487 f = fopen(git_path_head_file(), "r"); 3488 if (!f && errno == ENOENT) { 3489 /* 3490 * There is no multiple-cherry-pick in progress. 3491 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates 3492 * a single-cherry-pick in progress, abort that. 3493 */ 3494 return rollback_single_pick(r); 3495 } 3496 if (!f) 3497 return error_errno(_("cannot open '%s'"), git_path_head_file()); 3498 if (strbuf_getline_lf(&buf, f)) { 3499 error(_("cannot read '%s': %s"), git_path_head_file(), 3500 ferror(f) ? strerror(errno) : _("unexpected end of file")); 3501 fclose(f); 3502 goto fail; 3503 } 3504 fclose(f); 3505 if (parse_oid_hex(buf.buf, &oid, &p) || *p != '\0') { 3506 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"), 3507 git_path_head_file()); 3508 goto fail; 3509 } 3510 if (is_null_oid(&oid)) { 3511 error(_("cannot abort from a branch yet to be born")); 3512 goto fail; 3513 } 3514 3515 if (!rollback_is_safe()) { 3516 /* Do not error, just do not rollback */ 3517 warning(_("You seem to have moved HEAD. " 3518 "Not rewinding, check your HEAD!")); 3519 } else 3520 if (reset_merge(&oid)) 3521 goto fail; 3522 strbuf_release(&buf); 3523 return sequencer_remove_state(opts); 3524fail: 3525 strbuf_release(&buf); 3526 return -1; 3527} 3528 3529int sequencer_skip(struct repository *r, struct replay_opts *opts) 3530{ 3531 enum replay_action action = -1; 3532 sequencer_get_last_command(r, &action); 3533 3534 /* 3535 * Check whether the subcommand requested to skip the commit is actually 3536 * in progress and that it's safe to skip the commit. 3537 * 3538 * opts->action tells us which subcommand requested to skip the commit. 3539 * If the corresponding .git/<ACTION>_HEAD exists, we know that the 3540 * action is in progress and we can skip the commit. 3541 * 3542 * Otherwise we check that the last instruction was related to the 3543 * particular subcommand we're trying to execute and barf if that's not 3544 * the case. 3545 * 3546 * Finally we check that the rollback is "safe", i.e., has the HEAD 3547 * moved? In this case, it doesn't make sense to "reset the merge" and 3548 * "skip the commit" as the user already handled this by committing. But 3549 * we'd not want to barf here, instead give advice on how to proceed. We 3550 * only need to check that when .git/<ACTION>_HEAD doesn't exist because 3551 * it gets removed when the user commits, so if it still exists we're 3552 * sure the user can't have committed before. 3553 */ 3554 switch (opts->action) { 3555 case REPLAY_REVERT: 3556 if (!refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) { 3557 if (action != REPLAY_REVERT) 3558 return error(_("no revert in progress")); 3559 if (!rollback_is_safe()) 3560 goto give_advice; 3561 } 3562 break; 3563 case REPLAY_PICK: 3564 if (!refs_ref_exists(get_main_ref_store(r), 3565 "CHERRY_PICK_HEAD")) { 3566 if (action != REPLAY_PICK) 3567 return error(_("no cherry-pick in progress")); 3568 if (!rollback_is_safe()) 3569 goto give_advice; 3570 } 3571 break; 3572 default: 3573 BUG("unexpected action in sequencer_skip"); 3574 } 3575 3576 if (skip_single_pick()) 3577 return error(_("failed to skip the commit")); 3578 if (!is_directory(git_path_seq_dir())) 3579 return 0; 3580 3581 return sequencer_continue(r, opts); 3582 3583give_advice: 3584 error(_("there is nothing to skip")); 3585 3586 if (advice_enabled(ADVICE_RESOLVE_CONFLICT)) { 3587 advise(_("have you committed already?\n" 3588 "try \"git %s --continue\""), 3589 action == REPLAY_REVERT ? "revert" : "cherry-pick"); 3590 } 3591 return -1; 3592} 3593 3594static int save_todo(struct todo_list *todo_list, struct replay_opts *opts, 3595 int reschedule) 3596{ 3597 struct lock_file todo_lock = LOCK_INIT; 3598 const char *todo_path = get_todo_path(opts); 3599 int next = todo_list->current, offset, fd; 3600 3601 /* 3602 * rebase -i writes "git-rebase-todo" without the currently executing 3603 * command, appending it to "done" instead. 3604 */ 3605 if (is_rebase_i(opts) && !reschedule) 3606 next++; 3607 3608 fd = hold_lock_file_for_update(&todo_lock, todo_path, 0); 3609 if (fd < 0) 3610 return error_errno(_("could not lock '%s'"), todo_path); 3611 offset = get_item_line_offset(todo_list, next); 3612 if (write_in_full(fd, todo_list->buf.buf + offset, 3613 todo_list->buf.len - offset) < 0) 3614 return error_errno(_("could not write to '%s'"), todo_path); 3615 if (commit_lock_file(&todo_lock) < 0) 3616 return error(_("failed to finalize '%s'"), todo_path); 3617 3618 if (is_rebase_i(opts) && !reschedule && next > 0) { 3619 const char *done = rebase_path_done(); 3620 int fd = open(done, O_CREAT | O_WRONLY | O_APPEND, 0666); 3621 int ret = 0; 3622 3623 if (fd < 0) 3624 return 0; 3625 if (write_in_full(fd, get_item_line(todo_list, next - 1), 3626 get_item_line_length(todo_list, next - 1)) 3627 < 0) 3628 ret = error_errno(_("could not write to '%s'"), done); 3629 if (close(fd) < 0) 3630 ret = error_errno(_("failed to finalize '%s'"), done); 3631 return ret; 3632 } 3633 return 0; 3634} 3635 3636static int save_opts(struct replay_opts *opts) 3637{ 3638 const char *opts_file = git_path_opts_file(); 3639 int res = 0; 3640 3641 if (opts->no_commit) 3642 res |= repo_config_set_in_file_gently(the_repository, opts_file, 3643 "options.no-commit", NULL, "true"); 3644 if (opts->edit >= 0) 3645 res |= repo_config_set_in_file_gently(the_repository, opts_file, "options.edit", NULL, 3646 opts->edit ? "true" : "false"); 3647 if (opts->allow_empty) 3648 res |= repo_config_set_in_file_gently(the_repository, opts_file, 3649 "options.allow-empty", NULL, "true"); 3650 if (opts->allow_empty_message) 3651 res |= repo_config_set_in_file_gently(the_repository, opts_file, 3652 "options.allow-empty-message", NULL, "true"); 3653 if (opts->drop_redundant_commits) 3654 res |= repo_config_set_in_file_gently(the_repository, opts_file, 3655 "options.drop-redundant-commits", NULL, "true"); 3656 if (opts->keep_redundant_commits) 3657 res |= repo_config_set_in_file_gently(the_repository, opts_file, 3658 "options.keep-redundant-commits", NULL, "true"); 3659 if (opts->signoff) 3660 res |= repo_config_set_in_file_gently(the_repository, opts_file, 3661 "options.signoff", NULL, "true"); 3662 if (opts->record_origin) 3663 res |= repo_config_set_in_file_gently(the_repository, opts_file, 3664 "options.record-origin", NULL, "true"); 3665 if (opts->allow_ff) 3666 res |= repo_config_set_in_file_gently(the_repository, opts_file, 3667 "options.allow-ff", NULL, "true"); 3668 if (opts->mainline) { 3669 struct strbuf buf = STRBUF_INIT; 3670 strbuf_addf(&buf, "%d", opts->mainline); 3671 res |= repo_config_set_in_file_gently(the_repository, opts_file, 3672 "options.mainline", NULL, buf.buf); 3673 strbuf_release(&buf); 3674 } 3675 if (opts->strategy) 3676 res |= repo_config_set_in_file_gently(the_repository, opts_file, 3677 "options.strategy", NULL, opts->strategy); 3678 if (opts->gpg_sign) 3679 res |= repo_config_set_in_file_gently(the_repository, opts_file, 3680 "options.gpg-sign", NULL, opts->gpg_sign); 3681 for (size_t i = 0; i < opts->xopts.nr; i++) 3682 res |= repo_config_set_multivar_in_file_gently(the_repository, opts_file, 3683 "options.strategy-option", 3684 opts->xopts.v[i], "^$", NULL, 0); 3685 if (opts->allow_rerere_auto) 3686 res |= repo_config_set_in_file_gently(the_repository, opts_file, 3687 "options.allow-rerere-auto", NULL, 3688 opts->allow_rerere_auto == RERERE_AUTOUPDATE ? 3689 "true" : "false"); 3690 3691 if (opts->explicit_cleanup) 3692 res |= repo_config_set_in_file_gently(the_repository, opts_file, 3693 "options.default-msg-cleanup", NULL, 3694 describe_cleanup_mode(opts->default_msg_cleanup)); 3695 return res; 3696} 3697 3698static int make_patch(struct repository *r, 3699 struct commit *commit, 3700 struct replay_opts *opts) 3701{ 3702 struct rev_info log_tree_opt; 3703 const char *subject; 3704 char hex[GIT_MAX_HEXSZ + 1]; 3705 int res = 0; 3706 3707 if (!is_rebase_i(opts)) 3708 BUG("make_patch should only be called when rebasing"); 3709 3710 oid_to_hex_r(hex, &commit->object.oid); 3711 if (write_message(hex, strlen(hex), rebase_path_stopped_sha(), 1) < 0) 3712 return -1; 3713 res |= write_rebase_head(&commit->object.oid); 3714 3715 memset(&log_tree_opt, 0, sizeof(log_tree_opt)); 3716 repo_init_revisions(r, &log_tree_opt, NULL); 3717 log_tree_opt.abbrev = 0; 3718 log_tree_opt.diff = 1; 3719 log_tree_opt.diffopt.output_format = DIFF_FORMAT_PATCH; 3720 log_tree_opt.disable_stdin = 1; 3721 log_tree_opt.no_commit_id = 1; 3722 log_tree_opt.diffopt.file = fopen(rebase_path_patch(), "w"); 3723 log_tree_opt.diffopt.use_color = GIT_COLOR_NEVER; 3724 if (!log_tree_opt.diffopt.file) 3725 res |= error_errno(_("could not open '%s'"), 3726 rebase_path_patch()); 3727 else { 3728 res |= log_tree_commit(&log_tree_opt, commit); 3729 fclose(log_tree_opt.diffopt.file); 3730 } 3731 3732 if (!file_exists(rebase_path_message())) { 3733 const char *encoding = get_commit_output_encoding(); 3734 const char *commit_buffer = repo_logmsg_reencode(r, 3735 commit, NULL, 3736 encoding); 3737 find_commit_subject(commit_buffer, &subject); 3738 res |= write_message(subject, strlen(subject), rebase_path_message(), 1); 3739 repo_unuse_commit_buffer(r, commit, 3740 commit_buffer); 3741 } 3742 release_revisions(&log_tree_opt); 3743 3744 return res; 3745} 3746 3747static int intend_to_amend(void) 3748{ 3749 struct object_id head; 3750 char *p; 3751 3752 if (repo_get_oid(the_repository, "HEAD", &head)) 3753 return error(_("cannot read HEAD")); 3754 3755 p = oid_to_hex(&head); 3756 return write_message(p, strlen(p), rebase_path_amend(), 1); 3757} 3758 3759static int error_with_patch(struct repository *r, 3760 struct commit *commit, 3761 const char *subject, int subject_len, 3762 struct replay_opts *opts, 3763 int exit_code, int to_amend) 3764{ 3765 struct replay_ctx *ctx = opts->ctx; 3766 3767 /* 3768 * Write the commit message to be used by "git rebase 3769 * --continue". If a "fixup" or "squash" command has conflicts 3770 * then we will have already written rebase_path_message() in 3771 * error_failed_squash(). If an "edit" command was 3772 * fast-forwarded then we don't have a message in ctx->message 3773 * and rely on make_patch() to write rebase_path_message() 3774 * instead. 3775 */ 3776 if (ctx->have_message && !file_exists(rebase_path_message()) && 3777 write_message(ctx->message.buf, ctx->message.len, 3778 rebase_path_message(), 0)) 3779 return error(_("could not write commit message file")); 3780 3781 if (commit && make_patch(r, commit, opts)) 3782 return -1; 3783 3784 if (to_amend) { 3785 if (intend_to_amend()) 3786 return -1; 3787 3788 fprintf(stderr, 3789 _("You can amend the commit now, with\n" 3790 "\n" 3791 " git commit --amend %s\n" 3792 "\n" 3793 "Once you are satisfied with your changes, run\n" 3794 "\n" 3795 " git rebase --continue\n"), 3796 gpg_sign_opt_quoted(opts)); 3797 } else if (exit_code) { 3798 if (commit) 3799 fprintf_ln(stderr, _("Could not apply %s... %.*s"), 3800 short_commit_name(r, commit), subject_len, subject); 3801 else 3802 /* 3803 * We don't have the hash of the parent so 3804 * just print the line from the todo file. 3805 */ 3806 fprintf_ln(stderr, _("Could not merge %.*s"), 3807 subject_len, subject); 3808 } 3809 3810 return exit_code; 3811} 3812 3813static int error_failed_squash(struct repository *r, 3814 struct commit *commit, 3815 struct replay_opts *opts, 3816 int subject_len, 3817 const char *subject) 3818{ 3819 if (copy_file(rebase_path_message(), rebase_path_squash_msg(), 0666)) 3820 return error(_("could not copy '%s' to '%s'"), 3821 rebase_path_squash_msg(), rebase_path_message()); 3822 unlink(git_path_merge_msg(r)); 3823 if (copy_file(git_path_merge_msg(r), rebase_path_message(), 0666)) 3824 return error(_("could not copy '%s' to '%s'"), 3825 rebase_path_message(), 3826 git_path_merge_msg(r)); 3827 return error_with_patch(r, commit, subject, subject_len, opts, 1, 0); 3828} 3829 3830static int do_exec(struct repository *r, const char *command_line, int quiet) 3831{ 3832 struct child_process cmd = CHILD_PROCESS_INIT; 3833 int dirty, status; 3834 3835 if (!quiet) 3836 fprintf(stderr, _("Executing: %s\n"), command_line); 3837 cmd.use_shell = 1; 3838 strvec_push(&cmd.args, command_line); 3839 strvec_push(&cmd.env, "GIT_CHERRY_PICK_HELP"); 3840 status = run_command(&cmd); 3841 3842 /* force re-reading of the cache */ 3843 discard_index(r->index); 3844 if (repo_read_index(r) < 0) 3845 return error(_("could not read index")); 3846 3847 dirty = require_clean_work_tree(r, "rebase", NULL, 1, 1); 3848 3849 if (status) { 3850 warning(_("execution failed: %s\n%s" 3851 "You can fix the problem, and then run\n" 3852 "\n" 3853 " git rebase --continue\n" 3854 "\n"), 3855 command_line, 3856 dirty ? _("and made changes to the index and/or the " 3857 "working tree.\n") : ""); 3858 if (status == 127) 3859 /* command not found */ 3860 status = 1; 3861 } else if (dirty) { 3862 warning(_("execution succeeded: %s\nbut " 3863 "left changes to the index and/or the working tree.\n" 3864 "Commit or stash your changes, and then run\n" 3865 "\n" 3866 " git rebase --continue\n" 3867 "\n"), command_line); 3868 status = 1; 3869 } 3870 3871 return status; 3872} 3873 3874__attribute__((format (printf, 2, 3))) 3875static int safe_append(const char *filename, const char *fmt, ...) 3876{ 3877 va_list ap; 3878 struct lock_file lock = LOCK_INIT; 3879 int fd = hold_lock_file_for_update(&lock, filename, 3880 LOCK_REPORT_ON_ERROR); 3881 struct strbuf buf = STRBUF_INIT; 3882 3883 if (fd < 0) 3884 return -1; 3885 3886 if (strbuf_read_file(&buf, filename, 0) < 0 && errno != ENOENT) { 3887 error_errno(_("could not read '%s'"), filename); 3888 rollback_lock_file(&lock); 3889 return -1; 3890 } 3891 strbuf_complete(&buf, '\n'); 3892 va_start(ap, fmt); 3893 strbuf_vaddf(&buf, fmt, ap); 3894 va_end(ap); 3895 3896 if (write_in_full(fd, buf.buf, buf.len) < 0) { 3897 error_errno(_("could not write to '%s'"), filename); 3898 strbuf_release(&buf); 3899 rollback_lock_file(&lock); 3900 return -1; 3901 } 3902 if (commit_lock_file(&lock) < 0) { 3903 strbuf_release(&buf); 3904 return error(_("failed to finalize '%s'"), filename); 3905 } 3906 3907 strbuf_release(&buf); 3908 return 0; 3909} 3910 3911static int do_label(struct repository *r, const char *name, int len) 3912{ 3913 struct ref_store *refs = get_main_ref_store(r); 3914 struct ref_transaction *transaction; 3915 struct strbuf ref_name = STRBUF_INIT, err = STRBUF_INIT; 3916 struct strbuf msg = STRBUF_INIT; 3917 int ret = 0; 3918 struct object_id head_oid; 3919 3920 if (len == 1 && *name == '#') 3921 return error(_("illegal label name: '%.*s'"), len, name); 3922 3923 strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name); 3924 strbuf_addf(&msg, "rebase (label) '%.*s'", len, name); 3925 3926 transaction = ref_store_transaction_begin(refs, 0, &err); 3927 if (!transaction) { 3928 error("%s", err.buf); 3929 ret = -1; 3930 } else if (repo_get_oid(r, "HEAD", &head_oid)) { 3931 error(_("could not read HEAD")); 3932 ret = -1; 3933 } else if (ref_transaction_update(transaction, ref_name.buf, 3934 &head_oid, NULL, NULL, NULL, 3935 0, msg.buf, &err) < 0 || 3936 ref_transaction_commit(transaction, &err)) { 3937 error("%s", err.buf); 3938 ret = -1; 3939 } 3940 ref_transaction_free(transaction); 3941 strbuf_release(&err); 3942 strbuf_release(&msg); 3943 3944 if (!ret) 3945 ret = safe_append(rebase_path_refs_to_delete(), 3946 "%s\n", ref_name.buf); 3947 strbuf_release(&ref_name); 3948 3949 return ret; 3950} 3951 3952static struct commit *lookup_label(struct repository *r, const char *label, 3953 int len, struct strbuf *buf) 3954{ 3955 struct commit *commit; 3956 struct object_id oid; 3957 3958 strbuf_reset(buf); 3959 strbuf_addf(buf, "refs/rewritten/%.*s", len, label); 3960 if (!refs_read_ref(get_main_ref_store(the_repository), buf->buf, &oid)) { 3961 commit = lookup_commit_object(r, &oid); 3962 } else { 3963 /* fall back to non-rewritten ref or commit */ 3964 strbuf_splice(buf, 0, strlen("refs/rewritten/"), "", 0); 3965 commit = lookup_commit_reference_by_name(buf->buf); 3966 } 3967 3968 if (!commit) 3969 error(_("could not resolve '%s'"), buf->buf); 3970 3971 return commit; 3972} 3973 3974static int do_reset(struct repository *r, 3975 const char *name, int len, 3976 struct replay_opts *opts) 3977{ 3978 struct strbuf ref_name = STRBUF_INIT; 3979 struct object_id oid; 3980 struct lock_file lock = LOCK_INIT; 3981 struct tree_desc desc = { 0 }; 3982 struct tree *tree; 3983 struct unpack_trees_options unpack_tree_opts = { 0 }; 3984 int ret = 0; 3985 3986 if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0) 3987 return -1; 3988 3989 if (len == 10 && !strncmp("[new root]", name, len)) { 3990 if (!opts->have_squash_onto) { 3991 const char *hex; 3992 if (commit_tree("", 0, the_hash_algo->empty_tree, 3993 NULL, &opts->squash_onto, 3994 NULL, NULL)) 3995 return error(_("writing fake root commit")); 3996 opts->have_squash_onto = 1; 3997 hex = oid_to_hex(&opts->squash_onto); 3998 if (write_message(hex, strlen(hex), 3999 rebase_path_squash_onto(), 0)) 4000 return error(_("writing squash-onto")); 4001 } 4002 oidcpy(&oid, &opts->squash_onto); 4003 } else { 4004 int i; 4005 struct commit *commit; 4006 4007 /* Determine the length of the label */ 4008 for (i = 0; i < len; i++) 4009 if (isspace(name[i])) 4010 break; 4011 len = i; 4012 4013 commit = lookup_label(r, name, len, &ref_name); 4014 if (!commit) { 4015 ret = -1; 4016 goto cleanup; 4017 } 4018 oid = commit->object.oid; 4019 } 4020 4021 setup_unpack_trees_porcelain(&unpack_tree_opts, "reset"); 4022 unpack_tree_opts.head_idx = 1; 4023 unpack_tree_opts.src_index = r->index; 4024 unpack_tree_opts.dst_index = r->index; 4025 unpack_tree_opts.fn = oneway_merge; 4026 unpack_tree_opts.merge = 1; 4027 unpack_tree_opts.update = 1; 4028 unpack_tree_opts.preserve_ignored = 0; /* FIXME: !overwrite_ignore */ 4029 unpack_tree_opts.skip_cache_tree_update = 1; 4030 init_checkout_metadata(&unpack_tree_opts.meta, name, &oid, NULL); 4031 4032 if (repo_read_index_unmerged(r)) { 4033 ret = error_resolve_conflict(action_name(opts)); 4034 goto cleanup; 4035 } 4036 4037 if (!fill_tree_descriptor(r, &desc, &oid)) { 4038 ret = error(_("failed to find tree of %s"), oid_to_hex(&oid)); 4039 goto cleanup; 4040 } 4041 4042 if (unpack_trees(1, &desc, &unpack_tree_opts)) { 4043 ret = -1; 4044 goto cleanup; 4045 } 4046 4047 tree = parse_tree_indirect(&oid); 4048 if (!tree) 4049 return error(_("unable to read tree (%s)"), oid_to_hex(&oid)); 4050 prime_cache_tree(r, r->index, tree); 4051 4052 if (write_locked_index(r->index, &lock, COMMIT_LOCK) < 0) 4053 ret = error(_("could not write index")); 4054 4055 if (!ret) 4056 ret = refs_update_ref(get_main_ref_store(the_repository), reflog_message(opts, "reset", "'%.*s'", 4057 len, name), 4058 "HEAD", &oid, 4059 NULL, 0, UPDATE_REFS_MSG_ON_ERR); 4060cleanup: 4061 free((void *)desc.buffer); 4062 if (ret < 0) 4063 rollback_lock_file(&lock); 4064 strbuf_release(&ref_name); 4065 clear_unpack_trees_porcelain(&unpack_tree_opts); 4066 return ret; 4067} 4068 4069static int do_merge(struct repository *r, 4070 struct commit *commit, 4071 const char *arg, int arg_len, 4072 int flags, int *check_todo, struct replay_opts *opts) 4073{ 4074 struct replay_ctx *ctx = opts->ctx; 4075 int run_commit_flags = 0; 4076 struct strbuf ref_name = STRBUF_INIT; 4077 struct commit *head_commit, *merge_commit, *i; 4078 struct commit_list *bases = NULL, *j; 4079 struct commit_list *to_merge = NULL, **tail = &to_merge; 4080 const char *strategy = !opts->xopts.nr && 4081 (!opts->strategy || 4082 !strcmp(opts->strategy, "recursive") || 4083 !strcmp(opts->strategy, "ort")) ? 4084 NULL : opts->strategy; 4085 struct merge_options o; 4086 int merge_arg_len, oneline_offset, can_fast_forward, ret, k; 4087 static struct lock_file lock; 4088 const char *p; 4089 const char *reflog_action = reflog_message(opts, "merge", NULL); 4090 4091 if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0) { 4092 ret = -1; 4093 goto leave_merge; 4094 } 4095 4096 head_commit = lookup_commit_reference_by_name("HEAD"); 4097 if (!head_commit) { 4098 ret = error(_("cannot merge without a current revision")); 4099 goto leave_merge; 4100 } 4101 4102 /* 4103 * For octopus merges, the arg starts with the list of revisions to be 4104 * merged. The list is optionally followed by '#' and the oneline. 4105 */ 4106 merge_arg_len = oneline_offset = arg_len; 4107 for (p = arg; p - arg < arg_len; p += strspn(p, " \t\n")) { 4108 if (!*p) 4109 break; 4110 if (*p == '#' && (!p[1] || isspace(p[1]))) { 4111 p += 1 + strspn(p + 1, " \t\n"); 4112 oneline_offset = p - arg; 4113 break; 4114 } 4115 k = strcspn(p, " \t\n"); 4116 if (!k) 4117 continue; 4118 merge_commit = lookup_label(r, p, k, &ref_name); 4119 if (!merge_commit) { 4120 ret = error(_("unable to parse '%.*s'"), k, p); 4121 goto leave_merge; 4122 } 4123 tail = &commit_list_insert(merge_commit, tail)->next; 4124 p += k; 4125 merge_arg_len = p - arg; 4126 } 4127 4128 if (!to_merge) { 4129 ret = error(_("nothing to merge: '%.*s'"), arg_len, arg); 4130 goto leave_merge; 4131 } 4132 4133 if (opts->have_squash_onto && 4134 oideq(&head_commit->object.oid, &opts->squash_onto)) { 4135 /* 4136 * When the user tells us to "merge" something into a 4137 * "[new root]", let's simply fast-forward to the merge head. 4138 */ 4139 rollback_lock_file(&lock); 4140 if (to_merge->next) 4141 ret = error(_("octopus merge cannot be executed on " 4142 "top of a [new root]")); 4143 else 4144 ret = fast_forward_to(r, &to_merge->item->object.oid, 4145 &head_commit->object.oid, 0, 4146 opts); 4147 goto leave_merge; 4148 } 4149 4150 /* 4151 * If HEAD is not identical to the first parent of the original merge 4152 * commit, we cannot fast-forward. 4153 */ 4154 can_fast_forward = opts->allow_ff && commit && commit->parents && 4155 oideq(&commit->parents->item->object.oid, 4156 &head_commit->object.oid); 4157 4158 /* 4159 * If any merge head is different from the original one, we cannot 4160 * fast-forward. 4161 */ 4162 if (can_fast_forward) { 4163 struct commit_list *p = commit->parents->next; 4164 4165 for (j = to_merge; j && p; j = j->next, p = p->next) 4166 if (!oideq(&j->item->object.oid, 4167 &p->item->object.oid)) { 4168 can_fast_forward = 0; 4169 break; 4170 } 4171 /* 4172 * If the number of merge heads differs from the original merge 4173 * commit, we cannot fast-forward. 4174 */ 4175 if (j || p) 4176 can_fast_forward = 0; 4177 } 4178 4179 if (can_fast_forward) { 4180 rollback_lock_file(&lock); 4181 ret = fast_forward_to(r, &commit->object.oid, 4182 &head_commit->object.oid, 0, opts); 4183 if (flags & TODO_EDIT_MERGE_MSG) 4184 goto fast_forward_edit; 4185 4186 goto leave_merge; 4187 } 4188 4189 if (commit) { 4190 const char *encoding = get_commit_output_encoding(); 4191 const char *message = repo_logmsg_reencode(r, commit, NULL, 4192 encoding); 4193 const char *body; 4194 int len; 4195 4196 if (!message) { 4197 ret = error(_("could not get commit message of '%s'"), 4198 oid_to_hex(&commit->object.oid)); 4199 goto leave_merge; 4200 } 4201 write_author_script(message); 4202 find_commit_subject(message, &body); 4203 len = strlen(body); 4204 strbuf_add(&ctx->message, body, len); 4205 repo_unuse_commit_buffer(r, commit, message); 4206 } else { 4207 struct strbuf buf = STRBUF_INIT; 4208 4209 strbuf_addf(&buf, "author %s", git_author_info(0)); 4210 write_author_script(buf.buf); 4211 strbuf_release(&buf); 4212 4213 if (oneline_offset < arg_len) { 4214 strbuf_add(&ctx->message, arg + oneline_offset, 4215 arg_len - oneline_offset); 4216 } else { 4217 strbuf_addf(&ctx->message, "Merge %s '%.*s'", 4218 to_merge->next ? "branches" : "branch", 4219 merge_arg_len, arg); 4220 } 4221 } 4222 ctx->have_message = 1; 4223 if (write_message(ctx->message.buf, ctx->message.len, 4224 git_path_merge_msg(r), 0)) { 4225 ret = error_errno(_("could not write '%s'"), 4226 git_path_merge_msg(r)); 4227 goto leave_merge; 4228 } 4229 4230 if (strategy || to_merge->next) { 4231 /* Octopus merge */ 4232 struct child_process cmd = CHILD_PROCESS_INIT; 4233 4234 if (read_env_script(&cmd.env)) { 4235 const char *gpg_opt = gpg_sign_opt_quoted(opts); 4236 4237 ret = error(_(staged_changes_advice), gpg_opt, gpg_opt); 4238 goto leave_merge; 4239 } 4240 4241 if (opts->committer_date_is_author_date) 4242 strvec_pushf(&cmd.env, "GIT_COMMITTER_DATE=%s", 4243 opts->ignore_date ? 4244 "" : 4245 author_date_from_env(&cmd.env)); 4246 if (opts->ignore_date) 4247 strvec_push(&cmd.env, "GIT_AUTHOR_DATE="); 4248 4249 cmd.git_cmd = 1; 4250 strvec_push(&cmd.args, "merge"); 4251 strvec_push(&cmd.args, "-s"); 4252 if (!strategy) 4253 strvec_push(&cmd.args, "octopus"); 4254 else { 4255 strvec_push(&cmd.args, strategy); 4256 for (k = 0; k < opts->xopts.nr; k++) 4257 strvec_pushf(&cmd.args, 4258 "-X%s", opts->xopts.v[k]); 4259 } 4260 if (!(flags & TODO_EDIT_MERGE_MSG)) 4261 strvec_push(&cmd.args, "--no-edit"); 4262 else 4263 strvec_push(&cmd.args, "--edit"); 4264 strvec_push(&cmd.args, "--no-ff"); 4265 strvec_push(&cmd.args, "--no-log"); 4266 strvec_push(&cmd.args, "--no-stat"); 4267 strvec_push(&cmd.args, "-F"); 4268 strvec_push(&cmd.args, git_path_merge_msg(r)); 4269 if (opts->gpg_sign) 4270 strvec_pushf(&cmd.args, "-S%s", opts->gpg_sign); 4271 else 4272 strvec_push(&cmd.args, "--no-gpg-sign"); 4273 4274 /* Add the tips to be merged */ 4275 for (j = to_merge; j; j = j->next) 4276 strvec_push(&cmd.args, 4277 oid_to_hex(&j->item->object.oid)); 4278 4279 strbuf_release(&ref_name); 4280 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD", 4281 NULL, REF_NO_DEREF); 4282 rollback_lock_file(&lock); 4283 4284 ret = run_command(&cmd); 4285 4286 /* force re-reading of the cache */ 4287 if (!ret) { 4288 discard_index(r->index); 4289 if (repo_read_index(r) < 0) 4290 ret = error(_("could not read index")); 4291 } 4292 goto leave_merge; 4293 } 4294 4295 merge_commit = to_merge->item; 4296 if (repo_get_merge_bases(r, head_commit, merge_commit, &bases) < 0) { 4297 ret = -1; 4298 goto leave_merge; 4299 } 4300 4301 if (bases && oideq(&merge_commit->object.oid, 4302 &bases->item->object.oid)) { 4303 ret = 0; 4304 /* skip merging an ancestor of HEAD */ 4305 goto leave_merge; 4306 } 4307 4308 write_message(oid_to_hex(&merge_commit->object.oid), the_hash_algo->hexsz, 4309 git_path_merge_head(r), 0); 4310 write_message("no-ff", 5, git_path_merge_mode(r), 0); 4311 4312 bases = reverse_commit_list(bases); 4313 4314 repo_read_index(r); 4315 init_ui_merge_options(&o, r); 4316 o.branch1 = "HEAD"; 4317 o.branch2 = ref_name.buf; 4318 o.buffer_output = 2; 4319 4320 /* 4321 * TODO: Should use merge_incore_recursive() and 4322 * merge_switch_to_result(), skipping the call to 4323 * merge_switch_to_result() when we don't actually need to 4324 * update the index and working copy immediately. 4325 */ 4326 ret = merge_ort_recursive(&o, head_commit, merge_commit, bases, &i); 4327 if (ret <= 0) 4328 fputs(o.obuf.buf, stdout); 4329 strbuf_release(&o.obuf); 4330 if (ret < 0) { 4331 error(_("could not even attempt to merge '%.*s'"), 4332 merge_arg_len, arg); 4333 unlink(git_path_merge_msg(r)); 4334 goto leave_merge; 4335 } 4336 /* 4337 * The return value of merge_ort_recursive() is 1 on clean, and 0 on 4338 * unclean merge. 4339 * 4340 * Let's reverse that, so that do_merge() returns 0 upon success and 4341 * 1 upon failed merge (keeping the return value -1 for the cases where 4342 * we will want to reschedule the `merge` command). 4343 */ 4344 ret = !ret; 4345 4346 if (r->index->cache_changed && 4347 write_locked_index(r->index, &lock, COMMIT_LOCK)) { 4348 ret = error(_("merge: Unable to write new index file")); 4349 goto leave_merge; 4350 } 4351 4352 rollback_lock_file(&lock); 4353 if (ret) 4354 repo_rerere(r, opts->allow_rerere_auto); 4355 else 4356 /* 4357 * In case of problems, we now want to return a positive 4358 * value (a negative one would indicate that the `merge` 4359 * command needs to be rescheduled). 4360 */ 4361 ret = !!run_git_commit(git_path_merge_msg(r), reflog_action, 4362 opts, run_commit_flags); 4363 4364 if (!ret && flags & TODO_EDIT_MERGE_MSG) { 4365 fast_forward_edit: 4366 *check_todo = 1; 4367 run_commit_flags |= AMEND_MSG | EDIT_MSG | VERIFY_MSG; 4368 ret = !!run_git_commit(NULL, reflog_action, opts, 4369 run_commit_flags); 4370 } 4371 4372 4373leave_merge: 4374 strbuf_release(&ref_name); 4375 rollback_lock_file(&lock); 4376 free_commit_list(to_merge); 4377 free_commit_list(bases); 4378 return ret; 4379} 4380 4381static int write_update_refs_state(struct string_list *refs_to_oids) 4382{ 4383 int result = 0; 4384 struct lock_file lock = LOCK_INIT; 4385 FILE *fp = NULL; 4386 struct string_list_item *item; 4387 char *path; 4388 4389 path = rebase_path_update_refs(the_repository->gitdir); 4390 4391 if (!refs_to_oids->nr) { 4392 if (unlink(path) && errno != ENOENT) 4393 result = error_errno(_("could not unlink: %s"), path); 4394 goto cleanup; 4395 } 4396 4397 if (safe_create_leading_directories(the_repository, path)) { 4398 result = error(_("unable to create leading directories of %s"), 4399 path); 4400 goto cleanup; 4401 } 4402 4403 if (hold_lock_file_for_update(&lock, path, 0) < 0) { 4404 result = error(_("another 'rebase' process appears to be running; " 4405 "'%s.lock' already exists"), 4406 path); 4407 goto cleanup; 4408 } 4409 4410 fp = fdopen_lock_file(&lock, "w"); 4411 if (!fp) { 4412 result = error_errno(_("could not open '%s' for writing"), path); 4413 rollback_lock_file(&lock); 4414 goto cleanup; 4415 } 4416 4417 for_each_string_list_item(item, refs_to_oids) { 4418 struct update_ref_record *rec = item->util; 4419 fprintf(fp, "%s\n%s\n%s\n", item->string, 4420 oid_to_hex(&rec->before), oid_to_hex(&rec->after)); 4421 } 4422 4423 result = commit_lock_file(&lock); 4424 4425cleanup: 4426 free(path); 4427 return result; 4428} 4429 4430/* 4431 * Parse the update-refs file for the current rebase, then remove the 4432 * refs that do not appear in the todo_list (and have not had updated 4433 * values stored) and add refs that are in the todo_list but not 4434 * represented in the update-refs file. 4435 * 4436 * If there are changes to the update-refs list, then write the new state 4437 * to disk. 4438 */ 4439void todo_list_filter_update_refs(struct repository *r, 4440 struct todo_list *todo_list) 4441{ 4442 int i; 4443 int updated = 0; 4444 struct string_list update_refs = STRING_LIST_INIT_DUP; 4445 4446 sequencer_get_update_refs_state(r->gitdir, &update_refs); 4447 4448 /* 4449 * For each item in the update_refs list, if it has no updated 4450 * value and does not appear in the todo_list, then remove it 4451 * from the update_refs list. 4452 */ 4453 for (i = 0; i < update_refs.nr; i++) { 4454 int j; 4455 int found = 0; 4456 const char *ref = update_refs.items[i].string; 4457 size_t reflen = strlen(ref); 4458 struct update_ref_record *rec = update_refs.items[i].util; 4459 4460 /* OID already stored as updated. */ 4461 if (!is_null_oid(&rec->after)) 4462 continue; 4463 4464 for (j = 0; !found && j < todo_list->nr; j++) { 4465 struct todo_item *item = &todo_list->items[j]; 4466 const char *arg = todo_list->buf.buf + item->arg_offset; 4467 4468 if (item->command != TODO_UPDATE_REF) 4469 continue; 4470 4471 if (item->arg_len != reflen || 4472 strncmp(arg, ref, reflen)) 4473 continue; 4474 4475 found = 1; 4476 } 4477 4478 if (!found) { 4479 free(update_refs.items[i].string); 4480 free(update_refs.items[i].util); 4481 4482 update_refs.nr--; 4483 MOVE_ARRAY(update_refs.items + i, update_refs.items + i + 1, update_refs.nr - i); 4484 4485 updated = 1; 4486 i--; 4487 } 4488 } 4489 4490 /* 4491 * For each todo_item, check if its ref is in the update_refs list. 4492 * If not, then add it as an un-updated ref. 4493 */ 4494 for (i = 0; i < todo_list->nr; i++) { 4495 struct todo_item *item = &todo_list->items[i]; 4496 const char *arg = todo_list->buf.buf + item->arg_offset; 4497 int j, found = 0; 4498 4499 if (item->command != TODO_UPDATE_REF) 4500 continue; 4501 4502 for (j = 0; !found && j < update_refs.nr; j++) { 4503 const char *ref = update_refs.items[j].string; 4504 4505 found = strlen(ref) == item->arg_len && 4506 !strncmp(ref, arg, item->arg_len); 4507 } 4508 4509 if (!found) { 4510 struct string_list_item *inserted; 4511 struct strbuf argref = STRBUF_INIT; 4512 4513 strbuf_add(&argref, arg, item->arg_len); 4514 inserted = string_list_insert(&update_refs, argref.buf); 4515 inserted->util = init_update_ref_record(argref.buf); 4516 strbuf_release(&argref); 4517 updated = 1; 4518 } 4519 } 4520 4521 if (updated) 4522 write_update_refs_state(&update_refs); 4523 string_list_clear(&update_refs, 1); 4524} 4525 4526static int do_update_ref(struct repository *r, const char *refname) 4527{ 4528 struct string_list_item *item; 4529 struct string_list list = STRING_LIST_INIT_DUP; 4530 4531 if (sequencer_get_update_refs_state(r->gitdir, &list)) 4532 return -1; 4533 4534 for_each_string_list_item(item, &list) { 4535 if (!strcmp(item->string, refname)) { 4536 struct update_ref_record *rec = item->util; 4537 if (refs_read_ref(get_main_ref_store(the_repository), "HEAD", &rec->after)) 4538 return -1; 4539 break; 4540 } 4541 } 4542 4543 write_update_refs_state(&list); 4544 string_list_clear(&list, 1); 4545 return 0; 4546} 4547 4548static int do_update_refs(struct repository *r, int quiet) 4549{ 4550 int res = 0; 4551 struct string_list_item *item; 4552 struct string_list refs_to_oids = STRING_LIST_INIT_DUP; 4553 struct ref_store *refs = get_main_ref_store(r); 4554 struct strbuf update_msg = STRBUF_INIT; 4555 struct strbuf error_msg = STRBUF_INIT; 4556 4557 if ((res = sequencer_get_update_refs_state(r->gitdir, &refs_to_oids))) 4558 return res; 4559 4560 for_each_string_list_item(item, &refs_to_oids) { 4561 struct update_ref_record *rec = item->util; 4562 int loop_res; 4563 4564 loop_res = refs_update_ref(refs, "rewritten during rebase", 4565 item->string, 4566 &rec->after, &rec->before, 4567 0, UPDATE_REFS_MSG_ON_ERR); 4568 res |= loop_res; 4569 4570 if (quiet) 4571 continue; 4572 4573 if (loop_res) 4574 strbuf_addf(&error_msg, "\t%s\n", item->string); 4575 else 4576 strbuf_addf(&update_msg, "\t%s\n", item->string); 4577 } 4578 4579 if (!quiet && 4580 (update_msg.len || error_msg.len)) { 4581 fprintf(stderr, 4582 _("Updated the following refs with %s:\n%s"), 4583 "--update-refs", 4584 update_msg.buf); 4585 4586 if (res) 4587 fprintf(stderr, 4588 _("Failed to update the following refs with %s:\n%s"), 4589 "--update-refs", 4590 error_msg.buf); 4591 } 4592 4593 string_list_clear(&refs_to_oids, 1); 4594 strbuf_release(&update_msg); 4595 strbuf_release(&error_msg); 4596 return res; 4597} 4598 4599static int is_final_fixup(struct todo_list *todo_list) 4600{ 4601 int i = todo_list->current; 4602 4603 if (!is_fixup(todo_list->items[i].command)) 4604 return 0; 4605 4606 while (++i < todo_list->nr) 4607 if (is_fixup(todo_list->items[i].command)) 4608 return 0; 4609 else if (!is_noop(todo_list->items[i].command)) 4610 break; 4611 return 1; 4612} 4613 4614static enum todo_command peek_command(struct todo_list *todo_list, int offset) 4615{ 4616 int i; 4617 4618 for (i = todo_list->current + offset; i < todo_list->nr; i++) 4619 if (!is_noop(todo_list->items[i].command)) 4620 return todo_list->items[i].command; 4621 4622 return -1; 4623} 4624 4625static void create_autostash_internal(struct repository *r, 4626 const char *path, 4627 const char *refname) 4628{ 4629 struct strbuf buf = STRBUF_INIT; 4630 struct lock_file lock_file = LOCK_INIT; 4631 int fd; 4632 4633 if (path && refname) 4634 BUG("can only pass path or refname"); 4635 4636 fd = repo_hold_locked_index(r, &lock_file, 0); 4637 refresh_index(r->index, REFRESH_QUIET, NULL, NULL, NULL); 4638 if (0 <= fd) 4639 repo_update_index_if_able(r, &lock_file); 4640 rollback_lock_file(&lock_file); 4641 4642 if (has_unstaged_changes(r, 1) || 4643 has_uncommitted_changes(r, 1)) { 4644 struct child_process stash = CHILD_PROCESS_INIT; 4645 struct reset_head_opts ropts = { .flags = RESET_HEAD_HARD }; 4646 struct object_id oid; 4647 4648 strvec_pushl(&stash.args, 4649 "stash", "create", "autostash", NULL); 4650 stash.git_cmd = 1; 4651 stash.no_stdin = 1; 4652 strbuf_reset(&buf); 4653 if (capture_command(&stash, &buf, GIT_MAX_HEXSZ)) 4654 die(_("Cannot autostash")); 4655 strbuf_trim_trailing_newline(&buf); 4656 if (repo_get_oid(r, buf.buf, &oid)) 4657 die(_("Unexpected stash response: '%s'"), 4658 buf.buf); 4659 strbuf_reset(&buf); 4660 strbuf_add_unique_abbrev(&buf, &oid, DEFAULT_ABBREV); 4661 4662 if (path) { 4663 if (safe_create_leading_directories_const(the_repository, path)) 4664 die(_("Could not create directory for '%s'"), 4665 path); 4666 write_file(path, "%s", oid_to_hex(&oid)); 4667 } else { 4668 refs_update_ref(get_main_ref_store(r), "", refname, 4669 &oid, null_oid(the_hash_algo), 0, UPDATE_REFS_DIE_ON_ERR); 4670 } 4671 4672 printf(_("Created autostash: %s\n"), buf.buf); 4673 if (reset_head(r, &ropts) < 0) 4674 die(_("could not reset --hard")); 4675 discard_index(r->index); 4676 if (repo_read_index(r) < 0) 4677 die(_("could not read index")); 4678 } 4679 strbuf_release(&buf); 4680} 4681 4682void create_autostash(struct repository *r, const char *path) 4683{ 4684 create_autostash_internal(r, path, NULL); 4685} 4686 4687void create_autostash_ref(struct repository *r, const char *refname) 4688{ 4689 create_autostash_internal(r, NULL, refname); 4690} 4691 4692static int apply_save_autostash_oid(const char *stash_oid, int attempt_apply) 4693{ 4694 struct child_process child = CHILD_PROCESS_INIT; 4695 int ret = 0; 4696 4697 if (attempt_apply) { 4698 child.git_cmd = 1; 4699 child.no_stdout = 1; 4700 child.no_stderr = 1; 4701 strvec_push(&child.args, "stash"); 4702 strvec_push(&child.args, "apply"); 4703 strvec_push(&child.args, stash_oid); 4704 ret = run_command(&child); 4705 } 4706 4707 if (attempt_apply && !ret) 4708 fprintf(stderr, _("Applied autostash.\n")); 4709 else { 4710 struct child_process store = CHILD_PROCESS_INIT; 4711 4712 store.git_cmd = 1; 4713 strvec_push(&store.args, "stash"); 4714 strvec_push(&store.args, "store"); 4715 strvec_push(&store.args, "-m"); 4716 strvec_push(&store.args, "autostash"); 4717 strvec_push(&store.args, "-q"); 4718 strvec_push(&store.args, stash_oid); 4719 if (run_command(&store)) 4720 ret = error(_("cannot store %s"), stash_oid); 4721 else 4722 fprintf(stderr, 4723 _("%s\n" 4724 "Your changes are safe in the stash.\n" 4725 "You can run \"git stash pop\" or" 4726 " \"git stash drop\" at any time.\n"), 4727 attempt_apply ? 4728 _("Applying autostash resulted in conflicts.") : 4729 _("Autostash exists; creating a new stash entry.")); 4730 } 4731 4732 return ret; 4733} 4734 4735static int apply_save_autostash(const char *path, int attempt_apply) 4736{ 4737 struct strbuf stash_oid = STRBUF_INIT; 4738 int ret = 0; 4739 4740 if (!read_oneliner(&stash_oid, path, 4741 READ_ONELINER_SKIP_IF_EMPTY)) { 4742 strbuf_release(&stash_oid); 4743 return 0; 4744 } 4745 strbuf_trim(&stash_oid); 4746 4747 ret = apply_save_autostash_oid(stash_oid.buf, attempt_apply); 4748 4749 unlink(path); 4750 strbuf_release(&stash_oid); 4751 return ret; 4752} 4753 4754int save_autostash(const char *path) 4755{ 4756 return apply_save_autostash(path, 0); 4757} 4758 4759int apply_autostash(const char *path) 4760{ 4761 return apply_save_autostash(path, 1); 4762} 4763 4764int apply_autostash_oid(const char *stash_oid) 4765{ 4766 return apply_save_autostash_oid(stash_oid, 1); 4767} 4768 4769static int apply_save_autostash_ref(struct repository *r, const char *refname, 4770 int attempt_apply) 4771{ 4772 struct object_id stash_oid; 4773 char stash_oid_hex[GIT_MAX_HEXSZ + 1]; 4774 int flag, ret; 4775 4776 if (!refs_ref_exists(get_main_ref_store(r), refname)) 4777 return 0; 4778 4779 if (!refs_resolve_ref_unsafe(get_main_ref_store(r), refname, 4780 RESOLVE_REF_READING, &stash_oid, &flag)) 4781 return -1; 4782 if (flag & REF_ISSYMREF) 4783 return error(_("autostash reference is a symref")); 4784 4785 oid_to_hex_r(stash_oid_hex, &stash_oid); 4786 ret = apply_save_autostash_oid(stash_oid_hex, attempt_apply); 4787 4788 refs_delete_ref(get_main_ref_store(r), "", refname, 4789 &stash_oid, REF_NO_DEREF); 4790 4791 return ret; 4792} 4793 4794int save_autostash_ref(struct repository *r, const char *refname) 4795{ 4796 return apply_save_autostash_ref(r, refname, 0); 4797} 4798 4799int apply_autostash_ref(struct repository *r, const char *refname) 4800{ 4801 return apply_save_autostash_ref(r, refname, 1); 4802} 4803 4804static int checkout_onto(struct repository *r, struct replay_opts *opts, 4805 const char *onto_name, const struct object_id *onto, 4806 const struct object_id *orig_head) 4807{ 4808 struct reset_head_opts ropts = { 4809 .oid = onto, 4810 .orig_head = orig_head, 4811 .flags = RESET_HEAD_DETACH | RESET_ORIG_HEAD | 4812 RESET_HEAD_RUN_POST_CHECKOUT_HOOK, 4813 .head_msg = reflog_message(opts, "start", "checkout %s", 4814 onto_name), 4815 .default_reflog_action = sequencer_reflog_action(opts) 4816 }; 4817 if (reset_head(r, &ropts)) { 4818 apply_autostash(rebase_path_autostash()); 4819 sequencer_remove_state(opts); 4820 return error(_("could not detach HEAD")); 4821 } 4822 4823 return 0; 4824} 4825 4826static int stopped_at_head(struct repository *r) 4827{ 4828 struct object_id head; 4829 struct commit *commit; 4830 struct commit_message message; 4831 4832 if (repo_get_oid(r, "HEAD", &head) || 4833 !(commit = lookup_commit(r, &head)) || 4834 repo_parse_commit(r, commit) || get_message(commit, &message)) 4835 fprintf(stderr, _("Stopped at HEAD\n")); 4836 else { 4837 fprintf(stderr, _("Stopped at %s\n"), message.label); 4838 free_message(commit, &message); 4839 } 4840 return 0; 4841 4842} 4843 4844static int reread_todo_if_changed(struct repository *r, 4845 struct todo_list *todo_list, 4846 struct replay_opts *opts) 4847{ 4848 int offset; 4849 struct strbuf buf = STRBUF_INIT; 4850 4851 if (strbuf_read_file_or_whine(&buf, get_todo_path(opts)) < 0) 4852 return -1; 4853 offset = get_item_line_offset(todo_list, todo_list->current + 1); 4854 if (buf.len != todo_list->buf.len - offset || 4855 memcmp(buf.buf, todo_list->buf.buf + offset, buf.len)) { 4856 /* Reread the todo file if it has changed. */ 4857 todo_list_release(todo_list); 4858 if (read_populate_todo(r, todo_list, opts)) 4859 return -1; /* message was printed */ 4860 /* `current` will be incremented on return */ 4861 todo_list->current = -1; 4862 } 4863 strbuf_release(&buf); 4864 4865 return 0; 4866} 4867 4868static const char rescheduled_advice[] = 4869N_("Could not execute the todo command\n" 4870"\n" 4871" %.*s" 4872"\n" 4873"It has been rescheduled; To edit the command before continuing, please\n" 4874"edit the todo list first:\n" 4875"\n" 4876" git rebase --edit-todo\n" 4877" git rebase --continue\n"); 4878 4879static int pick_one_commit(struct repository *r, 4880 struct todo_list *todo_list, 4881 struct replay_opts *opts, 4882 int *check_todo, int* reschedule) 4883{ 4884 int res; 4885 struct todo_item *item = todo_list->items + todo_list->current; 4886 const char *arg = todo_item_get_arg(todo_list, item); 4887 4888 res = do_pick_commit(r, item, opts, is_final_fixup(todo_list), 4889 check_todo); 4890 if (is_rebase_i(opts) && res < 0) { 4891 /* Reschedule */ 4892 *reschedule = 1; 4893 return -1; 4894 } 4895 if (item->command == TODO_EDIT) { 4896 struct commit *commit = item->commit; 4897 if (!res) { 4898 if (!opts->verbose) 4899 term_clear_line(); 4900 fprintf(stderr, _("Stopped at %s... %.*s\n"), 4901 short_commit_name(r, commit), item->arg_len, arg); 4902 } 4903 return error_with_patch(r, commit, 4904 arg, item->arg_len, opts, res, !res); 4905 } 4906 if (is_rebase_i(opts) && !res) 4907 record_in_rewritten(&item->commit->object.oid, 4908 peek_command(todo_list, 1)); 4909 if (res && is_fixup(item->command)) { 4910 if (res == 1) 4911 intend_to_amend(); 4912 return error_failed_squash(r, item->commit, opts, 4913 item->arg_len, arg); 4914 } else if (res && is_rebase_i(opts) && item->commit) { 4915 int to_amend = 0; 4916 struct object_id oid; 4917 4918 /* 4919 * If we are rewording and have either 4920 * fast-forwarded already, or are about to 4921 * create a new root commit, we want to amend, 4922 * otherwise we do not. 4923 */ 4924 if (item->command == TODO_REWORD && 4925 !repo_get_oid(r, "HEAD", &oid) && 4926 (oideq(&item->commit->object.oid, &oid) || 4927 (opts->have_squash_onto && 4928 oideq(&opts->squash_onto, &oid)))) 4929 to_amend = 1; 4930 4931 return res | error_with_patch(r, item->commit, 4932 arg, item->arg_len, opts, 4933 res, to_amend); 4934 } 4935 return res; 4936} 4937 4938static int pick_commits(struct repository *r, 4939 struct todo_list *todo_list, 4940 struct replay_opts *opts) 4941{ 4942 struct replay_ctx *ctx = opts->ctx; 4943 int res = 0, reschedule = 0; 4944 4945 if (opts->allow_ff) 4946 ASSERT(!(opts->signoff || opts->no_commit || 4947 opts->record_origin || should_edit(opts) || 4948 opts->committer_date_is_author_date || 4949 opts->ignore_date)); 4950 if (read_and_refresh_cache(r, opts)) 4951 return -1; 4952 4953 unlink(rebase_path_message()); 4954 unlink(rebase_path_stopped_sha()); 4955 unlink(rebase_path_amend()); 4956 unlink(rebase_path_patch()); 4957 4958 while (todo_list->current < todo_list->nr) { 4959 struct todo_item *item = todo_list->items + todo_list->current; 4960 const char *arg = todo_item_get_arg(todo_list, item); 4961 int check_todo = 0; 4962 4963 if (save_todo(todo_list, opts, reschedule)) 4964 return -1; 4965 if (is_rebase_i(opts)) { 4966 if (item->command != TODO_COMMENT) { 4967 FILE *f = fopen(rebase_path_msgnum(), "w"); 4968 4969 todo_list->done_nr++; 4970 4971 if (f) { 4972 fprintf(f, "%d\n", todo_list->done_nr); 4973 fclose(f); 4974 } 4975 if (!opts->quiet) 4976 fprintf(stderr, _("Rebasing (%d/%d)%s"), 4977 todo_list->done_nr, 4978 todo_list->total_nr, 4979 opts->verbose ? "\n" : "\r"); 4980 } 4981 unlink(rebase_path_author_script()); 4982 unlink(git_path_merge_head(r)); 4983 refs_delete_ref(get_main_ref_store(r), "", "AUTO_MERGE", 4984 NULL, REF_NO_DEREF); 4985 refs_delete_ref(get_main_ref_store(r), "", "REBASE_HEAD", 4986 NULL, REF_NO_DEREF); 4987 4988 if (item->command == TODO_BREAK) { 4989 if (!opts->verbose) 4990 term_clear_line(); 4991 return stopped_at_head(r); 4992 } 4993 } 4994 strbuf_reset(&ctx->message); 4995 ctx->have_message = 0; 4996 if (item->command <= TODO_SQUASH) { 4997 res = pick_one_commit(r, todo_list, opts, &check_todo, 4998 &reschedule); 4999 if (!res && item->command == TODO_EDIT) 5000 return 0; 5001 } else if (item->command == TODO_EXEC) { 5002 char *end_of_arg = (char *)(arg + item->arg_len); 5003 int saved = *end_of_arg; 5004 5005 if (!opts->verbose) 5006 term_clear_line(); 5007 *end_of_arg = '\0'; 5008 res = do_exec(r, arg, opts->quiet); 5009 *end_of_arg = saved; 5010 5011 if (res) { 5012 if (opts->reschedule_failed_exec) 5013 reschedule = 1; 5014 } 5015 check_todo = 1; 5016 } else if (item->command == TODO_LABEL) { 5017 if ((res = do_label(r, arg, item->arg_len))) 5018 reschedule = 1; 5019 } else if (item->command == TODO_RESET) { 5020 if ((res = do_reset(r, arg, item->arg_len, opts))) 5021 reschedule = 1; 5022 } else if (item->command == TODO_MERGE) { 5023 if ((res = do_merge(r, item->commit, arg, item->arg_len, 5024 item->flags, &check_todo, opts)) < 0) 5025 reschedule = 1; 5026 else if (item->commit) 5027 record_in_rewritten(&item->commit->object.oid, 5028 peek_command(todo_list, 1)); 5029 if (res > 0) 5030 /* failed with merge conflicts */ 5031 return error_with_patch(r, item->commit, 5032 arg, item->arg_len, 5033 opts, res, 0); 5034 } else if (item->command == TODO_UPDATE_REF) { 5035 struct strbuf ref = STRBUF_INIT; 5036 strbuf_add(&ref, arg, item->arg_len); 5037 if ((res = do_update_ref(r, ref.buf))) 5038 reschedule = 1; 5039 strbuf_release(&ref); 5040 } else if (!is_noop(item->command)) 5041 return error(_("unknown command %d"), item->command); 5042 5043 if (reschedule) { 5044 advise(_(rescheduled_advice), 5045 get_item_line_length(todo_list, 5046 todo_list->current), 5047 get_item_line(todo_list, todo_list->current)); 5048 if (save_todo(todo_list, opts, reschedule)) 5049 return -1; 5050 if (item->commit) 5051 write_rebase_head(&item->commit->object.oid); 5052 } else if (is_rebase_i(opts) && check_todo && !res && 5053 reread_todo_if_changed(r, todo_list, opts)) { 5054 return -1; 5055 } 5056 5057 if (res) 5058 return res; 5059 5060 todo_list->current++; 5061 } 5062 5063 if (is_rebase_i(opts)) { 5064 struct strbuf head_ref = STRBUF_INIT, buf = STRBUF_INIT; 5065 struct stat st; 5066 5067 if (read_oneliner(&head_ref, rebase_path_head_name(), 0) && 5068 starts_with(head_ref.buf, "refs/")) { 5069 const char *msg; 5070 struct object_id head, orig; 5071 int res; 5072 5073 if (repo_get_oid(r, "HEAD", &head)) { 5074 res = error(_("cannot read HEAD")); 5075cleanup_head_ref: 5076 strbuf_release(&head_ref); 5077 strbuf_release(&buf); 5078 return res; 5079 } 5080 if (!read_oneliner(&buf, rebase_path_orig_head(), 0) || 5081 get_oid_hex(buf.buf, &orig)) { 5082 res = error(_("could not read orig-head")); 5083 goto cleanup_head_ref; 5084 } 5085 strbuf_reset(&buf); 5086 if (!read_oneliner(&buf, rebase_path_onto(), 0)) { 5087 res = error(_("could not read 'onto'")); 5088 goto cleanup_head_ref; 5089 } 5090 msg = reflog_message(opts, "finish", "%s onto %s", 5091 head_ref.buf, buf.buf); 5092 if (refs_update_ref(get_main_ref_store(the_repository), msg, head_ref.buf, &head, &orig, 5093 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR)) { 5094 res = error(_("could not update %s"), 5095 head_ref.buf); 5096 goto cleanup_head_ref; 5097 } 5098 msg = reflog_message(opts, "finish", "returning to %s", 5099 head_ref.buf); 5100 if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", head_ref.buf, msg)) { 5101 res = error(_("could not update HEAD to %s"), 5102 head_ref.buf); 5103 goto cleanup_head_ref; 5104 } 5105 strbuf_reset(&buf); 5106 } 5107 5108 if (opts->verbose) { 5109 struct rev_info log_tree_opt; 5110 struct object_id orig, head; 5111 5112 memset(&log_tree_opt, 0, sizeof(log_tree_opt)); 5113 repo_init_revisions(r, &log_tree_opt, NULL); 5114 log_tree_opt.diff = 1; 5115 log_tree_opt.diffopt.output_format = 5116 DIFF_FORMAT_DIFFSTAT; 5117 log_tree_opt.disable_stdin = 1; 5118 5119 if (read_oneliner(&buf, rebase_path_orig_head(), 0) && 5120 !repo_get_oid(r, buf.buf, &orig) && 5121 !repo_get_oid(r, "HEAD", &head)) { 5122 diff_tree_oid(&orig, &head, "", 5123 &log_tree_opt.diffopt); 5124 log_tree_diff_flush(&log_tree_opt); 5125 } 5126 release_revisions(&log_tree_opt); 5127 } 5128 flush_rewritten_pending(); 5129 if (!stat(rebase_path_rewritten_list(), &st) && 5130 st.st_size > 0) { 5131 struct child_process child = CHILD_PROCESS_INIT; 5132 struct run_hooks_opt hook_opt = RUN_HOOKS_OPT_INIT; 5133 5134 child.in = open(rebase_path_rewritten_list(), O_RDONLY); 5135 child.git_cmd = 1; 5136 strvec_push(&child.args, "notes"); 5137 strvec_push(&child.args, "copy"); 5138 strvec_push(&child.args, "--for-rewrite=rebase"); 5139 /* we don't care if this copying failed */ 5140 run_command(&child); 5141 5142 hook_opt.path_to_stdin = rebase_path_rewritten_list(); 5143 strvec_push(&hook_opt.args, "rebase"); 5144 run_hooks_opt(r, "post-rewrite", &hook_opt); 5145 } 5146 apply_autostash(rebase_path_autostash()); 5147 5148 if (!opts->quiet) { 5149 if (!opts->verbose) 5150 term_clear_line(); 5151 fprintf(stderr, 5152 _("Successfully rebased and updated %s.\n"), 5153 head_ref.buf); 5154 } 5155 5156 strbuf_release(&buf); 5157 strbuf_release(&head_ref); 5158 5159 if (do_update_refs(r, opts->quiet)) 5160 return -1; 5161 } 5162 5163 /* 5164 * Sequence of picks finished successfully; cleanup by 5165 * removing the .git/sequencer directory 5166 */ 5167 return sequencer_remove_state(opts); 5168} 5169 5170static int continue_single_pick(struct repository *r, struct replay_opts *opts) 5171{ 5172 struct child_process cmd = CHILD_PROCESS_INIT; 5173 5174 if (!refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD") && 5175 !refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) 5176 return error(_("no cherry-pick or revert in progress")); 5177 5178 cmd.git_cmd = 1; 5179 strvec_push(&cmd.args, "commit"); 5180 5181 /* 5182 * continue_single_pick() handles the case of recovering from a 5183 * conflict. should_edit() doesn't handle that case; for a conflict, 5184 * we want to edit if the user asked for it, or if they didn't specify 5185 * and stdin is a tty. 5186 */ 5187 if (!opts->edit || (opts->edit < 0 && !isatty(0))) 5188 /* 5189 * Include --cleanup=strip as well because we don't want the 5190 * "# Conflicts:" messages. 5191 */ 5192 strvec_pushl(&cmd.args, "--no-edit", "--cleanup=strip", NULL); 5193 5194 return run_command(&cmd); 5195} 5196 5197static int commit_staged_changes(struct repository *r, 5198 struct replay_opts *opts, 5199 struct todo_list *todo_list) 5200{ 5201 struct replay_ctx *ctx = opts->ctx; 5202 unsigned int flags = ALLOW_EMPTY | EDIT_MSG; 5203 unsigned int final_fixup = 0, is_clean; 5204 struct strbuf rev = STRBUF_INIT; 5205 const char *reflog_action = reflog_message(opts, "continue", NULL); 5206 int ret; 5207 5208 if (has_unstaged_changes(r, 1)) { 5209 ret = error(_("cannot rebase: You have unstaged changes.")); 5210 goto out; 5211 } 5212 5213 is_clean = !has_uncommitted_changes(r, 0); 5214 5215 if (!is_clean && !file_exists(rebase_path_message())) { 5216 const char *gpg_opt = gpg_sign_opt_quoted(opts); 5217 ret = error(_(staged_changes_advice), gpg_opt, gpg_opt); 5218 goto out; 5219 } 5220 5221 if (file_exists(rebase_path_amend())) { 5222 struct object_id head, to_amend; 5223 5224 if (repo_get_oid(r, "HEAD", &head)) { 5225 ret = error(_("cannot amend non-existing commit")); 5226 goto out; 5227 } 5228 5229 if (!read_oneliner(&rev, rebase_path_amend(), 0)) { 5230 ret = error(_("invalid file: '%s'"), rebase_path_amend()); 5231 goto out; 5232 } 5233 5234 if (get_oid_hex(rev.buf, &to_amend)) { 5235 ret = error(_("invalid contents: '%s'"), 5236 rebase_path_amend()); 5237 goto out; 5238 } 5239 if (!is_clean && !oideq(&head, &to_amend)) { 5240 ret = error(_("\nYou have uncommitted changes in your " 5241 "working tree. Please, commit them\n" 5242 "first and then run 'git rebase " 5243 "--continue' again.")); 5244 goto out; 5245 } 5246 /* 5247 * When skipping a failed fixup/squash, we need to edit the 5248 * commit message, the current fixup list and count, and if it 5249 * was the last fixup/squash in the chain, we need to clean up 5250 * the commit message and if there was a squash, let the user 5251 * edit it. 5252 */ 5253 if (!is_clean || !ctx->current_fixup_count) 5254 ; /* this is not the final fixup */ 5255 else if (!oideq(&head, &to_amend) || 5256 !file_exists(rebase_path_stopped_sha())) { 5257 /* was a final fixup or squash done manually? */ 5258 if (!is_fixup(peek_command(todo_list, 0))) { 5259 unlink(rebase_path_fixup_msg()); 5260 unlink(rebase_path_squash_msg()); 5261 unlink(rebase_path_current_fixups()); 5262 strbuf_reset(&ctx->current_fixups); 5263 ctx->current_fixup_count = 0; 5264 } 5265 } else { 5266 /* we are in a fixup/squash chain */ 5267 const char *p = ctx->current_fixups.buf; 5268 int len = ctx->current_fixups.len; 5269 5270 ctx->current_fixup_count--; 5271 if (!len) 5272 BUG("Incorrect current_fixups:\n%s", p); 5273 while (len && p[len - 1] != '\n') 5274 len--; 5275 strbuf_setlen(&ctx->current_fixups, len); 5276 if (write_message(p, len, rebase_path_current_fixups(), 5277 0) < 0) { 5278 ret = error(_("could not write file: '%s'"), 5279 rebase_path_current_fixups()); 5280 goto out; 5281 } 5282 5283 /* 5284 * If a fixup/squash in a fixup/squash chain failed, the 5285 * commit message is already correct, no need to commit 5286 * it again. 5287 * 5288 * Only if it is the final command in the fixup/squash 5289 * chain, and only if the chain is longer than a single 5290 * fixup/squash command (which was just skipped), do we 5291 * actually need to re-commit with a cleaned up commit 5292 * message. 5293 */ 5294 if (ctx->current_fixup_count > 0 && 5295 !is_fixup(peek_command(todo_list, 0))) { 5296 final_fixup = 1; 5297 /* 5298 * If there was not a single "squash" in the 5299 * chain, we only need to clean up the commit 5300 * message, no need to bother the user with 5301 * opening the commit message in the editor. 5302 */ 5303 if (!starts_with(p, "squash ") && 5304 !strstr(p, "\nsquash ")) 5305 flags = (flags & ~EDIT_MSG) | CLEANUP_MSG; 5306 } else if (is_fixup(peek_command(todo_list, 0))) { 5307 /* 5308 * We need to update the squash message to skip 5309 * the latest commit message. 5310 */ 5311 struct commit *commit; 5312 const char *msg; 5313 const char *path = rebase_path_squash_msg(); 5314 const char *encoding = get_commit_output_encoding(); 5315 5316 if (parse_head(r, &commit)) { 5317 ret = error(_("could not parse HEAD")); 5318 goto out; 5319 } 5320 5321 p = repo_logmsg_reencode(r, commit, NULL, encoding); 5322 if (!p) { 5323 ret = error(_("could not parse commit %s"), 5324 oid_to_hex(&commit->object.oid)); 5325 goto unuse_commit_buffer; 5326 } 5327 find_commit_subject(p, &msg); 5328 if (write_message(msg, strlen(msg), path, 0)) { 5329 ret = error(_("could not write file: " 5330 "'%s'"), path); 5331 goto unuse_commit_buffer; 5332 } 5333 5334 ret = 0; 5335 5336 unuse_commit_buffer: 5337 repo_unuse_commit_buffer(r, commit, p); 5338 if (ret) 5339 goto out; 5340 } 5341 } 5342 5343 flags |= AMEND_MSG; 5344 } 5345 5346 if (is_clean) { 5347 if (refs_ref_exists(get_main_ref_store(r), 5348 "CHERRY_PICK_HEAD") && 5349 refs_delete_ref(get_main_ref_store(r), "", 5350 "CHERRY_PICK_HEAD", NULL, REF_NO_DEREF)) { 5351 ret = error(_("could not remove CHERRY_PICK_HEAD")); 5352 goto out; 5353 } 5354 5355 if (unlink(git_path_merge_msg(r)) && errno != ENOENT) { 5356 ret = error_errno(_("could not remove '%s'"), 5357 git_path_merge_msg(r)); 5358 goto out; 5359 } 5360 5361 if (!final_fixup) { 5362 ret = 0; 5363 goto out; 5364 } 5365 } 5366 5367 if (run_git_commit(final_fixup ? NULL : rebase_path_message(), 5368 reflog_action, opts, flags)) { 5369 ret = error(_("could not commit staged changes.")); 5370 goto out; 5371 } 5372 5373 unlink(rebase_path_amend()); 5374 unlink(git_path_merge_head(r)); 5375 refs_delete_ref(get_main_ref_store(r), "", "AUTO_MERGE", 5376 NULL, REF_NO_DEREF); 5377 if (final_fixup) { 5378 unlink(rebase_path_fixup_msg()); 5379 unlink(rebase_path_squash_msg()); 5380 } 5381 if (ctx->current_fixup_count > 0) { 5382 /* 5383 * Whether final fixup or not, we just cleaned up the commit 5384 * message... 5385 */ 5386 unlink(rebase_path_current_fixups()); 5387 strbuf_reset(&ctx->current_fixups); 5388 ctx->current_fixup_count = 0; 5389 } 5390 5391 ret = 0; 5392 5393out: 5394 strbuf_release(&rev); 5395 return ret; 5396} 5397 5398int sequencer_continue(struct repository *r, struct replay_opts *opts) 5399{ 5400 struct todo_list todo_list = TODO_LIST_INIT; 5401 int res; 5402 5403 if (read_and_refresh_cache(r, opts)) 5404 return -1; 5405 5406 if (read_populate_opts(opts)) 5407 return -1; 5408 if (is_rebase_i(opts)) { 5409 if ((res = read_populate_todo(r, &todo_list, opts))) 5410 goto release_todo_list; 5411 5412 if (file_exists(rebase_path_dropped())) { 5413 if ((res = todo_list_check_against_backup(r, opts, 5414 &todo_list))) 5415 goto release_todo_list; 5416 5417 unlink(rebase_path_dropped()); 5418 } 5419 5420 if (commit_staged_changes(r, opts, &todo_list)) { 5421 res = -1; 5422 goto release_todo_list; 5423 } 5424 } else if (!file_exists(get_todo_path(opts))) 5425 return continue_single_pick(r, opts); 5426 else if ((res = read_populate_todo(r, &todo_list, opts))) 5427 goto release_todo_list; 5428 5429 if (!is_rebase_i(opts)) { 5430 /* Verify that the conflict has been resolved */ 5431 if (refs_ref_exists(get_main_ref_store(r), 5432 "CHERRY_PICK_HEAD") || 5433 refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) { 5434 res = continue_single_pick(r, opts); 5435 if (res) 5436 goto release_todo_list; 5437 } 5438 if (index_differs_from(r, "HEAD", NULL, 0)) { 5439 res = error_dirty_index(r, opts); 5440 goto release_todo_list; 5441 } 5442 todo_list.current++; 5443 } else if (file_exists(rebase_path_stopped_sha())) { 5444 struct strbuf buf = STRBUF_INIT; 5445 struct object_id oid; 5446 5447 if (read_oneliner(&buf, rebase_path_stopped_sha(), 5448 READ_ONELINER_SKIP_IF_EMPTY) && 5449 !get_oid_hex(buf.buf, &oid)) 5450 record_in_rewritten(&oid, peek_command(&todo_list, 0)); 5451 strbuf_release(&buf); 5452 } 5453 5454 res = pick_commits(r, &todo_list, opts); 5455release_todo_list: 5456 todo_list_release(&todo_list); 5457 return res; 5458} 5459 5460static int single_pick(struct repository *r, 5461 struct commit *cmit, 5462 struct replay_opts *opts) 5463{ 5464 int check_todo; 5465 struct todo_item item; 5466 5467 item.command = opts->action == REPLAY_PICK ? 5468 TODO_PICK : TODO_REVERT; 5469 item.commit = cmit; 5470 5471 return do_pick_commit(r, &item, opts, 0, &check_todo); 5472} 5473 5474int sequencer_pick_revisions(struct repository *r, 5475 struct replay_opts *opts) 5476{ 5477 struct todo_list todo_list = TODO_LIST_INIT; 5478 struct object_id oid; 5479 int i, res; 5480 5481 assert(opts->revs); 5482 if (read_and_refresh_cache(r, opts)) { 5483 res = -1; 5484 goto out; 5485 } 5486 5487 for (i = 0; i < opts->revs->pending.nr; i++) { 5488 struct object_id oid; 5489 const char *name = opts->revs->pending.objects[i].name; 5490 5491 /* This happens when using --stdin. */ 5492 if (!strlen(name)) 5493 continue; 5494 5495 if (!repo_get_oid(r, name, &oid)) { 5496 if (!lookup_commit_reference_gently(r, &oid, 1)) { 5497 enum object_type type = odb_read_object_info(r->objects, 5498 &oid, NULL); 5499 res = error(_("%s: can't cherry-pick a %s"), 5500 name, type_name(type)); 5501 goto out; 5502 } 5503 } else { 5504 res = error(_("%s: bad revision"), name); 5505 goto out; 5506 } 5507 } 5508 5509 /* 5510 * If we were called as "git cherry-pick <commit>", just 5511 * cherry-pick/revert it, set CHERRY_PICK_HEAD / 5512 * REVERT_HEAD, and don't touch the sequencer state. 5513 * This means it is possible to cherry-pick in the middle 5514 * of a cherry-pick sequence. 5515 */ 5516 if (opts->revs->cmdline.nr == 1 && 5517 opts->revs->cmdline.rev->whence == REV_CMD_REV && 5518 opts->revs->no_walk && 5519 !opts->revs->cmdline.rev->flags) { 5520 struct commit *cmit; 5521 5522 if (prepare_revision_walk(opts->revs)) { 5523 res = error(_("revision walk setup failed")); 5524 goto out; 5525 } 5526 5527 cmit = get_revision(opts->revs); 5528 if (!cmit) { 5529 res = error(_("empty commit set passed")); 5530 goto out; 5531 } 5532 5533 if (get_revision(opts->revs)) 5534 BUG("unexpected extra commit from walk"); 5535 5536 res = single_pick(r, cmit, opts); 5537 goto out; 5538 } 5539 5540 /* 5541 * Start a new cherry-pick/ revert sequence; but 5542 * first, make sure that an existing one isn't in 5543 * progress 5544 */ 5545 5546 if (walk_revs_populate_todo(&todo_list, opts) || 5547 create_seq_dir(r) < 0) { 5548 res = -1; 5549 goto out; 5550 } 5551 5552 if (repo_get_oid(r, "HEAD", &oid) && (opts->action == REPLAY_REVERT)) { 5553 res = error(_("can't revert as initial commit")); 5554 goto out; 5555 } 5556 5557 if (save_head(oid_to_hex(&oid))) { 5558 res = -1; 5559 goto out; 5560 } 5561 5562 if (save_opts(opts)) { 5563 res = -1; 5564 goto out; 5565 } 5566 5567 update_abort_safety_file(); 5568 res = pick_commits(r, &todo_list, opts); 5569 5570out: 5571 todo_list_release(&todo_list); 5572 return res; 5573} 5574 5575void append_signoff(struct strbuf *msgbuf, size_t ignore_footer, unsigned flag) 5576{ 5577 unsigned no_dup_sob = flag & APPEND_SIGNOFF_DEDUP; 5578 struct strbuf sob = STRBUF_INIT; 5579 int has_footer; 5580 5581 strbuf_addstr(&sob, sign_off_header); 5582 strbuf_addstr(&sob, fmt_name(WANT_COMMITTER_IDENT)); 5583 strbuf_addch(&sob, '\n'); 5584 5585 if (!ignore_footer) 5586 strbuf_complete_line(msgbuf); 5587 5588 /* 5589 * If the whole message buffer is equal to the sob, pretend that we 5590 * found a conforming footer with a matching sob 5591 */ 5592 if (msgbuf->len - ignore_footer == sob.len && 5593 !strncmp(msgbuf->buf, sob.buf, sob.len)) 5594 has_footer = 3; 5595 else 5596 has_footer = has_conforming_footer(msgbuf, &sob, ignore_footer); 5597 5598 if (!has_footer) { 5599 const char *append_newlines = NULL; 5600 size_t len = msgbuf->len - ignore_footer; 5601 5602 if (!len) { 5603 /* 5604 * The buffer is completely empty. Leave foom for 5605 * the title and body to be filled in by the user. 5606 */ 5607 append_newlines = "\n\n"; 5608 } else if (len == 1) { 5609 /* 5610 * Buffer contains a single newline. Add another 5611 * so that we leave room for the title and body. 5612 */ 5613 append_newlines = "\n"; 5614 } else if (msgbuf->buf[len - 2] != '\n') { 5615 /* 5616 * Buffer ends with a single newline. Add another 5617 * so that there is an empty line between the message 5618 * body and the sob. 5619 */ 5620 append_newlines = "\n"; 5621 } /* else, the buffer already ends with two newlines. */ 5622 5623 if (append_newlines) 5624 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0, 5625 append_newlines, strlen(append_newlines)); 5626 } 5627 5628 if (has_footer != 3 && (!no_dup_sob || has_footer != 2)) 5629 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0, 5630 sob.buf, sob.len); 5631 5632 strbuf_release(&sob); 5633} 5634 5635struct labels_entry { 5636 struct hashmap_entry entry; 5637 char label[FLEX_ARRAY]; 5638}; 5639 5640static int labels_cmp(const void *fndata UNUSED, 5641 const struct hashmap_entry *eptr, 5642 const struct hashmap_entry *entry_or_key, const void *key) 5643{ 5644 const struct labels_entry *a, *b; 5645 5646 a = container_of(eptr, const struct labels_entry, entry); 5647 b = container_of(entry_or_key, const struct labels_entry, entry); 5648 5649 return key ? strcmp(a->label, key) : strcmp(a->label, b->label); 5650} 5651 5652struct string_entry { 5653 struct oidmap_entry entry; 5654 char string[FLEX_ARRAY]; 5655}; 5656 5657struct label_state { 5658 struct oidmap commit2label; 5659 struct hashmap labels; 5660 struct strbuf buf; 5661 int max_label_length; 5662}; 5663 5664static const char *label_oid(struct object_id *oid, const char *label, 5665 struct label_state *state) 5666{ 5667 struct labels_entry *labels_entry; 5668 struct string_entry *string_entry; 5669 struct object_id dummy; 5670 int i; 5671 5672 string_entry = oidmap_get(&state->commit2label, oid); 5673 if (string_entry) 5674 return string_entry->string; 5675 5676 /* 5677 * For "uninteresting" commits, i.e. commits that are not to be 5678 * rebased, and which can therefore not be labeled, we use a unique 5679 * abbreviation of the commit name. This is slightly more complicated 5680 * than calling repo_find_unique_abbrev() because we also need to make 5681 * sure that the abbreviation does not conflict with any other 5682 * label. 5683 * 5684 * We disallow "interesting" commits to be labeled by a string that 5685 * is a valid full-length hash, to ensure that we always can find an 5686 * abbreviation for any uninteresting commit's names that does not 5687 * clash with any other label. 5688 */ 5689 strbuf_reset(&state->buf); 5690 if (!label) { 5691 char *p; 5692 5693 strbuf_grow(&state->buf, GIT_MAX_HEXSZ); 5694 label = p = state->buf.buf; 5695 5696 repo_find_unique_abbrev_r(the_repository, p, oid, 5697 default_abbrev); 5698 5699 /* 5700 * We may need to extend the abbreviated hash so that there is 5701 * no conflicting label. 5702 */ 5703 if (hashmap_get_from_hash(&state->labels, strihash(p), p)) { 5704 size_t i = strlen(p) + 1; 5705 5706 oid_to_hex_r(p, oid); 5707 for (; i < the_hash_algo->hexsz; i++) { 5708 char save = p[i]; 5709 p[i] = '\0'; 5710 if (!hashmap_get_from_hash(&state->labels, 5711 strihash(p), p)) 5712 break; 5713 p[i] = save; 5714 } 5715 } 5716 } else { 5717 struct strbuf *buf = &state->buf; 5718 int label_is_utf8 = 1; /* start with this assumption */ 5719 size_t max_len = buf->len + state->max_label_length; 5720 5721 /* 5722 * Sanitize labels by replacing non-alpha-numeric characters 5723 * (including white-space ones) by dashes, as they might be 5724 * illegal in file names (and hence in ref names). 5725 * 5726 * Note that we retain non-ASCII UTF-8 characters (identified 5727 * via the most significant bit). They should be all acceptable 5728 * in file names. 5729 * 5730 * As we will use the labels as names of (loose) refs, it is 5731 * vital that the name not be longer than the maximum component 5732 * size of the file system (`NAME_MAX`). We are careful to 5733 * truncate the label accordingly, allowing for the `.lock` 5734 * suffix and for the label to be UTF-8 encoded (i.e. we avoid 5735 * truncating in the middle of a character). 5736 */ 5737 for (; *label && buf->len + 1 < max_len; label++) 5738 if (isalnum(*label) || 5739 (!label_is_utf8 && (*label & 0x80))) 5740 strbuf_addch(buf, *label); 5741 else if (*label & 0x80) { 5742 const char *p = label; 5743 5744 utf8_width(&p, NULL); 5745 if (p) { 5746 if (buf->len + (p - label) > max_len) 5747 break; 5748 strbuf_add(buf, label, p - label); 5749 label = p - 1; 5750 } else { 5751 label_is_utf8 = 0; 5752 strbuf_addch(buf, *label); 5753 } 5754 /* avoid leading dash and double-dashes */ 5755 } else if (buf->len && buf->buf[buf->len - 1] != '-') 5756 strbuf_addch(buf, '-'); 5757 if (!buf->len) { 5758 strbuf_addstr(buf, "rev-"); 5759 strbuf_add_unique_abbrev(buf, oid, default_abbrev); 5760 } 5761 label = buf->buf; 5762 5763 if ((buf->len == the_hash_algo->hexsz && 5764 !get_oid_hex(label, &dummy)) || 5765 (buf->len == 1 && *label == '#') || 5766 hashmap_get_from_hash(&state->labels, 5767 strihash(label), label)) { 5768 /* 5769 * If the label already exists, or if the label is a 5770 * valid full OID, or the label is a '#' (which we use 5771 * as a separator between merge heads and oneline), we 5772 * append a dash and a number to make it unique. 5773 */ 5774 size_t len = buf->len; 5775 5776 for (i = 2; ; i++) { 5777 strbuf_setlen(buf, len); 5778 strbuf_addf(buf, "-%d", i); 5779 if (!hashmap_get_from_hash(&state->labels, 5780 strihash(buf->buf), 5781 buf->buf)) 5782 break; 5783 } 5784 5785 label = buf->buf; 5786 } 5787 } 5788 5789 FLEX_ALLOC_STR(labels_entry, label, label); 5790 hashmap_entry_init(&labels_entry->entry, strihash(label)); 5791 hashmap_add(&state->labels, &labels_entry->entry); 5792 5793 FLEX_ALLOC_STR(string_entry, string, label); 5794 oidcpy(&string_entry->entry.oid, oid); 5795 oidmap_put(&state->commit2label, string_entry); 5796 5797 return string_entry->string; 5798} 5799 5800static int make_script_with_merges(struct pretty_print_context *pp, 5801 struct rev_info *revs, struct strbuf *out, 5802 unsigned flags) 5803{ 5804 int keep_empty = flags & TODO_LIST_KEEP_EMPTY; 5805 int rebase_cousins = flags & TODO_LIST_REBASE_COUSINS; 5806 int root_with_onto = flags & TODO_LIST_ROOT_WITH_ONTO; 5807 int skipped_commit = 0; 5808 struct strbuf buf = STRBUF_INIT, oneline = STRBUF_INIT; 5809 struct strbuf label_from_message = STRBUF_INIT; 5810 struct commit_list *commits = NULL, **tail = &commits, *iter; 5811 struct commit_list *tips = NULL, **tips_tail = &tips; 5812 struct commit *commit; 5813 struct oidmap commit2todo = OIDMAP_INIT; 5814 struct string_entry *entry; 5815 struct oidset interesting = OIDSET_INIT, child_seen = OIDSET_INIT, 5816 shown = OIDSET_INIT; 5817 struct label_state state = 5818 { OIDMAP_INIT, { NULL }, STRBUF_INIT, GIT_MAX_LABEL_LENGTH }; 5819 5820 int abbr = flags & TODO_LIST_ABBREVIATE_CMDS; 5821 const char *cmd_pick = abbr ? "p" : "pick", 5822 *cmd_label = abbr ? "l" : "label", 5823 *cmd_reset = abbr ? "t" : "reset", 5824 *cmd_merge = abbr ? "m" : "merge"; 5825 5826 repo_config_get_int(the_repository, "rebase.maxlabellength", &state.max_label_length); 5827 5828 oidmap_init(&commit2todo, 0); 5829 oidmap_init(&state.commit2label, 0); 5830 hashmap_init(&state.labels, labels_cmp, NULL, 0); 5831 strbuf_init(&state.buf, 32); 5832 load_branch_decorations(); 5833 5834 if (revs->cmdline.nr && (revs->cmdline.rev[0].flags & BOTTOM)) { 5835 struct labels_entry *onto_label_entry; 5836 struct object_id *oid = &revs->cmdline.rev[0].item->oid; 5837 FLEX_ALLOC_STR(entry, string, "onto"); 5838 oidcpy(&entry->entry.oid, oid); 5839 oidmap_put(&state.commit2label, entry); 5840 5841 FLEX_ALLOC_STR(onto_label_entry, label, "onto"); 5842 hashmap_entry_init(&onto_label_entry->entry, strihash("onto")); 5843 hashmap_add(&state.labels, &onto_label_entry->entry); 5844 } 5845 5846 /* 5847 * First phase: 5848 * - get onelines for all commits 5849 * - gather all branch tips (i.e. 2nd or later parents of merges) 5850 * - label all branch tips 5851 */ 5852 while ((commit = get_revision(revs))) { 5853 struct commit_list *to_merge; 5854 const char *p1, *p2; 5855 struct object_id *oid; 5856 int is_empty; 5857 5858 tail = &commit_list_insert(commit, tail)->next; 5859 oidset_insert(&interesting, &commit->object.oid); 5860 5861 is_empty = is_original_commit_empty(commit); 5862 if (!is_empty && (commit->object.flags & PATCHSAME)) { 5863 if (flags & TODO_LIST_WARN_SKIPPED_CHERRY_PICKS) 5864 warning(_("skipped previously applied commit %s"), 5865 short_commit_name(the_repository, commit)); 5866 skipped_commit = 1; 5867 continue; 5868 } 5869 if (is_empty && !keep_empty) 5870 continue; 5871 5872 strbuf_reset(&oneline); 5873 pretty_print_commit(pp, commit, &oneline); 5874 5875 to_merge = commit->parents ? commit->parents->next : NULL; 5876 if (!to_merge) { 5877 /* non-merge commit: easy case */ 5878 strbuf_reset(&buf); 5879 strbuf_addf(&buf, "%s %s %s", cmd_pick, 5880 oid_to_hex(&commit->object.oid), 5881 oneline.buf); 5882 if (is_empty) 5883 strbuf_addf(&buf, " %s empty", 5884 comment_line_str); 5885 5886 FLEX_ALLOC_STR(entry, string, buf.buf); 5887 oidcpy(&entry->entry.oid, &commit->object.oid); 5888 oidmap_put(&commit2todo, entry); 5889 5890 continue; 5891 } 5892 5893 /* Create a label from the commit message */ 5894 strbuf_reset(&label_from_message); 5895 if (skip_prefix(oneline.buf, "# Merge ", &p1) && 5896 (p1 = strchr(p1, '\'')) && 5897 (p2 = strchr(++p1, '\''))) 5898 strbuf_add(&label_from_message, p1, p2 - p1); 5899 else if (skip_prefix(oneline.buf, "# Merge pull request ", 5900 &p1) && 5901 (p1 = strstr(p1, " from "))) 5902 strbuf_addstr(&label_from_message, p1 + strlen(" from ")); 5903 else 5904 strbuf_addbuf(&label_from_message, &oneline); 5905 5906 strbuf_reset(&buf); 5907 strbuf_addf(&buf, "%s -C %s", 5908 cmd_merge, oid_to_hex(&commit->object.oid)); 5909 5910 /* label the tips of merged branches */ 5911 for (; to_merge; to_merge = to_merge->next) { 5912 const char *label = label_from_message.buf; 5913 const struct name_decoration *decoration = 5914 get_name_decoration(&to_merge->item->object); 5915 5916 if (decoration) 5917 skip_prefix(decoration->name, "refs/heads/", 5918 &label); 5919 5920 oid = &to_merge->item->object.oid; 5921 strbuf_addch(&buf, ' '); 5922 5923 if (!oidset_contains(&interesting, oid)) { 5924 strbuf_addstr(&buf, label_oid(oid, NULL, 5925 &state)); 5926 continue; 5927 } 5928 5929 tips_tail = &commit_list_insert(to_merge->item, 5930 tips_tail)->next; 5931 5932 strbuf_addstr(&buf, label_oid(oid, label, &state)); 5933 } 5934 strbuf_addf(&buf, " %s", oneline.buf); 5935 5936 FLEX_ALLOC_STR(entry, string, buf.buf); 5937 oidcpy(&entry->entry.oid, &commit->object.oid); 5938 oidmap_put(&commit2todo, entry); 5939 } 5940 if (skipped_commit) 5941 advise_if_enabled(ADVICE_SKIPPED_CHERRY_PICKS, 5942 _("use --reapply-cherry-picks to include skipped commits")); 5943 5944 /* 5945 * Second phase: 5946 * - label branch points 5947 * - add HEAD to the branch tips 5948 */ 5949 for (iter = commits; iter; iter = iter->next) { 5950 struct commit_list *parent = iter->item->parents; 5951 for (; parent; parent = parent->next) { 5952 struct object_id *oid = &parent->item->object.oid; 5953 if (!oidset_contains(&interesting, oid)) 5954 continue; 5955 if (oidset_insert(&child_seen, oid)) 5956 label_oid(oid, "branch-point", &state); 5957 } 5958 5959 /* Add HEAD as implicit "tip of branch" */ 5960 if (!iter->next) 5961 tips_tail = &commit_list_insert(iter->item, 5962 tips_tail)->next; 5963 } 5964 5965 /* 5966 * Third phase: output the todo list. This is a bit tricky, as we 5967 * want to avoid jumping back and forth between revisions. To 5968 * accomplish that goal, we walk backwards from the branch tips, 5969 * gathering commits not yet shown, reversing the list on the fly, 5970 * then outputting that list (labeling revisions as needed). 5971 */ 5972 strbuf_addf(out, "%s onto\n", cmd_label); 5973 for (iter = tips; iter; iter = iter->next) { 5974 struct commit_list *list = NULL, *iter2; 5975 5976 commit = iter->item; 5977 if (oidset_contains(&shown, &commit->object.oid)) 5978 continue; 5979 entry = oidmap_get(&state.commit2label, &commit->object.oid); 5980 5981 if (entry) 5982 strbuf_addf(out, "\n%s Branch %s\n", comment_line_str, entry->string); 5983 else 5984 strbuf_addch(out, '\n'); 5985 5986 while (oidset_contains(&interesting, &commit->object.oid) && 5987 !oidset_contains(&shown, &commit->object.oid)) { 5988 commit_list_insert(commit, &list); 5989 if (!commit->parents) { 5990 commit = NULL; 5991 break; 5992 } 5993 commit = commit->parents->item; 5994 } 5995 5996 if (!commit) 5997 strbuf_addf(out, "%s %s\n", cmd_reset, 5998 rebase_cousins || root_with_onto ? 5999 "onto" : "[new root]"); 6000 else { 6001 const char *to = NULL; 6002 6003 entry = oidmap_get(&state.commit2label, 6004 &commit->object.oid); 6005 if (entry) 6006 to = entry->string; 6007 else if (!rebase_cousins) 6008 to = label_oid(&commit->object.oid, NULL, 6009 &state); 6010 6011 if (!to || !strcmp(to, "onto")) 6012 strbuf_addf(out, "%s onto\n", cmd_reset); 6013 else { 6014 strbuf_reset(&oneline); 6015 pretty_print_commit(pp, commit, &oneline); 6016 strbuf_addf(out, "%s %s %s\n", 6017 cmd_reset, to, oneline.buf); 6018 } 6019 } 6020 6021 for (iter2 = list; iter2; iter2 = iter2->next) { 6022 struct object_id *oid = &iter2->item->object.oid; 6023 entry = oidmap_get(&commit2todo, oid); 6024 /* only show if not already upstream */ 6025 if (entry) 6026 strbuf_addf(out, "%s\n", entry->string); 6027 entry = oidmap_get(&state.commit2label, oid); 6028 if (entry) 6029 strbuf_addf(out, "%s %s\n", 6030 cmd_label, entry->string); 6031 oidset_insert(&shown, oid); 6032 } 6033 6034 free_commit_list(list); 6035 } 6036 6037 free_commit_list(commits); 6038 free_commit_list(tips); 6039 6040 strbuf_release(&label_from_message); 6041 strbuf_release(&oneline); 6042 strbuf_release(&buf); 6043 6044 oidset_clear(&interesting); 6045 oidset_clear(&child_seen); 6046 oidset_clear(&shown); 6047 oidmap_clear(&commit2todo, 1); 6048 oidmap_clear(&state.commit2label, 1); 6049 hashmap_clear_and_free(&state.labels, struct labels_entry, entry); 6050 strbuf_release(&state.buf); 6051 6052 return 0; 6053} 6054 6055int sequencer_make_script(struct repository *r, struct strbuf *out, 6056 struct strvec *argv, unsigned flags) 6057{ 6058 char *format = NULL; 6059 struct pretty_print_context pp = {0}; 6060 struct rev_info revs; 6061 struct commit *commit; 6062 int keep_empty = flags & TODO_LIST_KEEP_EMPTY; 6063 const char *insn = flags & TODO_LIST_ABBREVIATE_CMDS ? "p" : "pick"; 6064 int rebase_merges = flags & TODO_LIST_REBASE_MERGES; 6065 int reapply_cherry_picks = flags & TODO_LIST_REAPPLY_CHERRY_PICKS; 6066 int skipped_commit = 0; 6067 int ret = 0; 6068 6069 repo_init_revisions(r, &revs, NULL); 6070 revs.verbose_header = 1; 6071 if (!rebase_merges) 6072 revs.max_parents = 1; 6073 revs.cherry_mark = !reapply_cherry_picks; 6074 revs.limited = 1; 6075 revs.reverse = 1; 6076 revs.right_only = 1; 6077 revs.sort_order = REV_SORT_IN_GRAPH_ORDER; 6078 revs.topo_order = 1; 6079 6080 revs.pretty_given = 1; 6081 repo_config_get_string(the_repository, "rebase.instructionFormat", &format); 6082 if (!format || !*format) { 6083 free(format); 6084 format = xstrdup("# %s"); 6085 } 6086 if (*format != '#') { 6087 char *temp = format; 6088 format = xstrfmt("# %s", temp); 6089 free(temp); 6090 } 6091 6092 get_commit_format(format, &revs); 6093 free(format); 6094 pp.fmt = revs.commit_format; 6095 pp.output_encoding = get_log_output_encoding(); 6096 6097 setup_revisions_from_strvec(argv, &revs, NULL); 6098 if (argv->nr > 1) { 6099 ret = error(_("make_script: unhandled options")); 6100 goto cleanup; 6101 } 6102 6103 if (prepare_revision_walk(&revs) < 0) { 6104 ret = error(_("make_script: error preparing revisions")); 6105 goto cleanup; 6106 } 6107 6108 if (rebase_merges) { 6109 ret = make_script_with_merges(&pp, &revs, out, flags); 6110 goto cleanup; 6111 } 6112 6113 while ((commit = get_revision(&revs))) { 6114 int is_empty = is_original_commit_empty(commit); 6115 6116 if (!is_empty && (commit->object.flags & PATCHSAME)) { 6117 if (flags & TODO_LIST_WARN_SKIPPED_CHERRY_PICKS) 6118 warning(_("skipped previously applied commit %s"), 6119 short_commit_name(r, commit)); 6120 skipped_commit = 1; 6121 continue; 6122 } 6123 if (is_empty && !keep_empty) 6124 continue; 6125 strbuf_addf(out, "%s %s ", insn, 6126 oid_to_hex(&commit->object.oid)); 6127 pretty_print_commit(&pp, commit, out); 6128 if (is_empty) 6129 strbuf_addf(out, " %s empty", comment_line_str); 6130 strbuf_addch(out, '\n'); 6131 } 6132 if (skipped_commit) 6133 advise_if_enabled(ADVICE_SKIPPED_CHERRY_PICKS, 6134 _("use --reapply-cherry-picks to include skipped commits")); 6135cleanup: 6136 release_revisions(&revs); 6137 return ret; 6138} 6139 6140/* 6141 * Add commands after pick and (series of) squash/fixup commands 6142 * in the todo list. 6143 */ 6144static void todo_list_add_exec_commands(struct todo_list *todo_list, 6145 struct string_list *commands) 6146{ 6147 struct strbuf *buf = &todo_list->buf; 6148 size_t base_offset = buf->len; 6149 int i, insert, nr = 0, alloc = 0; 6150 struct todo_item *items = NULL, *base_items = NULL; 6151 6152 CALLOC_ARRAY(base_items, commands->nr); 6153 for (i = 0; i < commands->nr; i++) { 6154 size_t command_len = strlen(commands->items[i].string); 6155 6156 strbuf_addstr(buf, commands->items[i].string); 6157 strbuf_addch(buf, '\n'); 6158 6159 base_items[i].command = TODO_EXEC; 6160 base_items[i].offset_in_buf = base_offset; 6161 base_items[i].arg_offset = base_offset; 6162 base_items[i].arg_len = command_len; 6163 6164 base_offset += command_len + 1; 6165 } 6166 6167 /* 6168 * Insert <commands> after every pick. Here, fixup/squash chains 6169 * are considered part of the pick, so we insert the commands *after* 6170 * those chains if there are any. 6171 * 6172 * As we insert the exec commands immediately after rearranging 6173 * any fixups and before the user edits the list, a fixup chain 6174 * can never contain comments (any comments are empty picks that 6175 * have been commented out because the user did not specify 6176 * --keep-empty). So, it is safe to insert an exec command 6177 * without looking at the command following a comment. 6178 */ 6179 insert = 0; 6180 for (i = 0; i < todo_list->nr; i++) { 6181 enum todo_command command = todo_list->items[i].command; 6182 if (insert && !is_fixup(command)) { 6183 ALLOC_GROW(items, nr + commands->nr, alloc); 6184 COPY_ARRAY(items + nr, base_items, commands->nr); 6185 nr += commands->nr; 6186 6187 insert = 0; 6188 } 6189 6190 ALLOC_GROW(items, nr + 1, alloc); 6191 items[nr++] = todo_list->items[i]; 6192 6193 if (command == TODO_PICK || command == TODO_MERGE) 6194 insert = 1; 6195 } 6196 6197 /* insert or append final <commands> */ 6198 if (insert) { 6199 ALLOC_GROW(items, nr + commands->nr, alloc); 6200 COPY_ARRAY(items + nr, base_items, commands->nr); 6201 nr += commands->nr; 6202 } 6203 6204 free(base_items); 6205 FREE_AND_NULL(todo_list->items); 6206 todo_list->items = items; 6207 todo_list->nr = nr; 6208 todo_list->alloc = alloc; 6209} 6210 6211static void todo_list_to_strbuf(struct repository *r, 6212 struct todo_list *todo_list, 6213 struct strbuf *buf, int num, unsigned flags) 6214{ 6215 struct todo_item *item; 6216 int i, max = todo_list->nr; 6217 6218 if (num > 0 && num < max) 6219 max = num; 6220 6221 for (item = todo_list->items, i = 0; i < max; i++, item++) { 6222 char cmd; 6223 6224 /* if the item is not a command write it and continue */ 6225 if (item->command >= TODO_COMMENT) { 6226 strbuf_addf(buf, "%.*s\n", item->arg_len, 6227 todo_item_get_arg(todo_list, item)); 6228 continue; 6229 } 6230 6231 /* add command to the buffer */ 6232 cmd = command_to_char(item->command); 6233 if ((flags & TODO_LIST_ABBREVIATE_CMDS) && cmd) 6234 strbuf_addch(buf, cmd); 6235 else 6236 strbuf_addstr(buf, command_to_string(item->command)); 6237 6238 /* add commit id */ 6239 if (item->commit) { 6240 const char *oid = flags & TODO_LIST_SHORTEN_IDS ? 6241 short_commit_name(r, item->commit) : 6242 oid_to_hex(&item->commit->object.oid); 6243 6244 if (item->command == TODO_FIXUP) { 6245 if (item->flags & TODO_EDIT_FIXUP_MSG) 6246 strbuf_addstr(buf, " -c"); 6247 else if (item->flags & TODO_REPLACE_FIXUP_MSG) { 6248 strbuf_addstr(buf, " -C"); 6249 } 6250 } 6251 6252 if (item->command == TODO_MERGE) { 6253 if (item->flags & TODO_EDIT_MERGE_MSG) 6254 strbuf_addstr(buf, " -c"); 6255 else 6256 strbuf_addstr(buf, " -C"); 6257 } 6258 6259 strbuf_addf(buf, " %s", oid); 6260 } 6261 6262 /* add all the rest */ 6263 if (!item->arg_len) 6264 strbuf_addch(buf, '\n'); 6265 else 6266 strbuf_addf(buf, " %.*s\n", item->arg_len, 6267 todo_item_get_arg(todo_list, item)); 6268 } 6269} 6270 6271int todo_list_write_to_file(struct repository *r, struct todo_list *todo_list, 6272 const char *file, const char *shortrevisions, 6273 const char *shortonto, int num, unsigned flags) 6274{ 6275 int res; 6276 struct strbuf buf = STRBUF_INIT; 6277 6278 todo_list_to_strbuf(r, todo_list, &buf, num, flags); 6279 if (flags & TODO_LIST_APPEND_TODO_HELP) 6280 append_todo_help(count_commands(todo_list), 6281 shortrevisions, shortonto, &buf); 6282 6283 res = write_message(buf.buf, buf.len, file, 0); 6284 strbuf_release(&buf); 6285 6286 return res; 6287} 6288 6289/* skip picking commits whose parents are unchanged */ 6290static int skip_unnecessary_picks(struct repository *r, 6291 struct todo_list *todo_list, 6292 struct object_id *base_oid) 6293{ 6294 struct object_id *parent_oid; 6295 int i; 6296 6297 for (i = 0; i < todo_list->nr; i++) { 6298 struct todo_item *item = todo_list->items + i; 6299 6300 if (item->command >= TODO_NOOP) 6301 continue; 6302 if (item->command != TODO_PICK) 6303 break; 6304 if (repo_parse_commit(r, item->commit)) { 6305 return error(_("could not parse commit '%s'"), 6306 oid_to_hex(&item->commit->object.oid)); 6307 } 6308 if (!item->commit->parents) 6309 break; /* root commit */ 6310 if (item->commit->parents->next) 6311 break; /* merge commit */ 6312 parent_oid = &item->commit->parents->item->object.oid; 6313 if (!oideq(parent_oid, base_oid)) 6314 break; 6315 oidcpy(base_oid, &item->commit->object.oid); 6316 } 6317 if (i > 0) { 6318 const char *done_path = rebase_path_done(); 6319 6320 if (todo_list_write_to_file(r, todo_list, done_path, NULL, NULL, i, 0)) { 6321 error_errno(_("could not write to '%s'"), done_path); 6322 return -1; 6323 } 6324 6325 MOVE_ARRAY(todo_list->items, todo_list->items + i, todo_list->nr - i); 6326 todo_list->nr -= i; 6327 todo_list->current = 0; 6328 todo_list->done_nr += i; 6329 6330 if (is_fixup(peek_command(todo_list, 0))) 6331 record_in_rewritten(base_oid, peek_command(todo_list, 0)); 6332 } 6333 6334 return 0; 6335} 6336 6337struct todo_add_branch_context { 6338 struct todo_item *items; 6339 size_t items_nr; 6340 size_t items_alloc; 6341 struct strbuf *buf; 6342 struct commit *commit; 6343 struct string_list refs_to_oids; 6344}; 6345 6346static int add_decorations_to_list(const struct commit *commit, 6347 struct todo_add_branch_context *ctx) 6348{ 6349 const struct name_decoration *decoration = get_name_decoration(&commit->object); 6350 const char *head_ref = refs_resolve_ref_unsafe(get_main_ref_store(the_repository), 6351 "HEAD", 6352 RESOLVE_REF_READING, 6353 NULL, 6354 NULL); 6355 6356 while (decoration) { 6357 struct todo_item *item; 6358 const char *path; 6359 size_t base_offset = ctx->buf->len; 6360 6361 /* 6362 * If the branch is the current HEAD, then it will be 6363 * updated by the default rebase behavior. 6364 */ 6365 if (head_ref && !strcmp(head_ref, decoration->name)) { 6366 decoration = decoration->next; 6367 continue; 6368 } 6369 6370 ALLOC_GROW(ctx->items, 6371 ctx->items_nr + 1, 6372 ctx->items_alloc); 6373 item = &ctx->items[ctx->items_nr]; 6374 memset(item, 0, sizeof(*item)); 6375 6376 /* If the branch is checked out, then leave a comment instead. */ 6377 if ((path = branch_checked_out(decoration->name))) { 6378 item->command = TODO_COMMENT; 6379 strbuf_commented_addf(ctx->buf, comment_line_str, 6380 "Ref %s checked out at '%s'\n", 6381 decoration->name, path); 6382 } else { 6383 struct string_list_item *sti; 6384 item->command = TODO_UPDATE_REF; 6385 strbuf_addf(ctx->buf, "%s\n", decoration->name); 6386 6387 sti = string_list_insert(&ctx->refs_to_oids, 6388 decoration->name); 6389 sti->util = init_update_ref_record(decoration->name); 6390 } 6391 6392 item->offset_in_buf = base_offset; 6393 item->arg_offset = base_offset; 6394 item->arg_len = ctx->buf->len - base_offset; 6395 ctx->items_nr++; 6396 6397 decoration = decoration->next; 6398 } 6399 6400 return 0; 6401} 6402 6403/* 6404 * For each 'pick' command, find out if the commit has a decoration in 6405 * refs/heads/. If so, then add a 'label for-update-refs/' command. 6406 */ 6407static int todo_list_add_update_ref_commands(struct todo_list *todo_list) 6408{ 6409 int i, res; 6410 struct todo_add_branch_context ctx = { 6411 .buf = &todo_list->buf, 6412 .refs_to_oids = STRING_LIST_INIT_DUP, 6413 }; 6414 6415 ctx.items_alloc = 2 * todo_list->nr + 1; 6416 ALLOC_ARRAY(ctx.items, ctx.items_alloc); 6417 6418 load_branch_decorations(); 6419 6420 for (i = 0; i < todo_list->nr; ) { 6421 struct todo_item *item = &todo_list->items[i]; 6422 6423 /* insert ith item into new list */ 6424 ALLOC_GROW(ctx.items, 6425 ctx.items_nr + 1, 6426 ctx.items_alloc); 6427 6428 ctx.items[ctx.items_nr++] = todo_list->items[i++]; 6429 6430 if (item->commit) { 6431 ctx.commit = item->commit; 6432 add_decorations_to_list(item->commit, &ctx); 6433 } 6434 } 6435 6436 res = write_update_refs_state(&ctx.refs_to_oids); 6437 6438 string_list_clear(&ctx.refs_to_oids, 1); 6439 6440 if (res) { 6441 /* we failed, so clean up the new list. */ 6442 free(ctx.items); 6443 return res; 6444 } 6445 6446 free(todo_list->items); 6447 todo_list->items = ctx.items; 6448 todo_list->nr = ctx.items_nr; 6449 todo_list->alloc = ctx.items_alloc; 6450 6451 return 0; 6452} 6453 6454int complete_action(struct repository *r, struct replay_opts *opts, unsigned flags, 6455 const char *shortrevisions, const char *onto_name, 6456 struct commit *onto, const struct object_id *orig_head, 6457 struct string_list *commands, unsigned autosquash, 6458 unsigned update_refs, 6459 struct todo_list *todo_list) 6460{ 6461 char shortonto[GIT_MAX_HEXSZ + 1]; 6462 const char *todo_file = rebase_path_todo(); 6463 struct todo_list new_todo = TODO_LIST_INIT; 6464 struct strbuf *buf = &todo_list->buf, buf2 = STRBUF_INIT; 6465 struct object_id oid = onto->object.oid; 6466 int res; 6467 6468 repo_find_unique_abbrev_r(r, shortonto, &oid, 6469 DEFAULT_ABBREV); 6470 6471 if (buf->len == 0) { 6472 struct todo_item *item = append_new_todo(todo_list); 6473 item->command = TODO_NOOP; 6474 item->commit = NULL; 6475 item->arg_len = item->arg_offset = item->flags = item->offset_in_buf = 0; 6476 } 6477 6478 if (update_refs && todo_list_add_update_ref_commands(todo_list)) 6479 return -1; 6480 6481 if (autosquash && todo_list_rearrange_squash(todo_list)) 6482 return -1; 6483 6484 if (commands->nr) 6485 todo_list_add_exec_commands(todo_list, commands); 6486 6487 if (count_commands(todo_list) == 0) { 6488 apply_autostash(rebase_path_autostash()); 6489 sequencer_remove_state(opts); 6490 6491 return error(_("nothing to do")); 6492 } 6493 6494 res = edit_todo_list(r, opts, todo_list, &new_todo, shortrevisions, 6495 shortonto, flags); 6496 if (res == -1) 6497 return -1; 6498 else if (res == -2) { 6499 apply_autostash(rebase_path_autostash()); 6500 sequencer_remove_state(opts); 6501 6502 return -1; 6503 } else if (res == -3) { 6504 apply_autostash(rebase_path_autostash()); 6505 sequencer_remove_state(opts); 6506 todo_list_release(&new_todo); 6507 6508 return error(_("nothing to do")); 6509 } else if (res == -4) { 6510 checkout_onto(r, opts, onto_name, &onto->object.oid, orig_head); 6511 todo_list_release(&new_todo); 6512 6513 return -1; 6514 } 6515 6516 /* Expand the commit IDs */ 6517 todo_list_to_strbuf(r, &new_todo, &buf2, -1, 0); 6518 strbuf_swap(&new_todo.buf, &buf2); 6519 strbuf_release(&buf2); 6520 /* Nothing is done yet, and we're reparsing, so let's reset the count */ 6521 new_todo.total_nr = 0; 6522 if (todo_list_parse_insn_buffer(r, opts, new_todo.buf.buf, &new_todo) < 0) 6523 BUG("invalid todo list after expanding IDs:\n%s", 6524 new_todo.buf.buf); 6525 6526 if (opts->allow_ff && skip_unnecessary_picks(r, &new_todo, &oid)) { 6527 todo_list_release(&new_todo); 6528 return error(_("could not skip unnecessary pick commands")); 6529 } 6530 6531 if (todo_list_write_to_file(r, &new_todo, todo_file, NULL, NULL, -1, 6532 flags & ~(TODO_LIST_SHORTEN_IDS))) { 6533 todo_list_release(&new_todo); 6534 return error_errno(_("could not write '%s'"), todo_file); 6535 } 6536 6537 res = -1; 6538 6539 if (checkout_onto(r, opts, onto_name, &oid, orig_head)) 6540 goto cleanup; 6541 6542 if (require_clean_work_tree(r, "rebase", NULL, 1, 1)) 6543 goto cleanup; 6544 6545 todo_list_write_total_nr(&new_todo); 6546 res = pick_commits(r, &new_todo, opts); 6547 6548cleanup: 6549 todo_list_release(&new_todo); 6550 6551 return res; 6552} 6553 6554struct subject2item_entry { 6555 struct hashmap_entry entry; 6556 int i; 6557 char subject[FLEX_ARRAY]; 6558}; 6559 6560static int subject2item_cmp(const void *fndata UNUSED, 6561 const struct hashmap_entry *eptr, 6562 const struct hashmap_entry *entry_or_key, 6563 const void *key) 6564{ 6565 const struct subject2item_entry *a, *b; 6566 6567 a = container_of(eptr, const struct subject2item_entry, entry); 6568 b = container_of(entry_or_key, const struct subject2item_entry, entry); 6569 6570 return key ? strcmp(a->subject, key) : strcmp(a->subject, b->subject); 6571} 6572 6573define_commit_slab(commit_todo_item, struct todo_item *); 6574 6575static int skip_fixupish(const char *subject, const char **p) { 6576 return skip_prefix(subject, "fixup! ", p) || 6577 skip_prefix(subject, "amend! ", p) || 6578 skip_prefix(subject, "squash! ", p); 6579} 6580 6581/* 6582 * Rearrange the todo list that has both "pick commit-id msg" and "pick 6583 * commit-id fixup!/squash! msg" in it so that the latter is put immediately 6584 * after the former, and change "pick" to "fixup"/"squash". 6585 * 6586 * Note that if the config has specified a custom instruction format, each log 6587 * message will have to be retrieved from the commit (as the oneline in the 6588 * script cannot be trusted) in order to normalize the autosquash arrangement. 6589 */ 6590int todo_list_rearrange_squash(struct todo_list *todo_list) 6591{ 6592 struct hashmap subject2item; 6593 int rearranged = 0, *next, *tail, i, nr = 0; 6594 char **subjects; 6595 struct commit_todo_item commit_todo; 6596 struct todo_item *items = NULL; 6597 int ret = 0; 6598 6599 init_commit_todo_item(&commit_todo); 6600 /* 6601 * The hashmap maps onelines to the respective todo list index. 6602 * 6603 * If any items need to be rearranged, the next[i] value will indicate 6604 * which item was moved directly after the i'th. 6605 * 6606 * In that case, last[i] will indicate the index of the latest item to 6607 * be moved to appear after the i'th. 6608 */ 6609 hashmap_init(&subject2item, subject2item_cmp, NULL, todo_list->nr); 6610 ALLOC_ARRAY(next, todo_list->nr); 6611 ALLOC_ARRAY(tail, todo_list->nr); 6612 ALLOC_ARRAY(subjects, todo_list->nr); 6613 for (i = 0; i < todo_list->nr; i++) { 6614 struct strbuf buf = STRBUF_INIT; 6615 struct todo_item *item = todo_list->items + i; 6616 const char *commit_buffer, *subject, *p; 6617 size_t subject_len; 6618 int i2 = -1; 6619 struct subject2item_entry *entry; 6620 6621 next[i] = tail[i] = -1; 6622 if (!item->commit || item->command == TODO_DROP) { 6623 subjects[i] = NULL; 6624 continue; 6625 } 6626 6627 if (is_fixup(item->command)) { 6628 ret = error(_("the script was already rearranged.")); 6629 goto cleanup; 6630 } 6631 6632 repo_parse_commit(the_repository, item->commit); 6633 commit_buffer = repo_logmsg_reencode(the_repository, 6634 item->commit, NULL, 6635 "UTF-8"); 6636 find_commit_subject(commit_buffer, &subject); 6637 format_subject(&buf, subject, " "); 6638 subject = subjects[i] = strbuf_detach(&buf, &subject_len); 6639 repo_unuse_commit_buffer(the_repository, item->commit, 6640 commit_buffer); 6641 if (skip_fixupish(subject, &p)) { 6642 struct commit *commit2; 6643 6644 for (;;) { 6645 while (isspace(*p)) 6646 p++; 6647 if (!skip_fixupish(p, &p)) 6648 break; 6649 } 6650 6651 entry = hashmap_get_entry_from_hash(&subject2item, 6652 strhash(p), p, 6653 struct subject2item_entry, 6654 entry); 6655 if (entry) 6656 /* found by title */ 6657 i2 = entry->i; 6658 else if (!strchr(p, ' ') && 6659 (commit2 = 6660 lookup_commit_reference_by_name(p)) && 6661 *commit_todo_item_at(&commit_todo, commit2)) 6662 /* found by commit name */ 6663 i2 = *commit_todo_item_at(&commit_todo, commit2) 6664 - todo_list->items; 6665 else { 6666 /* copy can be a prefix of the commit subject */ 6667 for (i2 = 0; i2 < i; i2++) 6668 if (subjects[i2] && 6669 starts_with(subjects[i2], p)) 6670 break; 6671 if (i2 == i) 6672 i2 = -1; 6673 } 6674 } 6675 if (i2 >= 0) { 6676 rearranged = 1; 6677 if (starts_with(subject, "fixup!")) { 6678 todo_list->items[i].command = TODO_FIXUP; 6679 } else if (starts_with(subject, "amend!")) { 6680 todo_list->items[i].command = TODO_FIXUP; 6681 todo_list->items[i].flags = TODO_REPLACE_FIXUP_MSG; 6682 } else { 6683 todo_list->items[i].command = TODO_SQUASH; 6684 } 6685 if (tail[i2] < 0) { 6686 next[i] = next[i2]; 6687 next[i2] = i; 6688 } else { 6689 next[i] = next[tail[i2]]; 6690 next[tail[i2]] = i; 6691 } 6692 tail[i2] = i; 6693 } else if (!hashmap_get_from_hash(&subject2item, 6694 strhash(subject), subject)) { 6695 FLEX_ALLOC_MEM(entry, subject, subject, subject_len); 6696 entry->i = i; 6697 hashmap_entry_init(&entry->entry, 6698 strhash(entry->subject)); 6699 hashmap_put(&subject2item, &entry->entry); 6700 } 6701 6702 *commit_todo_item_at(&commit_todo, item->commit) = item; 6703 } 6704 6705 if (rearranged) { 6706 ALLOC_ARRAY(items, todo_list->nr); 6707 6708 for (i = 0; i < todo_list->nr; i++) { 6709 enum todo_command command = todo_list->items[i].command; 6710 int cur = i; 6711 6712 /* 6713 * Initially, all commands are 'pick's. If it is a 6714 * fixup or a squash now, we have rearranged it. 6715 */ 6716 if (is_fixup(command)) 6717 continue; 6718 6719 while (cur >= 0) { 6720 items[nr++] = todo_list->items[cur]; 6721 cur = next[cur]; 6722 } 6723 } 6724 6725 assert(nr == todo_list->nr); 6726 todo_list->alloc = nr; 6727 FREE_AND_NULL(todo_list->items); 6728 todo_list->items = items; 6729 } 6730 6731cleanup: 6732 free(next); 6733 free(tail); 6734 for (i = 0; i < todo_list->nr; i++) 6735 free(subjects[i]); 6736 free(subjects); 6737 hashmap_clear_and_free(&subject2item, struct subject2item_entry, entry); 6738 6739 clear_commit_todo_item(&commit_todo); 6740 6741 return ret; 6742} 6743 6744int sequencer_determine_whence(struct repository *r, enum commit_whence *whence) 6745{ 6746 if (refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD")) { 6747 struct object_id cherry_pick_head, rebase_head; 6748 6749 if (file_exists(git_path_seq_dir())) 6750 *whence = FROM_CHERRY_PICK_MULTI; 6751 if (file_exists(rebase_path()) && 6752 !repo_get_oid(r, "REBASE_HEAD", &rebase_head) && 6753 !repo_get_oid(r, "CHERRY_PICK_HEAD", &cherry_pick_head) && 6754 oideq(&rebase_head, &cherry_pick_head)) 6755 *whence = FROM_REBASE_PICK; 6756 else 6757 *whence = FROM_CHERRY_PICK_SINGLE; 6758 6759 return 1; 6760 } 6761 6762 return 0; 6763} 6764 6765int sequencer_get_update_refs_state(const char *wt_dir, 6766 struct string_list *refs) 6767{ 6768 int result = 0; 6769 FILE *fp = NULL; 6770 struct strbuf ref = STRBUF_INIT; 6771 struct strbuf hash = STRBUF_INIT; 6772 struct update_ref_record *rec = NULL; 6773 6774 char *path = rebase_path_update_refs(wt_dir); 6775 6776 fp = fopen(path, "r"); 6777 if (!fp) 6778 goto cleanup; 6779 6780 while (strbuf_getline(&ref, fp) != EOF) { 6781 struct string_list_item *item; 6782 6783 CALLOC_ARRAY(rec, 1); 6784 6785 if (strbuf_getline(&hash, fp) == EOF || 6786 get_oid_hex(hash.buf, &rec->before)) { 6787 warning(_("update-refs file at '%s' is invalid"), 6788 path); 6789 result = -1; 6790 goto cleanup; 6791 } 6792 6793 if (strbuf_getline(&hash, fp) == EOF || 6794 get_oid_hex(hash.buf, &rec->after)) { 6795 warning(_("update-refs file at '%s' is invalid"), 6796 path); 6797 result = -1; 6798 goto cleanup; 6799 } 6800 6801 item = string_list_insert(refs, ref.buf); 6802 item->util = rec; 6803 rec = NULL; 6804 } 6805 6806cleanup: 6807 if (fp) 6808 fclose(fp); 6809 free(path); 6810 free(rec); 6811 strbuf_release(&ref); 6812 strbuf_release(&hash); 6813 return result; 6814}