sequencer.con commit rebase -i: fix SIGSEGV when 'merge <branch>' fails (bc9238b)
   1#include "cache.h"
   2#include "config.h"
   3#include "lockfile.h"
   4#include "dir.h"
   5#include "object.h"
   6#include "commit.h"
   7#include "sequencer.h"
   8#include "tag.h"
   9#include "run-command.h"
  10#include "exec-cmd.h"
  11#include "utf8.h"
  12#include "cache-tree.h"
  13#include "diff.h"
  14#include "revision.h"
  15#include "rerere.h"
  16#include "merge-recursive.h"
  17#include "refs.h"
  18#include "argv-array.h"
  19#include "quote.h"
  20#include "trailer.h"
  21#include "log-tree.h"
  22#include "wt-status.h"
  23#include "hashmap.h"
  24#include "notes-utils.h"
  25#include "sigchain.h"
  26#include "unpack-trees.h"
  27#include "worktree.h"
  28#include "oidmap.h"
  29#include "oidset.h"
  30#include "alias.h"
  31
  32#define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
  33
  34const char sign_off_header[] = "Signed-off-by: ";
  35static const char cherry_picked_prefix[] = "(cherry picked from commit ";
  36
  37GIT_PATH_FUNC(git_path_commit_editmsg, "COMMIT_EDITMSG")
  38
  39GIT_PATH_FUNC(git_path_seq_dir, "sequencer")
  40
  41static GIT_PATH_FUNC(git_path_todo_file, "sequencer/todo")
  42static GIT_PATH_FUNC(git_path_opts_file, "sequencer/opts")
  43static GIT_PATH_FUNC(git_path_head_file, "sequencer/head")
  44static GIT_PATH_FUNC(git_path_abort_safety_file, "sequencer/abort-safety")
  45
  46static GIT_PATH_FUNC(rebase_path, "rebase-merge")
  47/*
  48 * The file containing rebase commands, comments, and empty lines.
  49 * This file is created by "git rebase -i" then edited by the user. As
  50 * the lines are processed, they are removed from the front of this
  51 * file and written to the tail of 'done'.
  52 */
  53static GIT_PATH_FUNC(rebase_path_todo, "rebase-merge/git-rebase-todo")
  54/*
  55 * The rebase command lines that have already been processed. A line
  56 * is moved here when it is first handled, before any associated user
  57 * actions.
  58 */
  59static GIT_PATH_FUNC(rebase_path_done, "rebase-merge/done")
  60/*
  61 * The file to keep track of how many commands were already processed (e.g.
  62 * for the prompt).
  63 */
  64static GIT_PATH_FUNC(rebase_path_msgnum, "rebase-merge/msgnum");
  65/*
  66 * The file to keep track of how many commands are to be processed in total
  67 * (e.g. for the prompt).
  68 */
  69static GIT_PATH_FUNC(rebase_path_msgtotal, "rebase-merge/end");
  70/*
  71 * The commit message that is planned to be used for any changes that
  72 * need to be committed following a user interaction.
  73 */
  74static GIT_PATH_FUNC(rebase_path_message, "rebase-merge/message")
  75/*
  76 * The file into which is accumulated the suggested commit message for
  77 * squash/fixup commands. When the first of a series of squash/fixups
  78 * is seen, the file is created and the commit message from the
  79 * previous commit and from the first squash/fixup commit are written
  80 * to it. The commit message for each subsequent squash/fixup commit
  81 * is appended to the file as it is processed.
  82 */
  83static GIT_PATH_FUNC(rebase_path_squash_msg, "rebase-merge/message-squash")
  84/*
  85 * If the current series of squash/fixups has not yet included a squash
  86 * command, then this file exists and holds the commit message of the
  87 * original "pick" commit.  (If the series ends without a "squash"
  88 * command, then this can be used as the commit message of the combined
  89 * commit without opening the editor.)
  90 */
  91static GIT_PATH_FUNC(rebase_path_fixup_msg, "rebase-merge/message-fixup")
  92/*
  93 * This file contains the list fixup/squash commands that have been
  94 * accumulated into message-fixup or message-squash so far.
  95 */
  96static GIT_PATH_FUNC(rebase_path_current_fixups, "rebase-merge/current-fixups")
  97/*
  98 * A script to set the GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL, and
  99 * GIT_AUTHOR_DATE that will be used for the commit that is currently
 100 * being rebased.
 101 */
 102static GIT_PATH_FUNC(rebase_path_author_script, "rebase-merge/author-script")
 103/*
 104 * When an "edit" rebase command is being processed, the SHA1 of the
 105 * commit to be edited is recorded in this file.  When "git rebase
 106 * --continue" is executed, if there are any staged changes then they
 107 * will be amended to the HEAD commit, but only provided the HEAD
 108 * commit is still the commit to be edited.  When any other rebase
 109 * command is processed, this file is deleted.
 110 */
 111static GIT_PATH_FUNC(rebase_path_amend, "rebase-merge/amend")
 112/*
 113 * When we stop at a given patch via the "edit" command, this file contains
 114 * the abbreviated commit name of the corresponding patch.
 115 */
 116static GIT_PATH_FUNC(rebase_path_stopped_sha, "rebase-merge/stopped-sha")
 117/*
 118 * For the post-rewrite hook, we make a list of rewritten commits and
 119 * their new sha1s.  The rewritten-pending list keeps the sha1s of
 120 * commits that have been processed, but not committed yet,
 121 * e.g. because they are waiting for a 'squash' command.
 122 */
 123static GIT_PATH_FUNC(rebase_path_rewritten_list, "rebase-merge/rewritten-list")
 124static GIT_PATH_FUNC(rebase_path_rewritten_pending,
 125        "rebase-merge/rewritten-pending")
 126
 127/*
 128 * The path of the file containig the OID of the "squash onto" commit, i.e.
 129 * the dummy commit used for `reset [new root]`.
 130 */
 131static GIT_PATH_FUNC(rebase_path_squash_onto, "rebase-merge/squash-onto")
 132
 133/*
 134 * The path of the file listing refs that need to be deleted after the rebase
 135 * finishes. This is used by the `label` command to record the need for cleanup.
 136 */
 137static GIT_PATH_FUNC(rebase_path_refs_to_delete, "rebase-merge/refs-to-delete")
 138
 139/*
 140 * The following files are written by git-rebase just after parsing the
 141 * command-line (and are only consumed, not modified, by the sequencer).
 142 */
 143static GIT_PATH_FUNC(rebase_path_gpg_sign_opt, "rebase-merge/gpg_sign_opt")
 144static GIT_PATH_FUNC(rebase_path_orig_head, "rebase-merge/orig-head")
 145static GIT_PATH_FUNC(rebase_path_verbose, "rebase-merge/verbose")
 146static GIT_PATH_FUNC(rebase_path_signoff, "rebase-merge/signoff")
 147static GIT_PATH_FUNC(rebase_path_head_name, "rebase-merge/head-name")
 148static GIT_PATH_FUNC(rebase_path_onto, "rebase-merge/onto")
 149static GIT_PATH_FUNC(rebase_path_autostash, "rebase-merge/autostash")
 150static GIT_PATH_FUNC(rebase_path_strategy, "rebase-merge/strategy")
 151static GIT_PATH_FUNC(rebase_path_strategy_opts, "rebase-merge/strategy_opts")
 152static GIT_PATH_FUNC(rebase_path_allow_rerere_autoupdate, "rebase-merge/allow_rerere_autoupdate")
 153
 154static int git_sequencer_config(const char *k, const char *v, void *cb)
 155{
 156        struct replay_opts *opts = cb;
 157        int status;
 158
 159        if (!strcmp(k, "commit.cleanup")) {
 160                const char *s;
 161
 162                status = git_config_string(&s, k, v);
 163                if (status)
 164                        return status;
 165
 166                if (!strcmp(s, "verbatim"))
 167                        opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE;
 168                else if (!strcmp(s, "whitespace"))
 169                        opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SPACE;
 170                else if (!strcmp(s, "strip"))
 171                        opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_ALL;
 172                else if (!strcmp(s, "scissors"))
 173                        opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SPACE;
 174                else
 175                        warning(_("invalid commit message cleanup mode '%s'"),
 176                                  s);
 177
 178                return status;
 179        }
 180
 181        if (!strcmp(k, "commit.gpgsign")) {
 182                opts->gpg_sign = git_config_bool(k, v) ? xstrdup("") : NULL;
 183                return 0;
 184        }
 185
 186        status = git_gpg_config(k, v, NULL);
 187        if (status)
 188                return status;
 189
 190        return git_diff_basic_config(k, v, NULL);
 191}
 192
 193void sequencer_init_config(struct replay_opts *opts)
 194{
 195        opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE;
 196        git_config(git_sequencer_config, opts);
 197}
 198
 199static inline int is_rebase_i(const struct replay_opts *opts)
 200{
 201        return opts->action == REPLAY_INTERACTIVE_REBASE;
 202}
 203
 204static const char *get_dir(const struct replay_opts *opts)
 205{
 206        if (is_rebase_i(opts))
 207                return rebase_path();
 208        return git_path_seq_dir();
 209}
 210
 211static const char *get_todo_path(const struct replay_opts *opts)
 212{
 213        if (is_rebase_i(opts))
 214                return rebase_path_todo();
 215        return git_path_todo_file();
 216}
 217
 218/*
 219 * Returns 0 for non-conforming footer
 220 * Returns 1 for conforming footer
 221 * Returns 2 when sob exists within conforming footer
 222 * Returns 3 when sob exists within conforming footer as last entry
 223 */
 224static int has_conforming_footer(struct strbuf *sb, struct strbuf *sob,
 225        int ignore_footer)
 226{
 227        struct trailer_info info;
 228        int i;
 229        int found_sob = 0, found_sob_last = 0;
 230
 231        trailer_info_get(&info, sb->buf);
 232
 233        if (info.trailer_start == info.trailer_end)
 234                return 0;
 235
 236        for (i = 0; i < info.trailer_nr; i++)
 237                if (sob && !strncmp(info.trailers[i], sob->buf, sob->len)) {
 238                        found_sob = 1;
 239                        if (i == info.trailer_nr - 1)
 240                                found_sob_last = 1;
 241                }
 242
 243        trailer_info_release(&info);
 244
 245        if (found_sob_last)
 246                return 3;
 247        if (found_sob)
 248                return 2;
 249        return 1;
 250}
 251
 252static const char *gpg_sign_opt_quoted(struct replay_opts *opts)
 253{
 254        static struct strbuf buf = STRBUF_INIT;
 255
 256        strbuf_reset(&buf);
 257        if (opts->gpg_sign)
 258                sq_quotef(&buf, "-S%s", opts->gpg_sign);
 259        return buf.buf;
 260}
 261
 262int sequencer_remove_state(struct replay_opts *opts)
 263{
 264        struct strbuf buf = STRBUF_INIT;
 265        int i;
 266
 267        if (is_rebase_i(opts) &&
 268            strbuf_read_file(&buf, rebase_path_refs_to_delete(), 0) > 0) {
 269                char *p = buf.buf;
 270                while (*p) {
 271                        char *eol = strchr(p, '\n');
 272                        if (eol)
 273                                *eol = '\0';
 274                        if (delete_ref("(rebase -i) cleanup", p, NULL, 0) < 0)
 275                                warning(_("could not delete '%s'"), p);
 276                        if (!eol)
 277                                break;
 278                        p = eol + 1;
 279                }
 280        }
 281
 282        free(opts->gpg_sign);
 283        free(opts->strategy);
 284        for (i = 0; i < opts->xopts_nr; i++)
 285                free(opts->xopts[i]);
 286        free(opts->xopts);
 287        strbuf_release(&opts->current_fixups);
 288
 289        strbuf_reset(&buf);
 290        strbuf_addstr(&buf, get_dir(opts));
 291        remove_dir_recursively(&buf, 0);
 292        strbuf_release(&buf);
 293
 294        return 0;
 295}
 296
 297static const char *action_name(const struct replay_opts *opts)
 298{
 299        switch (opts->action) {
 300        case REPLAY_REVERT:
 301                return N_("revert");
 302        case REPLAY_PICK:
 303                return N_("cherry-pick");
 304        case REPLAY_INTERACTIVE_REBASE:
 305                return N_("rebase -i");
 306        }
 307        die(_("Unknown action: %d"), opts->action);
 308}
 309
 310struct commit_message {
 311        char *parent_label;
 312        char *label;
 313        char *subject;
 314        const char *message;
 315};
 316
 317static const char *short_commit_name(struct commit *commit)
 318{
 319        return find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV);
 320}
 321
 322static int get_message(struct commit *commit, struct commit_message *out)
 323{
 324        const char *abbrev, *subject;
 325        int subject_len;
 326
 327        out->message = logmsg_reencode(commit, NULL, get_commit_output_encoding());
 328        abbrev = short_commit_name(commit);
 329
 330        subject_len = find_commit_subject(out->message, &subject);
 331
 332        out->subject = xmemdupz(subject, subject_len);
 333        out->label = xstrfmt("%s... %s", abbrev, out->subject);
 334        out->parent_label = xstrfmt("parent of %s", out->label);
 335
 336        return 0;
 337}
 338
 339static void free_message(struct commit *commit, struct commit_message *msg)
 340{
 341        free(msg->parent_label);
 342        free(msg->label);
 343        free(msg->subject);
 344        unuse_commit_buffer(commit, msg->message);
 345}
 346
 347static void print_advice(int show_hint, struct replay_opts *opts)
 348{
 349        char *msg = getenv("GIT_CHERRY_PICK_HELP");
 350
 351        if (msg) {
 352                fprintf(stderr, "%s\n", msg);
 353                /*
 354                 * A conflict has occurred but the porcelain
 355                 * (typically rebase --interactive) wants to take care
 356                 * of the commit itself so remove CHERRY_PICK_HEAD
 357                 */
 358                unlink(git_path_cherry_pick_head());
 359                return;
 360        }
 361
 362        if (show_hint) {
 363                if (opts->no_commit)
 364                        advise(_("after resolving the conflicts, mark the corrected paths\n"
 365                                 "with 'git add <paths>' or 'git rm <paths>'"));
 366                else
 367                        advise(_("after resolving the conflicts, mark the corrected paths\n"
 368                                 "with 'git add <paths>' or 'git rm <paths>'\n"
 369                                 "and commit the result with 'git commit'"));
 370        }
 371}
 372
 373static int write_message(const void *buf, size_t len, const char *filename,
 374                         int append_eol)
 375{
 376        struct lock_file msg_file = LOCK_INIT;
 377
 378        int msg_fd = hold_lock_file_for_update(&msg_file, filename, 0);
 379        if (msg_fd < 0)
 380                return error_errno(_("could not lock '%s'"), filename);
 381        if (write_in_full(msg_fd, buf, len) < 0) {
 382                error_errno(_("could not write to '%s'"), filename);
 383                rollback_lock_file(&msg_file);
 384                return -1;
 385        }
 386        if (append_eol && write(msg_fd, "\n", 1) < 0) {
 387                error_errno(_("could not write eol to '%s'"), filename);
 388                rollback_lock_file(&msg_file);
 389                return -1;
 390        }
 391        if (commit_lock_file(&msg_file) < 0)
 392                return error(_("failed to finalize '%s'"), filename);
 393
 394        return 0;
 395}
 396
 397/*
 398 * Reads a file that was presumably written by a shell script, i.e. with an
 399 * end-of-line marker that needs to be stripped.
 400 *
 401 * Note that only the last end-of-line marker is stripped, consistent with the
 402 * behavior of "$(cat path)" in a shell script.
 403 *
 404 * Returns 1 if the file was read, 0 if it could not be read or does not exist.
 405 */
 406static int read_oneliner(struct strbuf *buf,
 407        const char *path, int skip_if_empty)
 408{
 409        int orig_len = buf->len;
 410
 411        if (!file_exists(path))
 412                return 0;
 413
 414        if (strbuf_read_file(buf, path, 0) < 0) {
 415                warning_errno(_("could not read '%s'"), path);
 416                return 0;
 417        }
 418
 419        if (buf->len > orig_len && buf->buf[buf->len - 1] == '\n') {
 420                if (--buf->len > orig_len && buf->buf[buf->len - 1] == '\r')
 421                        --buf->len;
 422                buf->buf[buf->len] = '\0';
 423        }
 424
 425        if (skip_if_empty && buf->len == orig_len)
 426                return 0;
 427
 428        return 1;
 429}
 430
 431static struct tree *empty_tree(void)
 432{
 433        return lookup_tree(the_hash_algo->empty_tree);
 434}
 435
 436static int error_dirty_index(struct replay_opts *opts)
 437{
 438        if (read_cache_unmerged())
 439                return error_resolve_conflict(_(action_name(opts)));
 440
 441        error(_("your local changes would be overwritten by %s."),
 442                _(action_name(opts)));
 443
 444        if (advice_commit_before_merge)
 445                advise(_("commit your changes or stash them to proceed."));
 446        return -1;
 447}
 448
 449static void update_abort_safety_file(void)
 450{
 451        struct object_id head;
 452
 453        /* Do nothing on a single-pick */
 454        if (!file_exists(git_path_seq_dir()))
 455                return;
 456
 457        if (!get_oid("HEAD", &head))
 458                write_file(git_path_abort_safety_file(), "%s", oid_to_hex(&head));
 459        else
 460                write_file(git_path_abort_safety_file(), "%s", "");
 461}
 462
 463static int fast_forward_to(const struct object_id *to, const struct object_id *from,
 464                        int unborn, struct replay_opts *opts)
 465{
 466        struct ref_transaction *transaction;
 467        struct strbuf sb = STRBUF_INIT;
 468        struct strbuf err = STRBUF_INIT;
 469
 470        read_cache();
 471        if (checkout_fast_forward(from, to, 1))
 472                return -1; /* the callee should have complained already */
 473
 474        strbuf_addf(&sb, _("%s: fast-forward"), _(action_name(opts)));
 475
 476        transaction = ref_transaction_begin(&err);
 477        if (!transaction ||
 478            ref_transaction_update(transaction, "HEAD",
 479                                   to, unborn && !is_rebase_i(opts) ?
 480                                   &null_oid : from,
 481                                   0, sb.buf, &err) ||
 482            ref_transaction_commit(transaction, &err)) {
 483                ref_transaction_free(transaction);
 484                error("%s", err.buf);
 485                strbuf_release(&sb);
 486                strbuf_release(&err);
 487                return -1;
 488        }
 489
 490        strbuf_release(&sb);
 491        strbuf_release(&err);
 492        ref_transaction_free(transaction);
 493        update_abort_safety_file();
 494        return 0;
 495}
 496
 497void append_conflicts_hint(struct strbuf *msgbuf)
 498{
 499        int i;
 500
 501        strbuf_addch(msgbuf, '\n');
 502        strbuf_commented_addf(msgbuf, "Conflicts:\n");
 503        for (i = 0; i < active_nr;) {
 504                const struct cache_entry *ce = active_cache[i++];
 505                if (ce_stage(ce)) {
 506                        strbuf_commented_addf(msgbuf, "\t%s\n", ce->name);
 507                        while (i < active_nr && !strcmp(ce->name,
 508                                                        active_cache[i]->name))
 509                                i++;
 510                }
 511        }
 512}
 513
 514static int do_recursive_merge(struct commit *base, struct commit *next,
 515                              const char *base_label, const char *next_label,
 516                              struct object_id *head, struct strbuf *msgbuf,
 517                              struct replay_opts *opts)
 518{
 519        struct merge_options o;
 520        struct tree *result, *next_tree, *base_tree, *head_tree;
 521        int clean;
 522        char **xopt;
 523        struct lock_file index_lock = LOCK_INIT;
 524
 525        if (hold_locked_index(&index_lock, LOCK_REPORT_ON_ERROR) < 0)
 526                return -1;
 527
 528        read_cache();
 529
 530        init_merge_options(&o);
 531        o.ancestor = base ? base_label : "(empty tree)";
 532        o.branch1 = "HEAD";
 533        o.branch2 = next ? next_label : "(empty tree)";
 534        if (is_rebase_i(opts))
 535                o.buffer_output = 2;
 536        o.show_rename_progress = 1;
 537
 538        head_tree = parse_tree_indirect(head);
 539        next_tree = next ? get_commit_tree(next) : empty_tree();
 540        base_tree = base ? get_commit_tree(base) : empty_tree();
 541
 542        for (xopt = opts->xopts; xopt != opts->xopts + opts->xopts_nr; xopt++)
 543                parse_merge_opt(&o, *xopt);
 544
 545        clean = merge_trees(&o,
 546                            head_tree,
 547                            next_tree, base_tree, &result);
 548        if (is_rebase_i(opts) && clean <= 0)
 549                fputs(o.obuf.buf, stdout);
 550        strbuf_release(&o.obuf);
 551        diff_warn_rename_limit("merge.renamelimit", o.needed_rename_limit, 0);
 552        if (clean < 0) {
 553                rollback_lock_file(&index_lock);
 554                return clean;
 555        }
 556
 557        if (write_locked_index(&the_index, &index_lock,
 558                               COMMIT_LOCK | SKIP_IF_UNCHANGED))
 559                /*
 560                 * TRANSLATORS: %s will be "revert", "cherry-pick" or
 561                 * "rebase -i".
 562                 */
 563                return error(_("%s: Unable to write new index file"),
 564                        _(action_name(opts)));
 565
 566        if (!clean)
 567                append_conflicts_hint(msgbuf);
 568
 569        return !clean;
 570}
 571
 572static struct object_id *get_cache_tree_oid(void)
 573{
 574        if (!active_cache_tree)
 575                active_cache_tree = cache_tree();
 576
 577        if (!cache_tree_fully_valid(active_cache_tree))
 578                if (cache_tree_update(&the_index, 0)) {
 579                        error(_("unable to update cache tree"));
 580                        return NULL;
 581                }
 582
 583        return &active_cache_tree->oid;
 584}
 585
 586static int is_index_unchanged(void)
 587{
 588        struct object_id head_oid, *cache_tree_oid;
 589        struct commit *head_commit;
 590
 591        if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, &head_oid, NULL))
 592                return error(_("could not resolve HEAD commit"));
 593
 594        head_commit = lookup_commit(&head_oid);
 595
 596        /*
 597         * If head_commit is NULL, check_commit, called from
 598         * lookup_commit, would have indicated that head_commit is not
 599         * a commit object already.  parse_commit() will return failure
 600         * without further complaints in such a case.  Otherwise, if
 601         * the commit is invalid, parse_commit() will complain.  So
 602         * there is nothing for us to say here.  Just return failure.
 603         */
 604        if (parse_commit(head_commit))
 605                return -1;
 606
 607        if (!(cache_tree_oid = get_cache_tree_oid()))
 608                return -1;
 609
 610        return !oidcmp(cache_tree_oid, get_commit_tree_oid(head_commit));
 611}
 612
 613static int write_author_script(const char *message)
 614{
 615        struct strbuf buf = STRBUF_INIT;
 616        const char *eol;
 617        int res;
 618
 619        for (;;)
 620                if (!*message || starts_with(message, "\n")) {
 621missing_author:
 622                        /* Missing 'author' line? */
 623                        unlink(rebase_path_author_script());
 624                        return 0;
 625                } else if (skip_prefix(message, "author ", &message))
 626                        break;
 627                else if ((eol = strchr(message, '\n')))
 628                        message = eol + 1;
 629                else
 630                        goto missing_author;
 631
 632        strbuf_addstr(&buf, "GIT_AUTHOR_NAME='");
 633        while (*message && *message != '\n' && *message != '\r')
 634                if (skip_prefix(message, " <", &message))
 635                        break;
 636                else if (*message != '\'')
 637                        strbuf_addch(&buf, *(message++));
 638                else
 639                        strbuf_addf(&buf, "'\\\\%c'", *(message++));
 640        strbuf_addstr(&buf, "'\nGIT_AUTHOR_EMAIL='");
 641        while (*message && *message != '\n' && *message != '\r')
 642                if (skip_prefix(message, "> ", &message))
 643                        break;
 644                else if (*message != '\'')
 645                        strbuf_addch(&buf, *(message++));
 646                else
 647                        strbuf_addf(&buf, "'\\\\%c'", *(message++));
 648        strbuf_addstr(&buf, "'\nGIT_AUTHOR_DATE='@");
 649        while (*message && *message != '\n' && *message != '\r')
 650                if (*message != '\'')
 651                        strbuf_addch(&buf, *(message++));
 652                else
 653                        strbuf_addf(&buf, "'\\\\%c'", *(message++));
 654        res = write_message(buf.buf, buf.len, rebase_path_author_script(), 1);
 655        strbuf_release(&buf);
 656        return res;
 657}
 658
 659/*
 660 * Read a list of environment variable assignments (such as the author-script
 661 * file) into an environment block. Returns -1 on error, 0 otherwise.
 662 */
 663static int read_env_script(struct argv_array *env)
 664{
 665        struct strbuf script = STRBUF_INIT;
 666        int i, count = 0;
 667        char *p, *p2;
 668
 669        if (strbuf_read_file(&script, rebase_path_author_script(), 256) <= 0)
 670                return -1;
 671
 672        for (p = script.buf; *p; p++)
 673                if (skip_prefix(p, "'\\\\''", (const char **)&p2))
 674                        strbuf_splice(&script, p - script.buf, p2 - p, "'", 1);
 675                else if (*p == '\'')
 676                        strbuf_splice(&script, p-- - script.buf, 1, "", 0);
 677                else if (*p == '\n') {
 678                        *p = '\0';
 679                        count++;
 680                }
 681
 682        for (i = 0, p = script.buf; i < count; i++) {
 683                argv_array_push(env, p);
 684                p += strlen(p) + 1;
 685        }
 686
 687        return 0;
 688}
 689
 690static char *get_author(const char *message)
 691{
 692        size_t len;
 693        const char *a;
 694
 695        a = find_commit_header(message, "author", &len);
 696        if (a)
 697                return xmemdupz(a, len);
 698
 699        return NULL;
 700}
 701
 702/* Read author-script and return an ident line (author <email> timestamp) */
 703static const char *read_author_ident(struct strbuf *buf)
 704{
 705        const char *keys[] = {
 706                "GIT_AUTHOR_NAME=", "GIT_AUTHOR_EMAIL=", "GIT_AUTHOR_DATE="
 707        };
 708        char *in, *out, *eol;
 709        int i = 0, len;
 710
 711        if (strbuf_read_file(buf, rebase_path_author_script(), 256) <= 0)
 712                return NULL;
 713
 714        /* dequote values and construct ident line in-place */
 715        for (in = out = buf->buf; i < 3 && in - buf->buf < buf->len; i++) {
 716                if (!skip_prefix(in, keys[i], (const char **)&in)) {
 717                        warning("could not parse '%s' (looking for '%s'",
 718                                rebase_path_author_script(), keys[i]);
 719                        return NULL;
 720                }
 721
 722                eol = strchrnul(in, '\n');
 723                *eol = '\0';
 724                sq_dequote(in);
 725                len = strlen(in);
 726
 727                if (i > 0) /* separate values by spaces */
 728                        *(out++) = ' ';
 729                if (i == 1) /* email needs to be surrounded by <...> */
 730                        *(out++) = '<';
 731                memmove(out, in, len);
 732                out += len;
 733                if (i == 1) /* email needs to be surrounded by <...> */
 734                        *(out++) = '>';
 735                in = eol + 1;
 736        }
 737
 738        if (i < 3) {
 739                warning("could not parse '%s' (looking for '%s')",
 740                        rebase_path_author_script(), keys[i]);
 741                return NULL;
 742        }
 743
 744        buf->len = out - buf->buf;
 745        return buf->buf;
 746}
 747
 748static const char staged_changes_advice[] =
 749N_("you have staged changes in your working tree\n"
 750"If these changes are meant to be squashed into the previous commit, run:\n"
 751"\n"
 752"  git commit --amend %s\n"
 753"\n"
 754"If they are meant to go into a new commit, run:\n"
 755"\n"
 756"  git commit %s\n"
 757"\n"
 758"In both cases, once you're done, continue with:\n"
 759"\n"
 760"  git rebase --continue\n");
 761
 762#define ALLOW_EMPTY (1<<0)
 763#define EDIT_MSG    (1<<1)
 764#define AMEND_MSG   (1<<2)
 765#define CLEANUP_MSG (1<<3)
 766#define VERIFY_MSG  (1<<4)
 767#define CREATE_ROOT_COMMIT (1<<5)
 768
 769/*
 770 * If we are cherry-pick, and if the merge did not result in
 771 * hand-editing, we will hit this commit and inherit the original
 772 * author date and name.
 773 *
 774 * If we are revert, or if our cherry-pick results in a hand merge,
 775 * we had better say that the current user is responsible for that.
 776 *
 777 * An exception is when run_git_commit() is called during an
 778 * interactive rebase: in that case, we will want to retain the
 779 * author metadata.
 780 */
 781static int run_git_commit(const char *defmsg, struct replay_opts *opts,
 782                          unsigned int flags)
 783{
 784        struct child_process cmd = CHILD_PROCESS_INIT;
 785        const char *value;
 786
 787        if ((flags & CREATE_ROOT_COMMIT) && !(flags & AMEND_MSG)) {
 788                struct strbuf msg = STRBUF_INIT, script = STRBUF_INIT;
 789                const char *author = is_rebase_i(opts) ?
 790                        read_author_ident(&script) : NULL;
 791                struct object_id root_commit, *cache_tree_oid;
 792                int res = 0;
 793
 794                if (!defmsg)
 795                        BUG("root commit without message");
 796
 797                if (!(cache_tree_oid = get_cache_tree_oid()))
 798                        res = -1;
 799
 800                if (!res)
 801                        res = strbuf_read_file(&msg, defmsg, 0);
 802
 803                if (res <= 0)
 804                        res = error_errno(_("could not read '%s'"), defmsg);
 805                else
 806                        res = commit_tree(msg.buf, msg.len, cache_tree_oid,
 807                                          NULL, &root_commit, author,
 808                                          opts->gpg_sign);
 809
 810                strbuf_release(&msg);
 811                strbuf_release(&script);
 812                if (!res) {
 813                        update_ref(NULL, "CHERRY_PICK_HEAD", &root_commit, NULL,
 814                                   REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR);
 815                        res = update_ref(NULL, "HEAD", &root_commit, NULL, 0,
 816                                         UPDATE_REFS_MSG_ON_ERR);
 817                }
 818                return res < 0 ? error(_("writing root commit")) : 0;
 819        }
 820
 821        cmd.git_cmd = 1;
 822
 823        if (is_rebase_i(opts)) {
 824                if (!(flags & EDIT_MSG)) {
 825                        cmd.stdout_to_stderr = 1;
 826                        cmd.err = -1;
 827                }
 828
 829                if (read_env_script(&cmd.env_array)) {
 830                        const char *gpg_opt = gpg_sign_opt_quoted(opts);
 831
 832                        return error(_(staged_changes_advice),
 833                                     gpg_opt, gpg_opt);
 834                }
 835        }
 836
 837        argv_array_push(&cmd.args, "commit");
 838
 839        if (!(flags & VERIFY_MSG))
 840                argv_array_push(&cmd.args, "-n");
 841        if ((flags & AMEND_MSG))
 842                argv_array_push(&cmd.args, "--amend");
 843        if (opts->gpg_sign)
 844                argv_array_pushf(&cmd.args, "-S%s", opts->gpg_sign);
 845        if (defmsg)
 846                argv_array_pushl(&cmd.args, "-F", defmsg, NULL);
 847        else if (!(flags & EDIT_MSG))
 848                argv_array_pushl(&cmd.args, "-C", "HEAD", NULL);
 849        if ((flags & CLEANUP_MSG))
 850                argv_array_push(&cmd.args, "--cleanup=strip");
 851        if ((flags & EDIT_MSG))
 852                argv_array_push(&cmd.args, "-e");
 853        else if (!(flags & CLEANUP_MSG) &&
 854                 !opts->signoff && !opts->record_origin &&
 855                 git_config_get_value("commit.cleanup", &value))
 856                argv_array_push(&cmd.args, "--cleanup=verbatim");
 857
 858        if ((flags & ALLOW_EMPTY))
 859                argv_array_push(&cmd.args, "--allow-empty");
 860
 861        if (opts->allow_empty_message)
 862                argv_array_push(&cmd.args, "--allow-empty-message");
 863
 864        if (cmd.err == -1) {
 865                /* hide stderr on success */
 866                struct strbuf buf = STRBUF_INIT;
 867                int rc = pipe_command(&cmd,
 868                                      NULL, 0,
 869                                      /* stdout is already redirected */
 870                                      NULL, 0,
 871                                      &buf, 0);
 872                if (rc)
 873                        fputs(buf.buf, stderr);
 874                strbuf_release(&buf);
 875                return rc;
 876        }
 877
 878        return run_command(&cmd);
 879}
 880
 881static int rest_is_empty(const struct strbuf *sb, int start)
 882{
 883        int i, eol;
 884        const char *nl;
 885
 886        /* Check if the rest is just whitespace and Signed-off-by's. */
 887        for (i = start; i < sb->len; i++) {
 888                nl = memchr(sb->buf + i, '\n', sb->len - i);
 889                if (nl)
 890                        eol = nl - sb->buf;
 891                else
 892                        eol = sb->len;
 893
 894                if (strlen(sign_off_header) <= eol - i &&
 895                    starts_with(sb->buf + i, sign_off_header)) {
 896                        i = eol;
 897                        continue;
 898                }
 899                while (i < eol)
 900                        if (!isspace(sb->buf[i++]))
 901                                return 0;
 902        }
 903
 904        return 1;
 905}
 906
 907/*
 908 * Find out if the message in the strbuf contains only whitespace and
 909 * Signed-off-by lines.
 910 */
 911int message_is_empty(const struct strbuf *sb,
 912                     enum commit_msg_cleanup_mode cleanup_mode)
 913{
 914        if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
 915                return 0;
 916        return rest_is_empty(sb, 0);
 917}
 918
 919/*
 920 * See if the user edited the message in the editor or left what
 921 * was in the template intact
 922 */
 923int template_untouched(const struct strbuf *sb, const char *template_file,
 924                       enum commit_msg_cleanup_mode cleanup_mode)
 925{
 926        struct strbuf tmpl = STRBUF_INIT;
 927        const char *start;
 928
 929        if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
 930                return 0;
 931
 932        if (!template_file || strbuf_read_file(&tmpl, template_file, 0) <= 0)
 933                return 0;
 934
 935        strbuf_stripspace(&tmpl, cleanup_mode == COMMIT_MSG_CLEANUP_ALL);
 936        if (!skip_prefix(sb->buf, tmpl.buf, &start))
 937                start = sb->buf;
 938        strbuf_release(&tmpl);
 939        return rest_is_empty(sb, start - sb->buf);
 940}
 941
 942int update_head_with_reflog(const struct commit *old_head,
 943                            const struct object_id *new_head,
 944                            const char *action, const struct strbuf *msg,
 945                            struct strbuf *err)
 946{
 947        struct ref_transaction *transaction;
 948        struct strbuf sb = STRBUF_INIT;
 949        const char *nl;
 950        int ret = 0;
 951
 952        if (action) {
 953                strbuf_addstr(&sb, action);
 954                strbuf_addstr(&sb, ": ");
 955        }
 956
 957        nl = strchr(msg->buf, '\n');
 958        if (nl) {
 959                strbuf_add(&sb, msg->buf, nl + 1 - msg->buf);
 960        } else {
 961                strbuf_addbuf(&sb, msg);
 962                strbuf_addch(&sb, '\n');
 963        }
 964
 965        transaction = ref_transaction_begin(err);
 966        if (!transaction ||
 967            ref_transaction_update(transaction, "HEAD", new_head,
 968                                   old_head ? &old_head->object.oid : &null_oid,
 969                                   0, sb.buf, err) ||
 970            ref_transaction_commit(transaction, err)) {
 971                ret = -1;
 972        }
 973        ref_transaction_free(transaction);
 974        strbuf_release(&sb);
 975
 976        return ret;
 977}
 978
 979static int run_rewrite_hook(const struct object_id *oldoid,
 980                            const struct object_id *newoid)
 981{
 982        struct child_process proc = CHILD_PROCESS_INIT;
 983        const char *argv[3];
 984        int code;
 985        struct strbuf sb = STRBUF_INIT;
 986
 987        argv[0] = find_hook("post-rewrite");
 988        if (!argv[0])
 989                return 0;
 990
 991        argv[1] = "amend";
 992        argv[2] = NULL;
 993
 994        proc.argv = argv;
 995        proc.in = -1;
 996        proc.stdout_to_stderr = 1;
 997
 998        code = start_command(&proc);
 999        if (code)
1000                return code;
1001        strbuf_addf(&sb, "%s %s\n", oid_to_hex(oldoid), oid_to_hex(newoid));
1002        sigchain_push(SIGPIPE, SIG_IGN);
1003        write_in_full(proc.in, sb.buf, sb.len);
1004        close(proc.in);
1005        strbuf_release(&sb);
1006        sigchain_pop(SIGPIPE);
1007        return finish_command(&proc);
1008}
1009
1010void commit_post_rewrite(const struct commit *old_head,
1011                         const struct object_id *new_head)
1012{
1013        struct notes_rewrite_cfg *cfg;
1014
1015        cfg = init_copy_notes_for_rewrite("amend");
1016        if (cfg) {
1017                /* we are amending, so old_head is not NULL */
1018                copy_note_for_rewrite(cfg, &old_head->object.oid, new_head);
1019                finish_copy_notes_for_rewrite(cfg, "Notes added by 'git commit --amend'");
1020        }
1021        run_rewrite_hook(&old_head->object.oid, new_head);
1022}
1023
1024static int run_prepare_commit_msg_hook(struct strbuf *msg, const char *commit)
1025{
1026        struct argv_array hook_env = ARGV_ARRAY_INIT;
1027        int ret;
1028        const char *name;
1029
1030        name = git_path_commit_editmsg();
1031        if (write_message(msg->buf, msg->len, name, 0))
1032                return -1;
1033
1034        argv_array_pushf(&hook_env, "GIT_INDEX_FILE=%s", get_index_file());
1035        argv_array_push(&hook_env, "GIT_EDITOR=:");
1036        if (commit)
1037                ret = run_hook_le(hook_env.argv, "prepare-commit-msg", name,
1038                                  "commit", commit, NULL);
1039        else
1040                ret = run_hook_le(hook_env.argv, "prepare-commit-msg", name,
1041                                  "message", NULL);
1042        if (ret)
1043                ret = error(_("'prepare-commit-msg' hook failed"));
1044        argv_array_clear(&hook_env);
1045
1046        return ret;
1047}
1048
1049static const char implicit_ident_advice_noconfig[] =
1050N_("Your name and email address were configured automatically based\n"
1051"on your username and hostname. Please check that they are accurate.\n"
1052"You can suppress this message by setting them explicitly. Run the\n"
1053"following command and follow the instructions in your editor to edit\n"
1054"your configuration file:\n"
1055"\n"
1056"    git config --global --edit\n"
1057"\n"
1058"After doing this, you may fix the identity used for this commit with:\n"
1059"\n"
1060"    git commit --amend --reset-author\n");
1061
1062static const char implicit_ident_advice_config[] =
1063N_("Your name and email address were configured automatically based\n"
1064"on your username and hostname. Please check that they are accurate.\n"
1065"You can suppress this message by setting them explicitly:\n"
1066"\n"
1067"    git config --global user.name \"Your Name\"\n"
1068"    git config --global user.email you@example.com\n"
1069"\n"
1070"After doing this, you may fix the identity used for this commit with:\n"
1071"\n"
1072"    git commit --amend --reset-author\n");
1073
1074static const char *implicit_ident_advice(void)
1075{
1076        char *user_config = expand_user_path("~/.gitconfig", 0);
1077        char *xdg_config = xdg_config_home("config");
1078        int config_exists = file_exists(user_config) || file_exists(xdg_config);
1079
1080        free(user_config);
1081        free(xdg_config);
1082
1083        if (config_exists)
1084                return _(implicit_ident_advice_config);
1085        else
1086                return _(implicit_ident_advice_noconfig);
1087
1088}
1089
1090void print_commit_summary(const char *prefix, const struct object_id *oid,
1091                          unsigned int flags)
1092{
1093        struct rev_info rev;
1094        struct commit *commit;
1095        struct strbuf format = STRBUF_INIT;
1096        const char *head;
1097        struct pretty_print_context pctx = {0};
1098        struct strbuf author_ident = STRBUF_INIT;
1099        struct strbuf committer_ident = STRBUF_INIT;
1100
1101        commit = lookup_commit(oid);
1102        if (!commit)
1103                die(_("couldn't look up newly created commit"));
1104        if (parse_commit(commit))
1105                die(_("could not parse newly created commit"));
1106
1107        strbuf_addstr(&format, "format:%h] %s");
1108
1109        format_commit_message(commit, "%an <%ae>", &author_ident, &pctx);
1110        format_commit_message(commit, "%cn <%ce>", &committer_ident, &pctx);
1111        if (strbuf_cmp(&author_ident, &committer_ident)) {
1112                strbuf_addstr(&format, "\n Author: ");
1113                strbuf_addbuf_percentquote(&format, &author_ident);
1114        }
1115        if (flags & SUMMARY_SHOW_AUTHOR_DATE) {
1116                struct strbuf date = STRBUF_INIT;
1117
1118                format_commit_message(commit, "%ad", &date, &pctx);
1119                strbuf_addstr(&format, "\n Date: ");
1120                strbuf_addbuf_percentquote(&format, &date);
1121                strbuf_release(&date);
1122        }
1123        if (!committer_ident_sufficiently_given()) {
1124                strbuf_addstr(&format, "\n Committer: ");
1125                strbuf_addbuf_percentquote(&format, &committer_ident);
1126                if (advice_implicit_identity) {
1127                        strbuf_addch(&format, '\n');
1128                        strbuf_addstr(&format, implicit_ident_advice());
1129                }
1130        }
1131        strbuf_release(&author_ident);
1132        strbuf_release(&committer_ident);
1133
1134        init_revisions(&rev, prefix);
1135        setup_revisions(0, NULL, &rev, NULL);
1136
1137        rev.diff = 1;
1138        rev.diffopt.output_format =
1139                DIFF_FORMAT_SHORTSTAT | DIFF_FORMAT_SUMMARY;
1140
1141        rev.verbose_header = 1;
1142        rev.show_root_diff = 1;
1143        get_commit_format(format.buf, &rev);
1144        rev.always_show_header = 0;
1145        rev.diffopt.detect_rename = DIFF_DETECT_RENAME;
1146        rev.diffopt.break_opt = 0;
1147        diff_setup_done(&rev.diffopt);
1148
1149        head = resolve_ref_unsafe("HEAD", 0, NULL, NULL);
1150        if (!head)
1151                die_errno(_("unable to resolve HEAD after creating commit"));
1152        if (!strcmp(head, "HEAD"))
1153                head = _("detached HEAD");
1154        else
1155                skip_prefix(head, "refs/heads/", &head);
1156        printf("[%s%s ", head, (flags & SUMMARY_INITIAL_COMMIT) ?
1157                                                _(" (root-commit)") : "");
1158
1159        if (!log_tree_commit(&rev, commit)) {
1160                rev.always_show_header = 1;
1161                rev.use_terminator = 1;
1162                log_tree_commit(&rev, commit);
1163        }
1164
1165        strbuf_release(&format);
1166}
1167
1168static int parse_head(struct commit **head)
1169{
1170        struct commit *current_head;
1171        struct object_id oid;
1172
1173        if (get_oid("HEAD", &oid)) {
1174                current_head = NULL;
1175        } else {
1176                current_head = lookup_commit_reference(&oid);
1177                if (!current_head)
1178                        return error(_("could not parse HEAD"));
1179                if (oidcmp(&oid, &current_head->object.oid)) {
1180                        warning(_("HEAD %s is not a commit!"),
1181                                oid_to_hex(&oid));
1182                }
1183                if (parse_commit(current_head))
1184                        return error(_("could not parse HEAD commit"));
1185        }
1186        *head = current_head;
1187
1188        return 0;
1189}
1190
1191/*
1192 * Try to commit without forking 'git commit'. In some cases we need
1193 * to run 'git commit' to display an error message
1194 *
1195 * Returns:
1196 *  -1 - error unable to commit
1197 *   0 - success
1198 *   1 - run 'git commit'
1199 */
1200static int try_to_commit(struct strbuf *msg, const char *author,
1201                         struct replay_opts *opts, unsigned int flags,
1202                         struct object_id *oid)
1203{
1204        struct object_id tree;
1205        struct commit *current_head;
1206        struct commit_list *parents = NULL;
1207        struct commit_extra_header *extra = NULL;
1208        struct strbuf err = STRBUF_INIT;
1209        struct strbuf commit_msg = STRBUF_INIT;
1210        char *amend_author = NULL;
1211        const char *hook_commit = NULL;
1212        enum commit_msg_cleanup_mode cleanup;
1213        int res = 0;
1214
1215        if (parse_head(&current_head))
1216                return -1;
1217
1218        if (flags & AMEND_MSG) {
1219                const char *exclude_gpgsig[] = { "gpgsig", NULL };
1220                const char *out_enc = get_commit_output_encoding();
1221                const char *message = logmsg_reencode(current_head, NULL,
1222                                                      out_enc);
1223
1224                if (!msg) {
1225                        const char *orig_message = NULL;
1226
1227                        find_commit_subject(message, &orig_message);
1228                        msg = &commit_msg;
1229                        strbuf_addstr(msg, orig_message);
1230                        hook_commit = "HEAD";
1231                }
1232                author = amend_author = get_author(message);
1233                unuse_commit_buffer(current_head, message);
1234                if (!author) {
1235                        res = error(_("unable to parse commit author"));
1236                        goto out;
1237                }
1238                parents = copy_commit_list(current_head->parents);
1239                extra = read_commit_extra_headers(current_head, exclude_gpgsig);
1240        } else if (current_head) {
1241                commit_list_insert(current_head, &parents);
1242        }
1243
1244        if (write_cache_as_tree(&tree, 0, NULL)) {
1245                res = error(_("git write-tree failed to write a tree"));
1246                goto out;
1247        }
1248
1249        if (!(flags & ALLOW_EMPTY) && !oidcmp(current_head ?
1250                                              get_commit_tree_oid(current_head) :
1251                                              the_hash_algo->empty_tree, &tree)) {
1252                res = 1; /* run 'git commit' to display error message */
1253                goto out;
1254        }
1255
1256        if (find_hook("prepare-commit-msg")) {
1257                res = run_prepare_commit_msg_hook(msg, hook_commit);
1258                if (res)
1259                        goto out;
1260                if (strbuf_read_file(&commit_msg, git_path_commit_editmsg(),
1261                                     2048) < 0) {
1262                        res = error_errno(_("unable to read commit message "
1263                                              "from '%s'"),
1264                                            git_path_commit_editmsg());
1265                        goto out;
1266                }
1267                msg = &commit_msg;
1268        }
1269
1270        cleanup = (flags & CLEANUP_MSG) ? COMMIT_MSG_CLEANUP_ALL :
1271                                          opts->default_msg_cleanup;
1272
1273        if (cleanup != COMMIT_MSG_CLEANUP_NONE)
1274                strbuf_stripspace(msg, cleanup == COMMIT_MSG_CLEANUP_ALL);
1275        if (!opts->allow_empty_message && message_is_empty(msg, cleanup)) {
1276                res = 1; /* run 'git commit' to display error message */
1277                goto out;
1278        }
1279
1280        reset_ident_date();
1281
1282        if (commit_tree_extended(msg->buf, msg->len, &tree, parents,
1283                                 oid, author, opts->gpg_sign, extra)) {
1284                res = error(_("failed to write commit object"));
1285                goto out;
1286        }
1287
1288        if (update_head_with_reflog(current_head, oid,
1289                                    getenv("GIT_REFLOG_ACTION"), msg, &err)) {
1290                res = error("%s", err.buf);
1291                goto out;
1292        }
1293
1294        if (flags & AMEND_MSG)
1295                commit_post_rewrite(current_head, oid);
1296
1297out:
1298        free_commit_extra_headers(extra);
1299        strbuf_release(&err);
1300        strbuf_release(&commit_msg);
1301        free(amend_author);
1302
1303        return res;
1304}
1305
1306static int do_commit(const char *msg_file, const char *author,
1307                     struct replay_opts *opts, unsigned int flags)
1308{
1309        int res = 1;
1310
1311        if (!(flags & EDIT_MSG) && !(flags & VERIFY_MSG) &&
1312            !(flags & CREATE_ROOT_COMMIT)) {
1313                struct object_id oid;
1314                struct strbuf sb = STRBUF_INIT;
1315
1316                if (msg_file && strbuf_read_file(&sb, msg_file, 2048) < 0)
1317                        return error_errno(_("unable to read commit message "
1318                                             "from '%s'"),
1319                                           msg_file);
1320
1321                res = try_to_commit(msg_file ? &sb : NULL, author, opts, flags,
1322                                    &oid);
1323                strbuf_release(&sb);
1324                if (!res) {
1325                        unlink(git_path_cherry_pick_head());
1326                        unlink(git_path_merge_msg());
1327                        if (!is_rebase_i(opts))
1328                                print_commit_summary(NULL, &oid,
1329                                                SUMMARY_SHOW_AUTHOR_DATE);
1330                        return res;
1331                }
1332        }
1333        if (res == 1)
1334                return run_git_commit(msg_file, opts, flags);
1335
1336        return res;
1337}
1338
1339static int is_original_commit_empty(struct commit *commit)
1340{
1341        const struct object_id *ptree_oid;
1342
1343        if (parse_commit(commit))
1344                return error(_("could not parse commit %s"),
1345                             oid_to_hex(&commit->object.oid));
1346        if (commit->parents) {
1347                struct commit *parent = commit->parents->item;
1348                if (parse_commit(parent))
1349                        return error(_("could not parse parent commit %s"),
1350                                oid_to_hex(&parent->object.oid));
1351                ptree_oid = get_commit_tree_oid(parent);
1352        } else {
1353                ptree_oid = the_hash_algo->empty_tree; /* commit is root */
1354        }
1355
1356        return !oidcmp(ptree_oid, get_commit_tree_oid(commit));
1357}
1358
1359/*
1360 * Do we run "git commit" with "--allow-empty"?
1361 */
1362static int allow_empty(struct replay_opts *opts, struct commit *commit)
1363{
1364        int index_unchanged, empty_commit;
1365
1366        /*
1367         * Three cases:
1368         *
1369         * (1) we do not allow empty at all and error out.
1370         *
1371         * (2) we allow ones that were initially empty, but
1372         * forbid the ones that become empty;
1373         *
1374         * (3) we allow both.
1375         */
1376        if (!opts->allow_empty)
1377                return 0; /* let "git commit" barf as necessary */
1378
1379        index_unchanged = is_index_unchanged();
1380        if (index_unchanged < 0)
1381                return index_unchanged;
1382        if (!index_unchanged)
1383                return 0; /* we do not have to say --allow-empty */
1384
1385        if (opts->keep_redundant_commits)
1386                return 1;
1387
1388        empty_commit = is_original_commit_empty(commit);
1389        if (empty_commit < 0)
1390                return empty_commit;
1391        if (!empty_commit)
1392                return 0;
1393        else
1394                return 1;
1395}
1396
1397/*
1398 * Note that ordering matters in this enum. Not only must it match the mapping
1399 * below, it is also divided into several sections that matter.  When adding
1400 * new commands, make sure you add it in the right section.
1401 */
1402enum todo_command {
1403        /* commands that handle commits */
1404        TODO_PICK = 0,
1405        TODO_REVERT,
1406        TODO_EDIT,
1407        TODO_REWORD,
1408        TODO_FIXUP,
1409        TODO_SQUASH,
1410        /* commands that do something else than handling a single commit */
1411        TODO_EXEC,
1412        TODO_LABEL,
1413        TODO_RESET,
1414        TODO_MERGE,
1415        /* commands that do nothing but are counted for reporting progress */
1416        TODO_NOOP,
1417        TODO_DROP,
1418        /* comments (not counted for reporting progress) */
1419        TODO_COMMENT
1420};
1421
1422static struct {
1423        char c;
1424        const char *str;
1425} todo_command_info[] = {
1426        { 'p', "pick" },
1427        { 0,   "revert" },
1428        { 'e', "edit" },
1429        { 'r', "reword" },
1430        { 'f', "fixup" },
1431        { 's', "squash" },
1432        { 'x', "exec" },
1433        { 'l', "label" },
1434        { 't', "reset" },
1435        { 'm', "merge" },
1436        { 0,   "noop" },
1437        { 'd', "drop" },
1438        { 0,   NULL }
1439};
1440
1441static const char *command_to_string(const enum todo_command command)
1442{
1443        if (command < TODO_COMMENT)
1444                return todo_command_info[command].str;
1445        die("Unknown command: %d", command);
1446}
1447
1448static char command_to_char(const enum todo_command command)
1449{
1450        if (command < TODO_COMMENT && todo_command_info[command].c)
1451                return todo_command_info[command].c;
1452        return comment_line_char;
1453}
1454
1455static int is_noop(const enum todo_command command)
1456{
1457        return TODO_NOOP <= command;
1458}
1459
1460static int is_fixup(enum todo_command command)
1461{
1462        return command == TODO_FIXUP || command == TODO_SQUASH;
1463}
1464
1465/* Does this command create a (non-merge) commit? */
1466static int is_pick_or_similar(enum todo_command command)
1467{
1468        switch (command) {
1469        case TODO_PICK:
1470        case TODO_REVERT:
1471        case TODO_EDIT:
1472        case TODO_REWORD:
1473        case TODO_FIXUP:
1474        case TODO_SQUASH:
1475                return 1;
1476        default:
1477                return 0;
1478        }
1479}
1480
1481static int update_squash_messages(enum todo_command command,
1482                struct commit *commit, struct replay_opts *opts)
1483{
1484        struct strbuf buf = STRBUF_INIT;
1485        int res;
1486        const char *message, *body;
1487
1488        if (opts->current_fixup_count > 0) {
1489                struct strbuf header = STRBUF_INIT;
1490                char *eol;
1491
1492                if (strbuf_read_file(&buf, rebase_path_squash_msg(), 9) <= 0)
1493                        return error(_("could not read '%s'"),
1494                                rebase_path_squash_msg());
1495
1496                eol = buf.buf[0] != comment_line_char ?
1497                        buf.buf : strchrnul(buf.buf, '\n');
1498
1499                strbuf_addf(&header, "%c ", comment_line_char);
1500                strbuf_addf(&header, _("This is a combination of %d commits."),
1501                            opts->current_fixup_count + 2);
1502                strbuf_splice(&buf, 0, eol - buf.buf, header.buf, header.len);
1503                strbuf_release(&header);
1504        } else {
1505                struct object_id head;
1506                struct commit *head_commit;
1507                const char *head_message, *body;
1508
1509                if (get_oid("HEAD", &head))
1510                        return error(_("need a HEAD to fixup"));
1511                if (!(head_commit = lookup_commit_reference(&head)))
1512                        return error(_("could not read HEAD"));
1513                if (!(head_message = get_commit_buffer(head_commit, NULL)))
1514                        return error(_("could not read HEAD's commit message"));
1515
1516                find_commit_subject(head_message, &body);
1517                if (write_message(body, strlen(body),
1518                                  rebase_path_fixup_msg(), 0)) {
1519                        unuse_commit_buffer(head_commit, head_message);
1520                        return error(_("cannot write '%s'"),
1521                                     rebase_path_fixup_msg());
1522                }
1523
1524                strbuf_addf(&buf, "%c ", comment_line_char);
1525                strbuf_addf(&buf, _("This is a combination of %d commits."), 2);
1526                strbuf_addf(&buf, "\n%c ", comment_line_char);
1527                strbuf_addstr(&buf, _("This is the 1st commit message:"));
1528                strbuf_addstr(&buf, "\n\n");
1529                strbuf_addstr(&buf, body);
1530
1531                unuse_commit_buffer(head_commit, head_message);
1532        }
1533
1534        if (!(message = get_commit_buffer(commit, NULL)))
1535                return error(_("could not read commit message of %s"),
1536                             oid_to_hex(&commit->object.oid));
1537        find_commit_subject(message, &body);
1538
1539        if (command == TODO_SQUASH) {
1540                unlink(rebase_path_fixup_msg());
1541                strbuf_addf(&buf, "\n%c ", comment_line_char);
1542                strbuf_addf(&buf, _("This is the commit message #%d:"),
1543                            ++opts->current_fixup_count);
1544                strbuf_addstr(&buf, "\n\n");
1545                strbuf_addstr(&buf, body);
1546        } else if (command == TODO_FIXUP) {
1547                strbuf_addf(&buf, "\n%c ", comment_line_char);
1548                strbuf_addf(&buf, _("The commit message #%d will be skipped:"),
1549                            ++opts->current_fixup_count);
1550                strbuf_addstr(&buf, "\n\n");
1551                strbuf_add_commented_lines(&buf, body, strlen(body));
1552        } else
1553                return error(_("unknown command: %d"), command);
1554        unuse_commit_buffer(commit, message);
1555
1556        res = write_message(buf.buf, buf.len, rebase_path_squash_msg(), 0);
1557        strbuf_release(&buf);
1558
1559        if (!res) {
1560                strbuf_addf(&opts->current_fixups, "%s%s %s",
1561                            opts->current_fixups.len ? "\n" : "",
1562                            command_to_string(command),
1563                            oid_to_hex(&commit->object.oid));
1564                res = write_message(opts->current_fixups.buf,
1565                                    opts->current_fixups.len,
1566                                    rebase_path_current_fixups(), 0);
1567        }
1568
1569        return res;
1570}
1571
1572static void flush_rewritten_pending(void) {
1573        struct strbuf buf = STRBUF_INIT;
1574        struct object_id newoid;
1575        FILE *out;
1576
1577        if (strbuf_read_file(&buf, rebase_path_rewritten_pending(), (GIT_MAX_HEXSZ + 1) * 2) > 0 &&
1578            !get_oid("HEAD", &newoid) &&
1579            (out = fopen_or_warn(rebase_path_rewritten_list(), "a"))) {
1580                char *bol = buf.buf, *eol;
1581
1582                while (*bol) {
1583                        eol = strchrnul(bol, '\n');
1584                        fprintf(out, "%.*s %s\n", (int)(eol - bol),
1585                                        bol, oid_to_hex(&newoid));
1586                        if (!*eol)
1587                                break;
1588                        bol = eol + 1;
1589                }
1590                fclose(out);
1591                unlink(rebase_path_rewritten_pending());
1592        }
1593        strbuf_release(&buf);
1594}
1595
1596static void record_in_rewritten(struct object_id *oid,
1597                enum todo_command next_command) {
1598        FILE *out = fopen_or_warn(rebase_path_rewritten_pending(), "a");
1599
1600        if (!out)
1601                return;
1602
1603        fprintf(out, "%s\n", oid_to_hex(oid));
1604        fclose(out);
1605
1606        if (!is_fixup(next_command))
1607                flush_rewritten_pending();
1608}
1609
1610static int do_pick_commit(enum todo_command command, struct commit *commit,
1611                struct replay_opts *opts, int final_fixup)
1612{
1613        unsigned int flags = opts->edit ? EDIT_MSG : 0;
1614        const char *msg_file = opts->edit ? NULL : git_path_merge_msg();
1615        struct object_id head;
1616        struct commit *base, *next, *parent;
1617        const char *base_label, *next_label;
1618        char *author = NULL;
1619        struct commit_message msg = { NULL, NULL, NULL, NULL };
1620        struct strbuf msgbuf = STRBUF_INIT;
1621        int res, unborn = 0, allow;
1622
1623        if (opts->no_commit) {
1624                /*
1625                 * We do not intend to commit immediately.  We just want to
1626                 * merge the differences in, so let's compute the tree
1627                 * that represents the "current" state for merge-recursive
1628                 * to work on.
1629                 */
1630                if (write_cache_as_tree(&head, 0, NULL))
1631                        return error(_("your index file is unmerged."));
1632        } else {
1633                unborn = get_oid("HEAD", &head);
1634                /* Do we want to generate a root commit? */
1635                if (is_pick_or_similar(command) && opts->have_squash_onto &&
1636                    !oidcmp(&head, &opts->squash_onto)) {
1637                        if (is_fixup(command))
1638                                return error(_("cannot fixup root commit"));
1639                        flags |= CREATE_ROOT_COMMIT;
1640                        unborn = 1;
1641                } else if (unborn)
1642                        oidcpy(&head, the_hash_algo->empty_tree);
1643                if (index_differs_from(unborn ? empty_tree_oid_hex() : "HEAD",
1644                                       NULL, 0))
1645                        return error_dirty_index(opts);
1646        }
1647        discard_cache();
1648
1649        if (!commit->parents)
1650                parent = NULL;
1651        else if (commit->parents->next) {
1652                /* Reverting or cherry-picking a merge commit */
1653                int cnt;
1654                struct commit_list *p;
1655
1656                if (!opts->mainline)
1657                        return error(_("commit %s is a merge but no -m option was given."),
1658                                oid_to_hex(&commit->object.oid));
1659
1660                for (cnt = 1, p = commit->parents;
1661                     cnt != opts->mainline && p;
1662                     cnt++)
1663                        p = p->next;
1664                if (cnt != opts->mainline || !p)
1665                        return error(_("commit %s does not have parent %d"),
1666                                oid_to_hex(&commit->object.oid), opts->mainline);
1667                parent = p->item;
1668        } else if (0 < opts->mainline)
1669                return error(_("mainline was specified but commit %s is not a merge."),
1670                        oid_to_hex(&commit->object.oid));
1671        else
1672                parent = commit->parents->item;
1673
1674        if (get_message(commit, &msg) != 0)
1675                return error(_("cannot get commit message for %s"),
1676                        oid_to_hex(&commit->object.oid));
1677
1678        if (opts->allow_ff && !is_fixup(command) &&
1679            ((parent && !oidcmp(&parent->object.oid, &head)) ||
1680             (!parent && unborn))) {
1681                if (is_rebase_i(opts))
1682                        write_author_script(msg.message);
1683                res = fast_forward_to(&commit->object.oid, &head, unborn,
1684                        opts);
1685                if (res || command != TODO_REWORD)
1686                        goto leave;
1687                flags |= EDIT_MSG | AMEND_MSG | VERIFY_MSG;
1688                msg_file = NULL;
1689                goto fast_forward_edit;
1690        }
1691        if (parent && parse_commit(parent) < 0)
1692                /* TRANSLATORS: The first %s will be a "todo" command like
1693                   "revert" or "pick", the second %s a SHA1. */
1694                return error(_("%s: cannot parse parent commit %s"),
1695                        command_to_string(command),
1696                        oid_to_hex(&parent->object.oid));
1697
1698        /*
1699         * "commit" is an existing commit.  We would want to apply
1700         * the difference it introduces since its first parent "prev"
1701         * on top of the current HEAD if we are cherry-pick.  Or the
1702         * reverse of it if we are revert.
1703         */
1704
1705        if (command == TODO_REVERT) {
1706                base = commit;
1707                base_label = msg.label;
1708                next = parent;
1709                next_label = msg.parent_label;
1710                strbuf_addstr(&msgbuf, "Revert \"");
1711                strbuf_addstr(&msgbuf, msg.subject);
1712                strbuf_addstr(&msgbuf, "\"\n\nThis reverts commit ");
1713                strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
1714
1715                if (commit->parents && commit->parents->next) {
1716                        strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
1717                        strbuf_addstr(&msgbuf, oid_to_hex(&parent->object.oid));
1718                }
1719                strbuf_addstr(&msgbuf, ".\n");
1720        } else {
1721                const char *p;
1722
1723                base = parent;
1724                base_label = msg.parent_label;
1725                next = commit;
1726                next_label = msg.label;
1727
1728                /* Append the commit log message to msgbuf. */
1729                if (find_commit_subject(msg.message, &p))
1730                        strbuf_addstr(&msgbuf, p);
1731
1732                if (opts->record_origin) {
1733                        strbuf_complete_line(&msgbuf);
1734                        if (!has_conforming_footer(&msgbuf, NULL, 0))
1735                                strbuf_addch(&msgbuf, '\n');
1736                        strbuf_addstr(&msgbuf, cherry_picked_prefix);
1737                        strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
1738                        strbuf_addstr(&msgbuf, ")\n");
1739                }
1740                if (!is_fixup(command))
1741                        author = get_author(msg.message);
1742        }
1743
1744        if (command == TODO_REWORD)
1745                flags |= EDIT_MSG | VERIFY_MSG;
1746        else if (is_fixup(command)) {
1747                if (update_squash_messages(command, commit, opts))
1748                        return -1;
1749                flags |= AMEND_MSG;
1750                if (!final_fixup)
1751                        msg_file = rebase_path_squash_msg();
1752                else if (file_exists(rebase_path_fixup_msg())) {
1753                        flags |= CLEANUP_MSG;
1754                        msg_file = rebase_path_fixup_msg();
1755                } else {
1756                        const char *dest = git_path_squash_msg();
1757                        unlink(dest);
1758                        if (copy_file(dest, rebase_path_squash_msg(), 0666))
1759                                return error(_("could not rename '%s' to '%s'"),
1760                                             rebase_path_squash_msg(), dest);
1761                        unlink(git_path_merge_msg());
1762                        msg_file = dest;
1763                        flags |= EDIT_MSG;
1764                }
1765        }
1766
1767        if (opts->signoff && !is_fixup(command))
1768                append_signoff(&msgbuf, 0, 0);
1769
1770        if (is_rebase_i(opts) && write_author_script(msg.message) < 0)
1771                res = -1;
1772        else if (!opts->strategy || !strcmp(opts->strategy, "recursive") || command == TODO_REVERT) {
1773                res = do_recursive_merge(base, next, base_label, next_label,
1774                                         &head, &msgbuf, opts);
1775                if (res < 0)
1776                        return res;
1777                res |= write_message(msgbuf.buf, msgbuf.len,
1778                                     git_path_merge_msg(), 0);
1779        } else {
1780                struct commit_list *common = NULL;
1781                struct commit_list *remotes = NULL;
1782
1783                res = write_message(msgbuf.buf, msgbuf.len,
1784                                    git_path_merge_msg(), 0);
1785
1786                commit_list_insert(base, &common);
1787                commit_list_insert(next, &remotes);
1788                res |= try_merge_command(opts->strategy,
1789                                         opts->xopts_nr, (const char **)opts->xopts,
1790                                        common, oid_to_hex(&head), remotes);
1791                free_commit_list(common);
1792                free_commit_list(remotes);
1793        }
1794        strbuf_release(&msgbuf);
1795
1796        /*
1797         * If the merge was clean or if it failed due to conflict, we write
1798         * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
1799         * However, if the merge did not even start, then we don't want to
1800         * write it at all.
1801         */
1802        if (command == TODO_PICK && !opts->no_commit && (res == 0 || res == 1) &&
1803            update_ref(NULL, "CHERRY_PICK_HEAD", &commit->object.oid, NULL,
1804                       REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
1805                res = -1;
1806        if (command == TODO_REVERT && ((opts->no_commit && res == 0) || res == 1) &&
1807            update_ref(NULL, "REVERT_HEAD", &commit->object.oid, NULL,
1808                       REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
1809                res = -1;
1810
1811        if (res) {
1812                error(command == TODO_REVERT
1813                      ? _("could not revert %s... %s")
1814                      : _("could not apply %s... %s"),
1815                      short_commit_name(commit), msg.subject);
1816                print_advice(res == 1, opts);
1817                rerere(opts->allow_rerere_auto);
1818                goto leave;
1819        }
1820
1821        allow = allow_empty(opts, commit);
1822        if (allow < 0) {
1823                res = allow;
1824                goto leave;
1825        } else if (allow)
1826                flags |= ALLOW_EMPTY;
1827        if (!opts->no_commit) {
1828fast_forward_edit:
1829                if (author || command == TODO_REVERT || (flags & AMEND_MSG))
1830                        res = do_commit(msg_file, author, opts, flags);
1831                else
1832                        res = error(_("unable to parse commit author"));
1833        }
1834
1835        if (!res && final_fixup) {
1836                unlink(rebase_path_fixup_msg());
1837                unlink(rebase_path_squash_msg());
1838                unlink(rebase_path_current_fixups());
1839                strbuf_reset(&opts->current_fixups);
1840                opts->current_fixup_count = 0;
1841        }
1842
1843leave:
1844        free_message(commit, &msg);
1845        free(author);
1846        update_abort_safety_file();
1847
1848        return res;
1849}
1850
1851static int prepare_revs(struct replay_opts *opts)
1852{
1853        /*
1854         * picking (but not reverting) ranges (but not individual revisions)
1855         * should be done in reverse
1856         */
1857        if (opts->action == REPLAY_PICK && !opts->revs->no_walk)
1858                opts->revs->reverse ^= 1;
1859
1860        if (prepare_revision_walk(opts->revs))
1861                return error(_("revision walk setup failed"));
1862
1863        if (!opts->revs->commits)
1864                return error(_("empty commit set passed"));
1865        return 0;
1866}
1867
1868static int read_and_refresh_cache(struct replay_opts *opts)
1869{
1870        struct lock_file index_lock = LOCK_INIT;
1871        int index_fd = hold_locked_index(&index_lock, 0);
1872        if (read_index_preload(&the_index, NULL) < 0) {
1873                rollback_lock_file(&index_lock);
1874                return error(_("git %s: failed to read the index"),
1875                        _(action_name(opts)));
1876        }
1877        refresh_index(&the_index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
1878        if (index_fd >= 0) {
1879                if (write_locked_index(&the_index, &index_lock,
1880                                       COMMIT_LOCK | SKIP_IF_UNCHANGED)) {
1881                        return error(_("git %s: failed to refresh the index"),
1882                                _(action_name(opts)));
1883                }
1884        }
1885        return 0;
1886}
1887
1888enum todo_item_flags {
1889        TODO_EDIT_MERGE_MSG = 1
1890};
1891
1892struct todo_item {
1893        enum todo_command command;
1894        struct commit *commit;
1895        unsigned int flags;
1896        const char *arg;
1897        int arg_len;
1898        size_t offset_in_buf;
1899};
1900
1901struct todo_list {
1902        struct strbuf buf;
1903        struct todo_item *items;
1904        int nr, alloc, current;
1905        int done_nr, total_nr;
1906        struct stat_data stat;
1907};
1908
1909#define TODO_LIST_INIT { STRBUF_INIT }
1910
1911static void todo_list_release(struct todo_list *todo_list)
1912{
1913        strbuf_release(&todo_list->buf);
1914        FREE_AND_NULL(todo_list->items);
1915        todo_list->nr = todo_list->alloc = 0;
1916}
1917
1918static struct todo_item *append_new_todo(struct todo_list *todo_list)
1919{
1920        ALLOC_GROW(todo_list->items, todo_list->nr + 1, todo_list->alloc);
1921        return todo_list->items + todo_list->nr++;
1922}
1923
1924static int parse_insn_line(struct todo_item *item, const char *bol, char *eol)
1925{
1926        struct object_id commit_oid;
1927        char *end_of_object_name;
1928        int i, saved, status, padding;
1929
1930        item->flags = 0;
1931
1932        /* left-trim */
1933        bol += strspn(bol, " \t");
1934
1935        if (bol == eol || *bol == '\r' || *bol == comment_line_char) {
1936                item->command = TODO_COMMENT;
1937                item->commit = NULL;
1938                item->arg = bol;
1939                item->arg_len = eol - bol;
1940                return 0;
1941        }
1942
1943        for (i = 0; i < TODO_COMMENT; i++)
1944                if (skip_prefix(bol, todo_command_info[i].str, &bol)) {
1945                        item->command = i;
1946                        break;
1947                } else if (bol[1] == ' ' && *bol == todo_command_info[i].c) {
1948                        bol++;
1949                        item->command = i;
1950                        break;
1951                }
1952        if (i >= TODO_COMMENT)
1953                return -1;
1954
1955        /* Eat up extra spaces/ tabs before object name */
1956        padding = strspn(bol, " \t");
1957        bol += padding;
1958
1959        if (item->command == TODO_NOOP) {
1960                if (bol != eol)
1961                        return error(_("%s does not accept arguments: '%s'"),
1962                                     command_to_string(item->command), bol);
1963                item->commit = NULL;
1964                item->arg = bol;
1965                item->arg_len = eol - bol;
1966                return 0;
1967        }
1968
1969        if (!padding)
1970                return error(_("missing arguments for %s"),
1971                             command_to_string(item->command));
1972
1973        if (item->command == TODO_EXEC || item->command == TODO_LABEL ||
1974            item->command == TODO_RESET) {
1975                item->commit = NULL;
1976                item->arg = bol;
1977                item->arg_len = (int)(eol - bol);
1978                return 0;
1979        }
1980
1981        if (item->command == TODO_MERGE) {
1982                if (skip_prefix(bol, "-C", &bol))
1983                        bol += strspn(bol, " \t");
1984                else if (skip_prefix(bol, "-c", &bol)) {
1985                        bol += strspn(bol, " \t");
1986                        item->flags |= TODO_EDIT_MERGE_MSG;
1987                } else {
1988                        item->flags |= TODO_EDIT_MERGE_MSG;
1989                        item->commit = NULL;
1990                        item->arg = bol;
1991                        item->arg_len = (int)(eol - bol);
1992                        return 0;
1993                }
1994        }
1995
1996        end_of_object_name = (char *) bol + strcspn(bol, " \t\n");
1997        saved = *end_of_object_name;
1998        *end_of_object_name = '\0';
1999        status = get_oid(bol, &commit_oid);
2000        *end_of_object_name = saved;
2001
2002        item->arg = end_of_object_name + strspn(end_of_object_name, " \t");
2003        item->arg_len = (int)(eol - item->arg);
2004
2005        if (status < 0)
2006                return -1;
2007
2008        item->commit = lookup_commit_reference(&commit_oid);
2009        return !item->commit;
2010}
2011
2012static int parse_insn_buffer(char *buf, struct todo_list *todo_list)
2013{
2014        struct todo_item *item;
2015        char *p = buf, *next_p;
2016        int i, res = 0, fixup_okay = file_exists(rebase_path_done());
2017
2018        for (i = 1; *p; i++, p = next_p) {
2019                char *eol = strchrnul(p, '\n');
2020
2021                next_p = *eol ? eol + 1 /* skip LF */ : eol;
2022
2023                if (p != eol && eol[-1] == '\r')
2024                        eol--; /* strip Carriage Return */
2025
2026                item = append_new_todo(todo_list);
2027                item->offset_in_buf = p - todo_list->buf.buf;
2028                if (parse_insn_line(item, p, eol)) {
2029                        res = error(_("invalid line %d: %.*s"),
2030                                i, (int)(eol - p), p);
2031                        item->command = TODO_NOOP;
2032                }
2033
2034                if (fixup_okay)
2035                        ; /* do nothing */
2036                else if (is_fixup(item->command))
2037                        return error(_("cannot '%s' without a previous commit"),
2038                                command_to_string(item->command));
2039                else if (!is_noop(item->command))
2040                        fixup_okay = 1;
2041        }
2042
2043        return res;
2044}
2045
2046static int count_commands(struct todo_list *todo_list)
2047{
2048        int count = 0, i;
2049
2050        for (i = 0; i < todo_list->nr; i++)
2051                if (todo_list->items[i].command != TODO_COMMENT)
2052                        count++;
2053
2054        return count;
2055}
2056
2057static int get_item_line_offset(struct todo_list *todo_list, int index)
2058{
2059        return index < todo_list->nr ?
2060                todo_list->items[index].offset_in_buf : todo_list->buf.len;
2061}
2062
2063static const char *get_item_line(struct todo_list *todo_list, int index)
2064{
2065        return todo_list->buf.buf + get_item_line_offset(todo_list, index);
2066}
2067
2068static int get_item_line_length(struct todo_list *todo_list, int index)
2069{
2070        return get_item_line_offset(todo_list, index + 1)
2071                -  get_item_line_offset(todo_list, index);
2072}
2073
2074static ssize_t strbuf_read_file_or_whine(struct strbuf *sb, const char *path)
2075{
2076        int fd;
2077        ssize_t len;
2078
2079        fd = open(path, O_RDONLY);
2080        if (fd < 0)
2081                return error_errno(_("could not open '%s'"), path);
2082        len = strbuf_read(sb, fd, 0);
2083        close(fd);
2084        if (len < 0)
2085                return error(_("could not read '%s'."), path);
2086        return len;
2087}
2088
2089static int read_populate_todo(struct todo_list *todo_list,
2090                        struct replay_opts *opts)
2091{
2092        struct stat st;
2093        const char *todo_file = get_todo_path(opts);
2094        int res;
2095
2096        strbuf_reset(&todo_list->buf);
2097        if (strbuf_read_file_or_whine(&todo_list->buf, todo_file) < 0)
2098                return -1;
2099
2100        res = stat(todo_file, &st);
2101        if (res)
2102                return error(_("could not stat '%s'"), todo_file);
2103        fill_stat_data(&todo_list->stat, &st);
2104
2105        res = parse_insn_buffer(todo_list->buf.buf, todo_list);
2106        if (res) {
2107                if (is_rebase_i(opts))
2108                        return error(_("please fix this using "
2109                                       "'git rebase --edit-todo'."));
2110                return error(_("unusable instruction sheet: '%s'"), todo_file);
2111        }
2112
2113        if (!todo_list->nr &&
2114            (!is_rebase_i(opts) || !file_exists(rebase_path_done())))
2115                return error(_("no commits parsed."));
2116
2117        if (!is_rebase_i(opts)) {
2118                enum todo_command valid =
2119                        opts->action == REPLAY_PICK ? TODO_PICK : TODO_REVERT;
2120                int i;
2121
2122                for (i = 0; i < todo_list->nr; i++)
2123                        if (valid == todo_list->items[i].command)
2124                                continue;
2125                        else if (valid == TODO_PICK)
2126                                return error(_("cannot cherry-pick during a revert."));
2127                        else
2128                                return error(_("cannot revert during a cherry-pick."));
2129        }
2130
2131        if (is_rebase_i(opts)) {
2132                struct todo_list done = TODO_LIST_INIT;
2133                FILE *f = fopen_or_warn(rebase_path_msgtotal(), "w");
2134
2135                if (strbuf_read_file(&done.buf, rebase_path_done(), 0) > 0 &&
2136                                !parse_insn_buffer(done.buf.buf, &done))
2137                        todo_list->done_nr = count_commands(&done);
2138                else
2139                        todo_list->done_nr = 0;
2140
2141                todo_list->total_nr = todo_list->done_nr
2142                        + count_commands(todo_list);
2143                todo_list_release(&done);
2144
2145                if (f) {
2146                        fprintf(f, "%d\n", todo_list->total_nr);
2147                        fclose(f);
2148                }
2149        }
2150
2151        return 0;
2152}
2153
2154static int git_config_string_dup(char **dest,
2155                                 const char *var, const char *value)
2156{
2157        if (!value)
2158                return config_error_nonbool(var);
2159        free(*dest);
2160        *dest = xstrdup(value);
2161        return 0;
2162}
2163
2164static int populate_opts_cb(const char *key, const char *value, void *data)
2165{
2166        struct replay_opts *opts = data;
2167        int error_flag = 1;
2168
2169        if (!value)
2170                error_flag = 0;
2171        else if (!strcmp(key, "options.no-commit"))
2172                opts->no_commit = git_config_bool_or_int(key, value, &error_flag);
2173        else if (!strcmp(key, "options.edit"))
2174                opts->edit = git_config_bool_or_int(key, value, &error_flag);
2175        else if (!strcmp(key, "options.signoff"))
2176                opts->signoff = git_config_bool_or_int(key, value, &error_flag);
2177        else if (!strcmp(key, "options.record-origin"))
2178                opts->record_origin = git_config_bool_or_int(key, value, &error_flag);
2179        else if (!strcmp(key, "options.allow-ff"))
2180                opts->allow_ff = git_config_bool_or_int(key, value, &error_flag);
2181        else if (!strcmp(key, "options.mainline"))
2182                opts->mainline = git_config_int(key, value);
2183        else if (!strcmp(key, "options.strategy"))
2184                git_config_string_dup(&opts->strategy, key, value);
2185        else if (!strcmp(key, "options.gpg-sign"))
2186                git_config_string_dup(&opts->gpg_sign, key, value);
2187        else if (!strcmp(key, "options.strategy-option")) {
2188                ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
2189                opts->xopts[opts->xopts_nr++] = xstrdup(value);
2190        } else if (!strcmp(key, "options.allow-rerere-auto"))
2191                opts->allow_rerere_auto =
2192                        git_config_bool_or_int(key, value, &error_flag) ?
2193                                RERERE_AUTOUPDATE : RERERE_NOAUTOUPDATE;
2194        else
2195                return error(_("invalid key: %s"), key);
2196
2197        if (!error_flag)
2198                return error(_("invalid value for %s: %s"), key, value);
2199
2200        return 0;
2201}
2202
2203static void read_strategy_opts(struct replay_opts *opts, struct strbuf *buf)
2204{
2205        int i;
2206
2207        strbuf_reset(buf);
2208        if (!read_oneliner(buf, rebase_path_strategy(), 0))
2209                return;
2210        opts->strategy = strbuf_detach(buf, NULL);
2211        if (!read_oneliner(buf, rebase_path_strategy_opts(), 0))
2212                return;
2213
2214        opts->xopts_nr = split_cmdline(buf->buf, (const char ***)&opts->xopts);
2215        for (i = 0; i < opts->xopts_nr; i++) {
2216                const char *arg = opts->xopts[i];
2217
2218                skip_prefix(arg, "--", &arg);
2219                opts->xopts[i] = xstrdup(arg);
2220        }
2221}
2222
2223static int read_populate_opts(struct replay_opts *opts)
2224{
2225        if (is_rebase_i(opts)) {
2226                struct strbuf buf = STRBUF_INIT;
2227
2228                if (read_oneliner(&buf, rebase_path_gpg_sign_opt(), 1)) {
2229                        if (!starts_with(buf.buf, "-S"))
2230                                strbuf_reset(&buf);
2231                        else {
2232                                free(opts->gpg_sign);
2233                                opts->gpg_sign = xstrdup(buf.buf + 2);
2234                        }
2235                        strbuf_reset(&buf);
2236                }
2237
2238                if (read_oneliner(&buf, rebase_path_allow_rerere_autoupdate(), 1)) {
2239                        if (!strcmp(buf.buf, "--rerere-autoupdate"))
2240                                opts->allow_rerere_auto = RERERE_AUTOUPDATE;
2241                        else if (!strcmp(buf.buf, "--no-rerere-autoupdate"))
2242                                opts->allow_rerere_auto = RERERE_NOAUTOUPDATE;
2243                        strbuf_reset(&buf);
2244                }
2245
2246                if (file_exists(rebase_path_verbose()))
2247                        opts->verbose = 1;
2248
2249                if (file_exists(rebase_path_signoff())) {
2250                        opts->allow_ff = 0;
2251                        opts->signoff = 1;
2252                }
2253
2254                read_strategy_opts(opts, &buf);
2255                strbuf_release(&buf);
2256
2257                if (read_oneliner(&opts->current_fixups,
2258                                  rebase_path_current_fixups(), 1)) {
2259                        const char *p = opts->current_fixups.buf;
2260                        opts->current_fixup_count = 1;
2261                        while ((p = strchr(p, '\n'))) {
2262                                opts->current_fixup_count++;
2263                                p++;
2264                        }
2265                }
2266
2267                if (read_oneliner(&buf, rebase_path_squash_onto(), 0)) {
2268                        if (get_oid_hex(buf.buf, &opts->squash_onto) < 0)
2269                                return error(_("unusable squash-onto"));
2270                        opts->have_squash_onto = 1;
2271                }
2272
2273                return 0;
2274        }
2275
2276        if (!file_exists(git_path_opts_file()))
2277                return 0;
2278        /*
2279         * The function git_parse_source(), called from git_config_from_file(),
2280         * may die() in case of a syntactically incorrect file. We do not care
2281         * about this case, though, because we wrote that file ourselves, so we
2282         * are pretty certain that it is syntactically correct.
2283         */
2284        if (git_config_from_file(populate_opts_cb, git_path_opts_file(), opts) < 0)
2285                return error(_("malformed options sheet: '%s'"),
2286                        git_path_opts_file());
2287        return 0;
2288}
2289
2290static int walk_revs_populate_todo(struct todo_list *todo_list,
2291                                struct replay_opts *opts)
2292{
2293        enum todo_command command = opts->action == REPLAY_PICK ?
2294                TODO_PICK : TODO_REVERT;
2295        const char *command_string = todo_command_info[command].str;
2296        struct commit *commit;
2297
2298        if (prepare_revs(opts))
2299                return -1;
2300
2301        while ((commit = get_revision(opts->revs))) {
2302                struct todo_item *item = append_new_todo(todo_list);
2303                const char *commit_buffer = get_commit_buffer(commit, NULL);
2304                const char *subject;
2305                int subject_len;
2306
2307                item->command = command;
2308                item->commit = commit;
2309                item->arg = NULL;
2310                item->arg_len = 0;
2311                item->offset_in_buf = todo_list->buf.len;
2312                subject_len = find_commit_subject(commit_buffer, &subject);
2313                strbuf_addf(&todo_list->buf, "%s %s %.*s\n", command_string,
2314                        short_commit_name(commit), subject_len, subject);
2315                unuse_commit_buffer(commit, commit_buffer);
2316        }
2317        return 0;
2318}
2319
2320static int create_seq_dir(void)
2321{
2322        if (file_exists(git_path_seq_dir())) {
2323                error(_("a cherry-pick or revert is already in progress"));
2324                advise(_("try \"git cherry-pick (--continue | --quit | --abort)\""));
2325                return -1;
2326        } else if (mkdir(git_path_seq_dir(), 0777) < 0)
2327                return error_errno(_("could not create sequencer directory '%s'"),
2328                                   git_path_seq_dir());
2329        return 0;
2330}
2331
2332static int save_head(const char *head)
2333{
2334        struct lock_file head_lock = LOCK_INIT;
2335        struct strbuf buf = STRBUF_INIT;
2336        int fd;
2337        ssize_t written;
2338
2339        fd = hold_lock_file_for_update(&head_lock, git_path_head_file(), 0);
2340        if (fd < 0)
2341                return error_errno(_("could not lock HEAD"));
2342        strbuf_addf(&buf, "%s\n", head);
2343        written = write_in_full(fd, buf.buf, buf.len);
2344        strbuf_release(&buf);
2345        if (written < 0) {
2346                error_errno(_("could not write to '%s'"), git_path_head_file());
2347                rollback_lock_file(&head_lock);
2348                return -1;
2349        }
2350        if (commit_lock_file(&head_lock) < 0)
2351                return error(_("failed to finalize '%s'"), git_path_head_file());
2352        return 0;
2353}
2354
2355static int rollback_is_safe(void)
2356{
2357        struct strbuf sb = STRBUF_INIT;
2358        struct object_id expected_head, actual_head;
2359
2360        if (strbuf_read_file(&sb, git_path_abort_safety_file(), 0) >= 0) {
2361                strbuf_trim(&sb);
2362                if (get_oid_hex(sb.buf, &expected_head)) {
2363                        strbuf_release(&sb);
2364                        die(_("could not parse %s"), git_path_abort_safety_file());
2365                }
2366                strbuf_release(&sb);
2367        }
2368        else if (errno == ENOENT)
2369                oidclr(&expected_head);
2370        else
2371                die_errno(_("could not read '%s'"), git_path_abort_safety_file());
2372
2373        if (get_oid("HEAD", &actual_head))
2374                oidclr(&actual_head);
2375
2376        return !oidcmp(&actual_head, &expected_head);
2377}
2378
2379static int reset_for_rollback(const struct object_id *oid)
2380{
2381        const char *argv[4];    /* reset --merge <arg> + NULL */
2382
2383        argv[0] = "reset";
2384        argv[1] = "--merge";
2385        argv[2] = oid_to_hex(oid);
2386        argv[3] = NULL;
2387        return run_command_v_opt(argv, RUN_GIT_CMD);
2388}
2389
2390static int rollback_single_pick(void)
2391{
2392        struct object_id head_oid;
2393
2394        if (!file_exists(git_path_cherry_pick_head()) &&
2395            !file_exists(git_path_revert_head()))
2396                return error(_("no cherry-pick or revert in progress"));
2397        if (read_ref_full("HEAD", 0, &head_oid, NULL))
2398                return error(_("cannot resolve HEAD"));
2399        if (is_null_oid(&head_oid))
2400                return error(_("cannot abort from a branch yet to be born"));
2401        return reset_for_rollback(&head_oid);
2402}
2403
2404int sequencer_rollback(struct replay_opts *opts)
2405{
2406        FILE *f;
2407        struct object_id oid;
2408        struct strbuf buf = STRBUF_INIT;
2409        const char *p;
2410
2411        f = fopen(git_path_head_file(), "r");
2412        if (!f && errno == ENOENT) {
2413                /*
2414                 * There is no multiple-cherry-pick in progress.
2415                 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
2416                 * a single-cherry-pick in progress, abort that.
2417                 */
2418                return rollback_single_pick();
2419        }
2420        if (!f)
2421                return error_errno(_("cannot open '%s'"), git_path_head_file());
2422        if (strbuf_getline_lf(&buf, f)) {
2423                error(_("cannot read '%s': %s"), git_path_head_file(),
2424                      ferror(f) ?  strerror(errno) : _("unexpected end of file"));
2425                fclose(f);
2426                goto fail;
2427        }
2428        fclose(f);
2429        if (parse_oid_hex(buf.buf, &oid, &p) || *p != '\0') {
2430                error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
2431                        git_path_head_file());
2432                goto fail;
2433        }
2434        if (is_null_oid(&oid)) {
2435                error(_("cannot abort from a branch yet to be born"));
2436                goto fail;
2437        }
2438
2439        if (!rollback_is_safe()) {
2440                /* Do not error, just do not rollback */
2441                warning(_("You seem to have moved HEAD. "
2442                          "Not rewinding, check your HEAD!"));
2443        } else
2444        if (reset_for_rollback(&oid))
2445                goto fail;
2446        strbuf_release(&buf);
2447        return sequencer_remove_state(opts);
2448fail:
2449        strbuf_release(&buf);
2450        return -1;
2451}
2452
2453static int save_todo(struct todo_list *todo_list, struct replay_opts *opts)
2454{
2455        struct lock_file todo_lock = LOCK_INIT;
2456        const char *todo_path = get_todo_path(opts);
2457        int next = todo_list->current, offset, fd;
2458
2459        /*
2460         * rebase -i writes "git-rebase-todo" without the currently executing
2461         * command, appending it to "done" instead.
2462         */
2463        if (is_rebase_i(opts))
2464                next++;
2465
2466        fd = hold_lock_file_for_update(&todo_lock, todo_path, 0);
2467        if (fd < 0)
2468                return error_errno(_("could not lock '%s'"), todo_path);
2469        offset = get_item_line_offset(todo_list, next);
2470        if (write_in_full(fd, todo_list->buf.buf + offset,
2471                        todo_list->buf.len - offset) < 0)
2472                return error_errno(_("could not write to '%s'"), todo_path);
2473        if (commit_lock_file(&todo_lock) < 0)
2474                return error(_("failed to finalize '%s'"), todo_path);
2475
2476        if (is_rebase_i(opts) && next > 0) {
2477                const char *done = rebase_path_done();
2478                int fd = open(done, O_CREAT | O_WRONLY | O_APPEND, 0666);
2479                int ret = 0;
2480
2481                if (fd < 0)
2482                        return 0;
2483                if (write_in_full(fd, get_item_line(todo_list, next - 1),
2484                                  get_item_line_length(todo_list, next - 1))
2485                    < 0)
2486                        ret = error_errno(_("could not write to '%s'"), done);
2487                if (close(fd) < 0)
2488                        ret = error_errno(_("failed to finalize '%s'"), done);
2489                return ret;
2490        }
2491        return 0;
2492}
2493
2494static int save_opts(struct replay_opts *opts)
2495{
2496        const char *opts_file = git_path_opts_file();
2497        int res = 0;
2498
2499        if (opts->no_commit)
2500                res |= git_config_set_in_file_gently(opts_file, "options.no-commit", "true");
2501        if (opts->edit)
2502                res |= git_config_set_in_file_gently(opts_file, "options.edit", "true");
2503        if (opts->signoff)
2504                res |= git_config_set_in_file_gently(opts_file, "options.signoff", "true");
2505        if (opts->record_origin)
2506                res |= git_config_set_in_file_gently(opts_file, "options.record-origin", "true");
2507        if (opts->allow_ff)
2508                res |= git_config_set_in_file_gently(opts_file, "options.allow-ff", "true");
2509        if (opts->mainline) {
2510                struct strbuf buf = STRBUF_INIT;
2511                strbuf_addf(&buf, "%d", opts->mainline);
2512                res |= git_config_set_in_file_gently(opts_file, "options.mainline", buf.buf);
2513                strbuf_release(&buf);
2514        }
2515        if (opts->strategy)
2516                res |= git_config_set_in_file_gently(opts_file, "options.strategy", opts->strategy);
2517        if (opts->gpg_sign)
2518                res |= git_config_set_in_file_gently(opts_file, "options.gpg-sign", opts->gpg_sign);
2519        if (opts->xopts) {
2520                int i;
2521                for (i = 0; i < opts->xopts_nr; i++)
2522                        res |= git_config_set_multivar_in_file_gently(opts_file,
2523                                                        "options.strategy-option",
2524                                                        opts->xopts[i], "^$", 0);
2525        }
2526        if (opts->allow_rerere_auto)
2527                res |= git_config_set_in_file_gently(opts_file, "options.allow-rerere-auto",
2528                                                     opts->allow_rerere_auto == RERERE_AUTOUPDATE ?
2529                                                     "true" : "false");
2530        return res;
2531}
2532
2533static int make_patch(struct commit *commit, struct replay_opts *opts)
2534{
2535        struct strbuf buf = STRBUF_INIT;
2536        struct rev_info log_tree_opt;
2537        const char *subject, *p;
2538        int res = 0;
2539
2540        p = short_commit_name(commit);
2541        if (write_message(p, strlen(p), rebase_path_stopped_sha(), 1) < 0)
2542                return -1;
2543        if (update_ref("rebase", "REBASE_HEAD", &commit->object.oid,
2544                       NULL, REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
2545                res |= error(_("could not update %s"), "REBASE_HEAD");
2546
2547        strbuf_addf(&buf, "%s/patch", get_dir(opts));
2548        memset(&log_tree_opt, 0, sizeof(log_tree_opt));
2549        init_revisions(&log_tree_opt, NULL);
2550        log_tree_opt.abbrev = 0;
2551        log_tree_opt.diff = 1;
2552        log_tree_opt.diffopt.output_format = DIFF_FORMAT_PATCH;
2553        log_tree_opt.disable_stdin = 1;
2554        log_tree_opt.no_commit_id = 1;
2555        log_tree_opt.diffopt.file = fopen(buf.buf, "w");
2556        log_tree_opt.diffopt.use_color = GIT_COLOR_NEVER;
2557        if (!log_tree_opt.diffopt.file)
2558                res |= error_errno(_("could not open '%s'"), buf.buf);
2559        else {
2560                res |= log_tree_commit(&log_tree_opt, commit);
2561                fclose(log_tree_opt.diffopt.file);
2562        }
2563        strbuf_reset(&buf);
2564
2565        strbuf_addf(&buf, "%s/message", get_dir(opts));
2566        if (!file_exists(buf.buf)) {
2567                const char *commit_buffer = get_commit_buffer(commit, NULL);
2568                find_commit_subject(commit_buffer, &subject);
2569                res |= write_message(subject, strlen(subject), buf.buf, 1);
2570                unuse_commit_buffer(commit, commit_buffer);
2571        }
2572        strbuf_release(&buf);
2573
2574        return res;
2575}
2576
2577static int intend_to_amend(void)
2578{
2579        struct object_id head;
2580        char *p;
2581
2582        if (get_oid("HEAD", &head))
2583                return error(_("cannot read HEAD"));
2584
2585        p = oid_to_hex(&head);
2586        return write_message(p, strlen(p), rebase_path_amend(), 1);
2587}
2588
2589static int error_with_patch(struct commit *commit,
2590        const char *subject, int subject_len,
2591        struct replay_opts *opts, int exit_code, int to_amend)
2592{
2593        if (commit) {
2594                if (make_patch(commit, opts))
2595                        return -1;
2596        } else if (copy_file(rebase_path_message(), git_path_merge_msg(), 0666))
2597                return error(_("unable to copy '%s' to '%s'"),
2598                             git_path_merge_msg(), rebase_path_message());
2599
2600        if (to_amend) {
2601                if (intend_to_amend())
2602                        return -1;
2603
2604                fprintf(stderr, "You can amend the commit now, with\n"
2605                        "\n"
2606                        "  git commit --amend %s\n"
2607                        "\n"
2608                        "Once you are satisfied with your changes, run\n"
2609                        "\n"
2610                        "  git rebase --continue\n", gpg_sign_opt_quoted(opts));
2611        } else if (exit_code) {
2612                if (commit)
2613                        fprintf(stderr, "Could not apply %s... %.*s\n",
2614                                short_commit_name(commit),
2615                                subject_len, subject);
2616                else
2617                        /*
2618                         * We don't have the hash of the parent so
2619                         * just print the line from the todo file.
2620                         */
2621                        fprintf(stderr, "Could not merge %.*s\n",
2622                                subject_len, subject);
2623        }
2624
2625        return exit_code;
2626}
2627
2628static int error_failed_squash(struct commit *commit,
2629        struct replay_opts *opts, int subject_len, const char *subject)
2630{
2631        if (copy_file(rebase_path_message(), rebase_path_squash_msg(), 0666))
2632                return error(_("could not copy '%s' to '%s'"),
2633                        rebase_path_squash_msg(), rebase_path_message());
2634        unlink(git_path_merge_msg());
2635        if (copy_file(git_path_merge_msg(), rebase_path_message(), 0666))
2636                return error(_("could not copy '%s' to '%s'"),
2637                             rebase_path_message(), git_path_merge_msg());
2638        return error_with_patch(commit, subject, subject_len, opts, 1, 0);
2639}
2640
2641static int do_exec(const char *command_line)
2642{
2643        struct argv_array child_env = ARGV_ARRAY_INIT;
2644        const char *child_argv[] = { NULL, NULL };
2645        int dirty, status;
2646
2647        fprintf(stderr, "Executing: %s\n", command_line);
2648        child_argv[0] = command_line;
2649        argv_array_pushf(&child_env, "GIT_DIR=%s", absolute_path(get_git_dir()));
2650        status = run_command_v_opt_cd_env(child_argv, RUN_USING_SHELL, NULL,
2651                                          child_env.argv);
2652
2653        /* force re-reading of the cache */
2654        if (discard_cache() < 0 || read_cache() < 0)
2655                return error(_("could not read index"));
2656
2657        dirty = require_clean_work_tree("rebase", NULL, 1, 1);
2658
2659        if (status) {
2660                warning(_("execution failed: %s\n%s"
2661                          "You can fix the problem, and then run\n"
2662                          "\n"
2663                          "  git rebase --continue\n"
2664                          "\n"),
2665                        command_line,
2666                        dirty ? N_("and made changes to the index and/or the "
2667                                "working tree\n") : "");
2668                if (status == 127)
2669                        /* command not found */
2670                        status = 1;
2671        } else if (dirty) {
2672                warning(_("execution succeeded: %s\nbut "
2673                          "left changes to the index and/or the working tree\n"
2674                          "Commit or stash your changes, and then run\n"
2675                          "\n"
2676                          "  git rebase --continue\n"
2677                          "\n"), command_line);
2678                status = 1;
2679        }
2680
2681        argv_array_clear(&child_env);
2682
2683        return status;
2684}
2685
2686static int safe_append(const char *filename, const char *fmt, ...)
2687{
2688        va_list ap;
2689        struct lock_file lock = LOCK_INIT;
2690        int fd = hold_lock_file_for_update(&lock, filename,
2691                                           LOCK_REPORT_ON_ERROR);
2692        struct strbuf buf = STRBUF_INIT;
2693
2694        if (fd < 0)
2695                return -1;
2696
2697        if (strbuf_read_file(&buf, filename, 0) < 0 && errno != ENOENT) {
2698                error_errno(_("could not read '%s'"), filename);
2699                rollback_lock_file(&lock);
2700                return -1;
2701        }
2702        strbuf_complete(&buf, '\n');
2703        va_start(ap, fmt);
2704        strbuf_vaddf(&buf, fmt, ap);
2705        va_end(ap);
2706
2707        if (write_in_full(fd, buf.buf, buf.len) < 0) {
2708                error_errno(_("could not write to '%s'"), filename);
2709                strbuf_release(&buf);
2710                rollback_lock_file(&lock);
2711                return -1;
2712        }
2713        if (commit_lock_file(&lock) < 0) {
2714                strbuf_release(&buf);
2715                rollback_lock_file(&lock);
2716                return error(_("failed to finalize '%s'"), filename);
2717        }
2718
2719        strbuf_release(&buf);
2720        return 0;
2721}
2722
2723static int do_label(const char *name, int len)
2724{
2725        struct ref_store *refs = get_main_ref_store(the_repository);
2726        struct ref_transaction *transaction;
2727        struct strbuf ref_name = STRBUF_INIT, err = STRBUF_INIT;
2728        struct strbuf msg = STRBUF_INIT;
2729        int ret = 0;
2730        struct object_id head_oid;
2731
2732        if (len == 1 && *name == '#')
2733                return error("Illegal label name: '%.*s'", len, name);
2734
2735        strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
2736        strbuf_addf(&msg, "rebase -i (label) '%.*s'", len, name);
2737
2738        transaction = ref_store_transaction_begin(refs, &err);
2739        if (!transaction) {
2740                error("%s", err.buf);
2741                ret = -1;
2742        } else if (get_oid("HEAD", &head_oid)) {
2743                error(_("could not read HEAD"));
2744                ret = -1;
2745        } else if (ref_transaction_update(transaction, ref_name.buf, &head_oid,
2746                                          NULL, 0, msg.buf, &err) < 0 ||
2747                   ref_transaction_commit(transaction, &err)) {
2748                error("%s", err.buf);
2749                ret = -1;
2750        }
2751        ref_transaction_free(transaction);
2752        strbuf_release(&err);
2753        strbuf_release(&msg);
2754
2755        if (!ret)
2756                ret = safe_append(rebase_path_refs_to_delete(),
2757                                  "%s\n", ref_name.buf);
2758        strbuf_release(&ref_name);
2759
2760        return ret;
2761}
2762
2763static const char *reflog_message(struct replay_opts *opts,
2764        const char *sub_action, const char *fmt, ...);
2765
2766static int do_reset(const char *name, int len, struct replay_opts *opts)
2767{
2768        struct strbuf ref_name = STRBUF_INIT;
2769        struct object_id oid;
2770        struct lock_file lock = LOCK_INIT;
2771        struct tree_desc desc;
2772        struct tree *tree;
2773        struct unpack_trees_options unpack_tree_opts;
2774        int ret = 0, i;
2775
2776        if (hold_locked_index(&lock, LOCK_REPORT_ON_ERROR) < 0)
2777                return -1;
2778
2779        if (len == 10 && !strncmp("[new root]", name, len)) {
2780                if (!opts->have_squash_onto) {
2781                        const char *hex;
2782                        if (commit_tree("", 0, the_hash_algo->empty_tree,
2783                                        NULL, &opts->squash_onto,
2784                                        NULL, NULL))
2785                                return error(_("writing fake root commit"));
2786                        opts->have_squash_onto = 1;
2787                        hex = oid_to_hex(&opts->squash_onto);
2788                        if (write_message(hex, strlen(hex),
2789                                          rebase_path_squash_onto(), 0))
2790                                return error(_("writing squash-onto"));
2791                }
2792                oidcpy(&oid, &opts->squash_onto);
2793        } else {
2794                /* Determine the length of the label */
2795                for (i = 0; i < len; i++)
2796                        if (isspace(name[i]))
2797                                len = i;
2798
2799                strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
2800                if (get_oid(ref_name.buf, &oid) &&
2801                    get_oid(ref_name.buf + strlen("refs/rewritten/"), &oid)) {
2802                        error(_("could not read '%s'"), ref_name.buf);
2803                        rollback_lock_file(&lock);
2804                        strbuf_release(&ref_name);
2805                        return -1;
2806                }
2807        }
2808
2809        memset(&unpack_tree_opts, 0, sizeof(unpack_tree_opts));
2810        setup_unpack_trees_porcelain(&unpack_tree_opts, "reset");
2811        unpack_tree_opts.head_idx = 1;
2812        unpack_tree_opts.src_index = &the_index;
2813        unpack_tree_opts.dst_index = &the_index;
2814        unpack_tree_opts.fn = oneway_merge;
2815        unpack_tree_opts.merge = 1;
2816        unpack_tree_opts.update = 1;
2817
2818        if (read_cache_unmerged()) {
2819                rollback_lock_file(&lock);
2820                strbuf_release(&ref_name);
2821                return error_resolve_conflict(_(action_name(opts)));
2822        }
2823
2824        if (!fill_tree_descriptor(&desc, &oid)) {
2825                error(_("failed to find tree of %s"), oid_to_hex(&oid));
2826                rollback_lock_file(&lock);
2827                free((void *)desc.buffer);
2828                strbuf_release(&ref_name);
2829                return -1;
2830        }
2831
2832        if (unpack_trees(1, &desc, &unpack_tree_opts)) {
2833                rollback_lock_file(&lock);
2834                free((void *)desc.buffer);
2835                strbuf_release(&ref_name);
2836                return -1;
2837        }
2838
2839        tree = parse_tree_indirect(&oid);
2840        prime_cache_tree(&the_index, tree);
2841
2842        if (write_locked_index(&the_index, &lock, COMMIT_LOCK) < 0)
2843                ret = error(_("could not write index"));
2844        free((void *)desc.buffer);
2845
2846        if (!ret)
2847                ret = update_ref(reflog_message(opts, "reset", "'%.*s'",
2848                                                len, name), "HEAD", &oid,
2849                                 NULL, 0, UPDATE_REFS_MSG_ON_ERR);
2850
2851        strbuf_release(&ref_name);
2852        return ret;
2853}
2854
2855static int do_merge(struct commit *commit, const char *arg, int arg_len,
2856                    int flags, struct replay_opts *opts)
2857{
2858        int run_commit_flags = (flags & TODO_EDIT_MERGE_MSG) ?
2859                EDIT_MSG | VERIFY_MSG : 0;
2860        struct strbuf ref_name = STRBUF_INIT;
2861        struct commit *head_commit, *merge_commit, *i;
2862        struct commit_list *bases, *j, *reversed = NULL;
2863        struct merge_options o;
2864        int merge_arg_len, oneline_offset, can_fast_forward, ret;
2865        static struct lock_file lock;
2866        const char *p;
2867
2868        if (hold_locked_index(&lock, LOCK_REPORT_ON_ERROR) < 0) {
2869                ret = -1;
2870                goto leave_merge;
2871        }
2872
2873        head_commit = lookup_commit_reference_by_name("HEAD");
2874        if (!head_commit) {
2875                ret = error(_("cannot merge without a current revision"));
2876                goto leave_merge;
2877        }
2878
2879        oneline_offset = arg_len;
2880        merge_arg_len = strcspn(arg, " \t\n");
2881        p = arg + merge_arg_len;
2882        p += strspn(p, " \t\n");
2883        if (*p == '#' && (!p[1] || isspace(p[1]))) {
2884                p += 1 + strspn(p + 1, " \t\n");
2885                oneline_offset = p - arg;
2886        } else if (p - arg < arg_len)
2887                BUG("octopus merges are not supported yet: '%s'", p);
2888
2889        strbuf_addf(&ref_name, "refs/rewritten/%.*s", merge_arg_len, arg);
2890        merge_commit = lookup_commit_reference_by_name(ref_name.buf);
2891        if (!merge_commit) {
2892                /* fall back to non-rewritten ref or commit */
2893                strbuf_splice(&ref_name, 0, strlen("refs/rewritten/"), "", 0);
2894                merge_commit = lookup_commit_reference_by_name(ref_name.buf);
2895        }
2896
2897        if (!merge_commit) {
2898                ret = error(_("could not resolve '%s'"), ref_name.buf);
2899                goto leave_merge;
2900        }
2901
2902        if (opts->have_squash_onto &&
2903            !oidcmp(&head_commit->object.oid, &opts->squash_onto)) {
2904                /*
2905                 * When the user tells us to "merge" something into a
2906                 * "[new root]", let's simply fast-forward to the merge head.
2907                 */
2908                rollback_lock_file(&lock);
2909                ret = fast_forward_to(&merge_commit->object.oid,
2910                                       &head_commit->object.oid, 0, opts);
2911                goto leave_merge;
2912        }
2913
2914        if (commit) {
2915                const char *message = get_commit_buffer(commit, NULL);
2916                const char *body;
2917                int len;
2918
2919                if (!message) {
2920                        ret = error(_("could not get commit message of '%s'"),
2921                                    oid_to_hex(&commit->object.oid));
2922                        goto leave_merge;
2923                }
2924                write_author_script(message);
2925                find_commit_subject(message, &body);
2926                len = strlen(body);
2927                ret = write_message(body, len, git_path_merge_msg(), 0);
2928                unuse_commit_buffer(commit, message);
2929                if (ret) {
2930                        error_errno(_("could not write '%s'"),
2931                                    git_path_merge_msg());
2932                        goto leave_merge;
2933                }
2934        } else {
2935                struct strbuf buf = STRBUF_INIT;
2936                int len;
2937
2938                strbuf_addf(&buf, "author %s", git_author_info(0));
2939                write_author_script(buf.buf);
2940                strbuf_reset(&buf);
2941
2942                if (oneline_offset < arg_len) {
2943                        p = arg + oneline_offset;
2944                        len = arg_len - oneline_offset;
2945                } else {
2946                        strbuf_addf(&buf, "Merge branch '%.*s'",
2947                                    merge_arg_len, arg);
2948                        p = buf.buf;
2949                        len = buf.len;
2950                }
2951
2952                ret = write_message(p, len, git_path_merge_msg(), 0);
2953                strbuf_release(&buf);
2954                if (ret) {
2955                        error_errno(_("could not write '%s'"),
2956                                    git_path_merge_msg());
2957                        goto leave_merge;
2958                }
2959        }
2960
2961        /*
2962         * If HEAD is not identical to the first parent of the original merge
2963         * commit, we cannot fast-forward.
2964         */
2965        can_fast_forward = opts->allow_ff && commit && commit->parents &&
2966                !oidcmp(&commit->parents->item->object.oid,
2967                        &head_commit->object.oid);
2968
2969        /*
2970         * If the merge head is different from the original one, we cannot
2971         * fast-forward.
2972         */
2973        if (can_fast_forward) {
2974                struct commit_list *second_parent = commit->parents->next;
2975
2976                if (second_parent && !second_parent->next &&
2977                    oidcmp(&merge_commit->object.oid,
2978                           &second_parent->item->object.oid))
2979                        can_fast_forward = 0;
2980        }
2981
2982        if (can_fast_forward && commit->parents->next &&
2983            !commit->parents->next->next &&
2984            !oidcmp(&commit->parents->next->item->object.oid,
2985                    &merge_commit->object.oid)) {
2986                rollback_lock_file(&lock);
2987                ret = fast_forward_to(&commit->object.oid,
2988                                      &head_commit->object.oid, 0, opts);
2989                goto leave_merge;
2990        }
2991
2992        write_message(oid_to_hex(&merge_commit->object.oid), GIT_SHA1_HEXSZ,
2993                      git_path_merge_head(), 0);
2994        write_message("no-ff", 5, git_path_merge_mode(), 0);
2995
2996        bases = get_merge_bases(head_commit, merge_commit);
2997        if (bases && !oidcmp(&merge_commit->object.oid,
2998                             &bases->item->object.oid)) {
2999                ret = 0;
3000                /* skip merging an ancestor of HEAD */
3001                goto leave_merge;
3002        }
3003
3004        for (j = bases; j; j = j->next)
3005                commit_list_insert(j->item, &reversed);
3006        free_commit_list(bases);
3007
3008        read_cache();
3009        init_merge_options(&o);
3010        o.branch1 = "HEAD";
3011        o.branch2 = ref_name.buf;
3012        o.buffer_output = 2;
3013
3014        ret = merge_recursive(&o, head_commit, merge_commit, reversed, &i);
3015        if (ret <= 0)
3016                fputs(o.obuf.buf, stdout);
3017        strbuf_release(&o.obuf);
3018        if (ret < 0) {
3019                error(_("could not even attempt to merge '%.*s'"),
3020                      merge_arg_len, arg);
3021                goto leave_merge;
3022        }
3023        /*
3024         * The return value of merge_recursive() is 1 on clean, and 0 on
3025         * unclean merge.
3026         *
3027         * Let's reverse that, so that do_merge() returns 0 upon success and
3028         * 1 upon failed merge (keeping the return value -1 for the cases where
3029         * we will want to reschedule the `merge` command).
3030         */
3031        ret = !ret;
3032
3033        if (active_cache_changed &&
3034            write_locked_index(&the_index, &lock, COMMIT_LOCK)) {
3035                ret = error(_("merge: Unable to write new index file"));
3036                goto leave_merge;
3037        }
3038
3039        rollback_lock_file(&lock);
3040        if (ret)
3041                rerere(opts->allow_rerere_auto);
3042        else
3043                /*
3044                 * In case of problems, we now want to return a positive
3045                 * value (a negative one would indicate that the `merge`
3046                 * command needs to be rescheduled).
3047                 */
3048                ret = !!run_git_commit(git_path_merge_msg(), opts,
3049                                     run_commit_flags);
3050
3051leave_merge:
3052        strbuf_release(&ref_name);
3053        rollback_lock_file(&lock);
3054        return ret;
3055}
3056
3057static int is_final_fixup(struct todo_list *todo_list)
3058{
3059        int i = todo_list->current;
3060
3061        if (!is_fixup(todo_list->items[i].command))
3062                return 0;
3063
3064        while (++i < todo_list->nr)
3065                if (is_fixup(todo_list->items[i].command))
3066                        return 0;
3067                else if (!is_noop(todo_list->items[i].command))
3068                        break;
3069        return 1;
3070}
3071
3072static enum todo_command peek_command(struct todo_list *todo_list, int offset)
3073{
3074        int i;
3075
3076        for (i = todo_list->current + offset; i < todo_list->nr; i++)
3077                if (!is_noop(todo_list->items[i].command))
3078                        return todo_list->items[i].command;
3079
3080        return -1;
3081}
3082
3083static int apply_autostash(struct replay_opts *opts)
3084{
3085        struct strbuf stash_sha1 = STRBUF_INIT;
3086        struct child_process child = CHILD_PROCESS_INIT;
3087        int ret = 0;
3088
3089        if (!read_oneliner(&stash_sha1, rebase_path_autostash(), 1)) {
3090                strbuf_release(&stash_sha1);
3091                return 0;
3092        }
3093        strbuf_trim(&stash_sha1);
3094
3095        child.git_cmd = 1;
3096        child.no_stdout = 1;
3097        child.no_stderr = 1;
3098        argv_array_push(&child.args, "stash");
3099        argv_array_push(&child.args, "apply");
3100        argv_array_push(&child.args, stash_sha1.buf);
3101        if (!run_command(&child))
3102                fprintf(stderr, _("Applied autostash.\n"));
3103        else {
3104                struct child_process store = CHILD_PROCESS_INIT;
3105
3106                store.git_cmd = 1;
3107                argv_array_push(&store.args, "stash");
3108                argv_array_push(&store.args, "store");
3109                argv_array_push(&store.args, "-m");
3110                argv_array_push(&store.args, "autostash");
3111                argv_array_push(&store.args, "-q");
3112                argv_array_push(&store.args, stash_sha1.buf);
3113                if (run_command(&store))
3114                        ret = error(_("cannot store %s"), stash_sha1.buf);
3115                else
3116                        fprintf(stderr,
3117                                _("Applying autostash resulted in conflicts.\n"
3118                                  "Your changes are safe in the stash.\n"
3119                                  "You can run \"git stash pop\" or"
3120                                  " \"git stash drop\" at any time.\n"));
3121        }
3122
3123        strbuf_release(&stash_sha1);
3124        return ret;
3125}
3126
3127static const char *reflog_message(struct replay_opts *opts,
3128        const char *sub_action, const char *fmt, ...)
3129{
3130        va_list ap;
3131        static struct strbuf buf = STRBUF_INIT;
3132
3133        va_start(ap, fmt);
3134        strbuf_reset(&buf);
3135        strbuf_addstr(&buf, action_name(opts));
3136        if (sub_action)
3137                strbuf_addf(&buf, " (%s)", sub_action);
3138        if (fmt) {
3139                strbuf_addstr(&buf, ": ");
3140                strbuf_vaddf(&buf, fmt, ap);
3141        }
3142        va_end(ap);
3143
3144        return buf.buf;
3145}
3146
3147static const char rescheduled_advice[] =
3148N_("Could not execute the todo command\n"
3149"\n"
3150"    %.*s"
3151"\n"
3152"It has been rescheduled; To edit the command before continuing, please\n"
3153"edit the todo list first:\n"
3154"\n"
3155"    git rebase --edit-todo\n"
3156"    git rebase --continue\n");
3157
3158static int pick_commits(struct todo_list *todo_list, struct replay_opts *opts)
3159{
3160        int res = 0, reschedule = 0;
3161
3162        setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
3163        if (opts->allow_ff)
3164                assert(!(opts->signoff || opts->no_commit ||
3165                                opts->record_origin || opts->edit));
3166        if (read_and_refresh_cache(opts))
3167                return -1;
3168
3169        while (todo_list->current < todo_list->nr) {
3170                struct todo_item *item = todo_list->items + todo_list->current;
3171                if (save_todo(todo_list, opts))
3172                        return -1;
3173                if (is_rebase_i(opts)) {
3174                        if (item->command != TODO_COMMENT) {
3175                                FILE *f = fopen(rebase_path_msgnum(), "w");
3176
3177                                todo_list->done_nr++;
3178
3179                                if (f) {
3180                                        fprintf(f, "%d\n", todo_list->done_nr);
3181                                        fclose(f);
3182                                }
3183                                fprintf(stderr, "Rebasing (%d/%d)%s",
3184                                        todo_list->done_nr,
3185                                        todo_list->total_nr,
3186                                        opts->verbose ? "\n" : "\r");
3187                        }
3188                        unlink(rebase_path_message());
3189                        unlink(rebase_path_author_script());
3190                        unlink(rebase_path_stopped_sha());
3191                        unlink(rebase_path_amend());
3192                        delete_ref(NULL, "REBASE_HEAD", NULL, REF_NO_DEREF);
3193                }
3194                if (item->command <= TODO_SQUASH) {
3195                        if (is_rebase_i(opts))
3196                                setenv("GIT_REFLOG_ACTION", reflog_message(opts,
3197                                        command_to_string(item->command), NULL),
3198                                        1);
3199                        res = do_pick_commit(item->command, item->commit,
3200                                        opts, is_final_fixup(todo_list));
3201                        if (is_rebase_i(opts) && res < 0) {
3202                                /* Reschedule */
3203                                advise(_(rescheduled_advice),
3204                                       get_item_line_length(todo_list,
3205                                                            todo_list->current),
3206                                       get_item_line(todo_list,
3207                                                     todo_list->current));
3208                                todo_list->current--;
3209                                if (save_todo(todo_list, opts))
3210                                        return -1;
3211                        }
3212                        if (item->command == TODO_EDIT) {
3213                                struct commit *commit = item->commit;
3214                                if (!res)
3215                                        fprintf(stderr,
3216                                                _("Stopped at %s...  %.*s\n"),
3217                                                short_commit_name(commit),
3218                                                item->arg_len, item->arg);
3219                                return error_with_patch(commit,
3220                                        item->arg, item->arg_len, opts, res,
3221                                        !res);
3222                        }
3223                        if (is_rebase_i(opts) && !res)
3224                                record_in_rewritten(&item->commit->object.oid,
3225                                        peek_command(todo_list, 1));
3226                        if (res && is_fixup(item->command)) {
3227                                if (res == 1)
3228                                        intend_to_amend();
3229                                return error_failed_squash(item->commit, opts,
3230                                        item->arg_len, item->arg);
3231                        } else if (res && is_rebase_i(opts) && item->commit)
3232                                return res | error_with_patch(item->commit,
3233                                        item->arg, item->arg_len, opts, res,
3234                                        item->command == TODO_REWORD);
3235                } else if (item->command == TODO_EXEC) {
3236                        char *end_of_arg = (char *)(item->arg + item->arg_len);
3237                        int saved = *end_of_arg;
3238                        struct stat st;
3239
3240                        *end_of_arg = '\0';
3241                        res = do_exec(item->arg);
3242                        *end_of_arg = saved;
3243
3244                        /* Reread the todo file if it has changed. */
3245                        if (res)
3246                                ; /* fall through */
3247                        else if (stat(get_todo_path(opts), &st))
3248                                res = error_errno(_("could not stat '%s'"),
3249                                                  get_todo_path(opts));
3250                        else if (match_stat_data(&todo_list->stat, &st)) {
3251                                todo_list_release(todo_list);
3252                                if (read_populate_todo(todo_list, opts))
3253                                        res = -1; /* message was printed */
3254                                /* `current` will be incremented below */
3255                                todo_list->current = -1;
3256                        }
3257                } else if (item->command == TODO_LABEL) {
3258                        if ((res = do_label(item->arg, item->arg_len)))
3259                                reschedule = 1;
3260                } else if (item->command == TODO_RESET) {
3261                        if ((res = do_reset(item->arg, item->arg_len, opts)))
3262                                reschedule = 1;
3263                } else if (item->command == TODO_MERGE) {
3264                        if ((res = do_merge(item->commit,
3265                                            item->arg, item->arg_len,
3266                                            item->flags, opts)) < 0)
3267                                reschedule = 1;
3268                        else if (item->commit)
3269                                record_in_rewritten(&item->commit->object.oid,
3270                                                    peek_command(todo_list, 1));
3271                        if (res > 0)
3272                                /* failed with merge conflicts */
3273                                return error_with_patch(item->commit,
3274                                                        item->arg,
3275                                                        item->arg_len, opts,
3276                                                        res, 0);
3277                } else if (!is_noop(item->command))
3278                        return error(_("unknown command %d"), item->command);
3279
3280                if (reschedule) {
3281                        advise(_(rescheduled_advice),
3282                               get_item_line_length(todo_list,
3283                                                    todo_list->current),
3284                               get_item_line(todo_list, todo_list->current));
3285                        todo_list->current--;
3286                        if (save_todo(todo_list, opts))
3287                                return -1;
3288                        if (item->commit)
3289                                return error_with_patch(item->commit,
3290                                                        item->arg,
3291                                                        item->arg_len, opts,
3292                                                        res, 0);
3293                }
3294
3295                todo_list->current++;
3296                if (res)
3297                        return res;
3298        }
3299
3300        if (is_rebase_i(opts)) {
3301                struct strbuf head_ref = STRBUF_INIT, buf = STRBUF_INIT;
3302                struct stat st;
3303
3304                /* Stopped in the middle, as planned? */
3305                if (todo_list->current < todo_list->nr)
3306                        return 0;
3307
3308                if (read_oneliner(&head_ref, rebase_path_head_name(), 0) &&
3309                                starts_with(head_ref.buf, "refs/")) {
3310                        const char *msg;
3311                        struct object_id head, orig;
3312                        int res;
3313
3314                        if (get_oid("HEAD", &head)) {
3315                                res = error(_("cannot read HEAD"));
3316cleanup_head_ref:
3317                                strbuf_release(&head_ref);
3318                                strbuf_release(&buf);
3319                                return res;
3320                        }
3321                        if (!read_oneliner(&buf, rebase_path_orig_head(), 0) ||
3322                                        get_oid_hex(buf.buf, &orig)) {
3323                                res = error(_("could not read orig-head"));
3324                                goto cleanup_head_ref;
3325                        }
3326                        strbuf_reset(&buf);
3327                        if (!read_oneliner(&buf, rebase_path_onto(), 0)) {
3328                                res = error(_("could not read 'onto'"));
3329                                goto cleanup_head_ref;
3330                        }
3331                        msg = reflog_message(opts, "finish", "%s onto %s",
3332                                head_ref.buf, buf.buf);
3333                        if (update_ref(msg, head_ref.buf, &head, &orig,
3334                                       REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR)) {
3335                                res = error(_("could not update %s"),
3336                                        head_ref.buf);
3337                                goto cleanup_head_ref;
3338                        }
3339                        msg = reflog_message(opts, "finish", "returning to %s",
3340                                head_ref.buf);
3341                        if (create_symref("HEAD", head_ref.buf, msg)) {
3342                                res = error(_("could not update HEAD to %s"),
3343                                        head_ref.buf);
3344                                goto cleanup_head_ref;
3345                        }
3346                        strbuf_reset(&buf);
3347                }
3348
3349                if (opts->verbose) {
3350                        struct rev_info log_tree_opt;
3351                        struct object_id orig, head;
3352
3353                        memset(&log_tree_opt, 0, sizeof(log_tree_opt));
3354                        init_revisions(&log_tree_opt, NULL);
3355                        log_tree_opt.diff = 1;
3356                        log_tree_opt.diffopt.output_format =
3357                                DIFF_FORMAT_DIFFSTAT;
3358                        log_tree_opt.disable_stdin = 1;
3359
3360                        if (read_oneliner(&buf, rebase_path_orig_head(), 0) &&
3361                            !get_oid(buf.buf, &orig) &&
3362                            !get_oid("HEAD", &head)) {
3363                                diff_tree_oid(&orig, &head, "",
3364                                              &log_tree_opt.diffopt);
3365                                log_tree_diff_flush(&log_tree_opt);
3366                        }
3367                }
3368                flush_rewritten_pending();
3369                if (!stat(rebase_path_rewritten_list(), &st) &&
3370                                st.st_size > 0) {
3371                        struct child_process child = CHILD_PROCESS_INIT;
3372                        const char *post_rewrite_hook =
3373                                find_hook("post-rewrite");
3374
3375                        child.in = open(rebase_path_rewritten_list(), O_RDONLY);
3376                        child.git_cmd = 1;
3377                        argv_array_push(&child.args, "notes");
3378                        argv_array_push(&child.args, "copy");
3379                        argv_array_push(&child.args, "--for-rewrite=rebase");
3380                        /* we don't care if this copying failed */
3381                        run_command(&child);
3382
3383                        if (post_rewrite_hook) {
3384                                struct child_process hook = CHILD_PROCESS_INIT;
3385
3386                                hook.in = open(rebase_path_rewritten_list(),
3387                                        O_RDONLY);
3388                                hook.stdout_to_stderr = 1;
3389                                argv_array_push(&hook.args, post_rewrite_hook);
3390                                argv_array_push(&hook.args, "rebase");
3391                                /* we don't care if this hook failed */
3392                                run_command(&hook);
3393                        }
3394                }
3395                apply_autostash(opts);
3396
3397                fprintf(stderr, "Successfully rebased and updated %s.\n",
3398                        head_ref.buf);
3399
3400                strbuf_release(&buf);
3401                strbuf_release(&head_ref);
3402        }
3403
3404        /*
3405         * Sequence of picks finished successfully; cleanup by
3406         * removing the .git/sequencer directory
3407         */
3408        return sequencer_remove_state(opts);
3409}
3410
3411static int continue_single_pick(void)
3412{
3413        const char *argv[] = { "commit", NULL };
3414
3415        if (!file_exists(git_path_cherry_pick_head()) &&
3416            !file_exists(git_path_revert_head()))
3417                return error(_("no cherry-pick or revert in progress"));
3418        return run_command_v_opt(argv, RUN_GIT_CMD);
3419}
3420
3421static int commit_staged_changes(struct replay_opts *opts,
3422                                 struct todo_list *todo_list)
3423{
3424        unsigned int flags = ALLOW_EMPTY | EDIT_MSG;
3425        unsigned int final_fixup = 0, is_clean;
3426
3427        if (has_unstaged_changes(1))
3428                return error(_("cannot rebase: You have unstaged changes."));
3429
3430        is_clean = !has_uncommitted_changes(0);
3431
3432        if (file_exists(rebase_path_amend())) {
3433                struct strbuf rev = STRBUF_INIT;
3434                struct object_id head, to_amend;
3435
3436                if (get_oid("HEAD", &head))
3437                        return error(_("cannot amend non-existing commit"));
3438                if (!read_oneliner(&rev, rebase_path_amend(), 0))
3439                        return error(_("invalid file: '%s'"), rebase_path_amend());
3440                if (get_oid_hex(rev.buf, &to_amend))
3441                        return error(_("invalid contents: '%s'"),
3442                                rebase_path_amend());
3443                if (!is_clean && oidcmp(&head, &to_amend))
3444                        return error(_("\nYou have uncommitted changes in your "
3445                                       "working tree. Please, commit them\n"
3446                                       "first and then run 'git rebase "
3447                                       "--continue' again."));
3448                /*
3449                 * When skipping a failed fixup/squash, we need to edit the
3450                 * commit message, the current fixup list and count, and if it
3451                 * was the last fixup/squash in the chain, we need to clean up
3452                 * the commit message and if there was a squash, let the user
3453                 * edit it.
3454                 */
3455                if (is_clean && !oidcmp(&head, &to_amend) &&
3456                    opts->current_fixup_count > 0 &&
3457                    file_exists(rebase_path_stopped_sha())) {
3458                        const char *p = opts->current_fixups.buf;
3459                        int len = opts->current_fixups.len;
3460
3461                        opts->current_fixup_count--;
3462                        if (!len)
3463                                BUG("Incorrect current_fixups:\n%s", p);
3464                        while (len && p[len - 1] != '\n')
3465                                len--;
3466                        strbuf_setlen(&opts->current_fixups, len);
3467                        if (write_message(p, len, rebase_path_current_fixups(),
3468                                          0) < 0)
3469                                return error(_("could not write file: '%s'"),
3470                                             rebase_path_current_fixups());
3471
3472                        /*
3473                         * If a fixup/squash in a fixup/squash chain failed, the
3474                         * commit message is already correct, no need to commit
3475                         * it again.
3476                         *
3477                         * Only if it is the final command in the fixup/squash
3478                         * chain, and only if the chain is longer than a single
3479                         * fixup/squash command (which was just skipped), do we
3480                         * actually need to re-commit with a cleaned up commit
3481                         * message.
3482                         */
3483                        if (opts->current_fixup_count > 0 &&
3484                            !is_fixup(peek_command(todo_list, 0))) {
3485                                final_fixup = 1;
3486                                /*
3487                                 * If there was not a single "squash" in the
3488                                 * chain, we only need to clean up the commit
3489                                 * message, no need to bother the user with
3490                                 * opening the commit message in the editor.
3491                                 */
3492                                if (!starts_with(p, "squash ") &&
3493                                    !strstr(p, "\nsquash "))
3494                                        flags = (flags & ~EDIT_MSG) | CLEANUP_MSG;
3495                        } else if (is_fixup(peek_command(todo_list, 0))) {
3496                                /*
3497                                 * We need to update the squash message to skip
3498                                 * the latest commit message.
3499                                 */
3500                                struct commit *commit;
3501                                const char *path = rebase_path_squash_msg();
3502
3503                                if (parse_head(&commit) ||
3504                                    !(p = get_commit_buffer(commit, NULL)) ||
3505                                    write_message(p, strlen(p), path, 0)) {
3506                                        unuse_commit_buffer(commit, p);
3507                                        return error(_("could not write file: "
3508                                                       "'%s'"), path);
3509                                }
3510                                unuse_commit_buffer(commit, p);
3511                        }
3512                }
3513
3514                strbuf_release(&rev);
3515                flags |= AMEND_MSG;
3516        }
3517
3518        if (is_clean) {
3519                const char *cherry_pick_head = git_path_cherry_pick_head();
3520
3521                if (file_exists(cherry_pick_head) && unlink(cherry_pick_head))
3522                        return error(_("could not remove CHERRY_PICK_HEAD"));
3523                if (!final_fixup)
3524                        return 0;
3525        }
3526
3527        if (run_git_commit(final_fixup ? NULL : rebase_path_message(),
3528                           opts, flags))
3529                return error(_("could not commit staged changes."));
3530        unlink(rebase_path_amend());
3531        if (final_fixup) {
3532                unlink(rebase_path_fixup_msg());
3533                unlink(rebase_path_squash_msg());
3534        }
3535        if (opts->current_fixup_count > 0) {
3536                /*
3537                 * Whether final fixup or not, we just cleaned up the commit
3538                 * message...
3539                 */
3540                unlink(rebase_path_current_fixups());
3541                strbuf_reset(&opts->current_fixups);
3542                opts->current_fixup_count = 0;
3543        }
3544        return 0;
3545}
3546
3547int sequencer_continue(struct replay_opts *opts)
3548{
3549        struct todo_list todo_list = TODO_LIST_INIT;
3550        int res;
3551
3552        if (read_and_refresh_cache(opts))
3553                return -1;
3554
3555        if (read_populate_opts(opts))
3556                return -1;
3557        if (is_rebase_i(opts)) {
3558                if ((res = read_populate_todo(&todo_list, opts)))
3559                        goto release_todo_list;
3560                if (commit_staged_changes(opts, &todo_list))
3561                        return -1;
3562        } else if (!file_exists(get_todo_path(opts)))
3563                return continue_single_pick();
3564        else if ((res = read_populate_todo(&todo_list, opts)))
3565                goto release_todo_list;
3566
3567        if (!is_rebase_i(opts)) {
3568                /* Verify that the conflict has been resolved */
3569                if (file_exists(git_path_cherry_pick_head()) ||
3570                    file_exists(git_path_revert_head())) {
3571                        res = continue_single_pick();
3572                        if (res)
3573                                goto release_todo_list;
3574                }
3575                if (index_differs_from("HEAD", NULL, 0)) {
3576                        res = error_dirty_index(opts);
3577                        goto release_todo_list;
3578                }
3579                todo_list.current++;
3580        } else if (file_exists(rebase_path_stopped_sha())) {
3581                struct strbuf buf = STRBUF_INIT;
3582                struct object_id oid;
3583
3584                if (read_oneliner(&buf, rebase_path_stopped_sha(), 1) &&
3585                    !get_oid_committish(buf.buf, &oid))
3586                        record_in_rewritten(&oid, peek_command(&todo_list, 0));
3587                strbuf_release(&buf);
3588        }
3589
3590        res = pick_commits(&todo_list, opts);
3591release_todo_list:
3592        todo_list_release(&todo_list);
3593        return res;
3594}
3595
3596static int single_pick(struct commit *cmit, struct replay_opts *opts)
3597{
3598        setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
3599        return do_pick_commit(opts->action == REPLAY_PICK ?
3600                TODO_PICK : TODO_REVERT, cmit, opts, 0);
3601}
3602
3603int sequencer_pick_revisions(struct replay_opts *opts)
3604{
3605        struct todo_list todo_list = TODO_LIST_INIT;
3606        struct object_id oid;
3607        int i, res;
3608
3609        assert(opts->revs);
3610        if (read_and_refresh_cache(opts))
3611                return -1;
3612
3613        for (i = 0; i < opts->revs->pending.nr; i++) {
3614                struct object_id oid;
3615                const char *name = opts->revs->pending.objects[i].name;
3616
3617                /* This happens when using --stdin. */
3618                if (!strlen(name))
3619                        continue;
3620
3621                if (!get_oid(name, &oid)) {
3622                        if (!lookup_commit_reference_gently(&oid, 1)) {
3623                                enum object_type type = oid_object_info(the_repository,
3624                                                                        &oid,
3625                                                                        NULL);
3626                                return error(_("%s: can't cherry-pick a %s"),
3627                                        name, type_name(type));
3628                        }
3629                } else
3630                        return error(_("%s: bad revision"), name);
3631        }
3632
3633        /*
3634         * If we were called as "git cherry-pick <commit>", just
3635         * cherry-pick/revert it, set CHERRY_PICK_HEAD /
3636         * REVERT_HEAD, and don't touch the sequencer state.
3637         * This means it is possible to cherry-pick in the middle
3638         * of a cherry-pick sequence.
3639         */
3640        if (opts->revs->cmdline.nr == 1 &&
3641            opts->revs->cmdline.rev->whence == REV_CMD_REV &&
3642            opts->revs->no_walk &&
3643            !opts->revs->cmdline.rev->flags) {
3644                struct commit *cmit;
3645                if (prepare_revision_walk(opts->revs))
3646                        return error(_("revision walk setup failed"));
3647                cmit = get_revision(opts->revs);
3648                if (!cmit || get_revision(opts->revs))
3649                        return error("BUG: expected exactly one commit from walk");
3650                return single_pick(cmit, opts);
3651        }
3652
3653        /*
3654         * Start a new cherry-pick/ revert sequence; but
3655         * first, make sure that an existing one isn't in
3656         * progress
3657         */
3658
3659        if (walk_revs_populate_todo(&todo_list, opts) ||
3660                        create_seq_dir() < 0)
3661                return -1;
3662        if (get_oid("HEAD", &oid) && (opts->action == REPLAY_REVERT))
3663                return error(_("can't revert as initial commit"));
3664        if (save_head(oid_to_hex(&oid)))
3665                return -1;
3666        if (save_opts(opts))
3667                return -1;
3668        update_abort_safety_file();
3669        res = pick_commits(&todo_list, opts);
3670        todo_list_release(&todo_list);
3671        return res;
3672}
3673
3674void append_signoff(struct strbuf *msgbuf, int ignore_footer, unsigned flag)
3675{
3676        unsigned no_dup_sob = flag & APPEND_SIGNOFF_DEDUP;
3677        struct strbuf sob = STRBUF_INIT;
3678        int has_footer;
3679
3680        strbuf_addstr(&sob, sign_off_header);
3681        strbuf_addstr(&sob, fmt_name(getenv("GIT_COMMITTER_NAME"),
3682                                getenv("GIT_COMMITTER_EMAIL")));
3683        strbuf_addch(&sob, '\n');
3684
3685        if (!ignore_footer)
3686                strbuf_complete_line(msgbuf);
3687
3688        /*
3689         * If the whole message buffer is equal to the sob, pretend that we
3690         * found a conforming footer with a matching sob
3691         */
3692        if (msgbuf->len - ignore_footer == sob.len &&
3693            !strncmp(msgbuf->buf, sob.buf, sob.len))
3694                has_footer = 3;
3695        else
3696                has_footer = has_conforming_footer(msgbuf, &sob, ignore_footer);
3697
3698        if (!has_footer) {
3699                const char *append_newlines = NULL;
3700                size_t len = msgbuf->len - ignore_footer;
3701
3702                if (!len) {
3703                        /*
3704                         * The buffer is completely empty.  Leave foom for
3705                         * the title and body to be filled in by the user.
3706                         */
3707                        append_newlines = "\n\n";
3708                } else if (len == 1) {
3709                        /*
3710                         * Buffer contains a single newline.  Add another
3711                         * so that we leave room for the title and body.
3712                         */
3713                        append_newlines = "\n";
3714                } else if (msgbuf->buf[len - 2] != '\n') {
3715                        /*
3716                         * Buffer ends with a single newline.  Add another
3717                         * so that there is an empty line between the message
3718                         * body and the sob.
3719                         */
3720                        append_newlines = "\n";
3721                } /* else, the buffer already ends with two newlines. */
3722
3723                if (append_newlines)
3724                        strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
3725                                append_newlines, strlen(append_newlines));
3726        }
3727
3728        if (has_footer != 3 && (!no_dup_sob || has_footer != 2))
3729                strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
3730                                sob.buf, sob.len);
3731
3732        strbuf_release(&sob);
3733}
3734
3735struct labels_entry {
3736        struct hashmap_entry entry;
3737        char label[FLEX_ARRAY];
3738};
3739
3740static int labels_cmp(const void *fndata, const struct labels_entry *a,
3741                      const struct labels_entry *b, const void *key)
3742{
3743        return key ? strcmp(a->label, key) : strcmp(a->label, b->label);
3744}
3745
3746struct string_entry {
3747        struct oidmap_entry entry;
3748        char string[FLEX_ARRAY];
3749};
3750
3751struct label_state {
3752        struct oidmap commit2label;
3753        struct hashmap labels;
3754        struct strbuf buf;
3755};
3756
3757static const char *label_oid(struct object_id *oid, const char *label,
3758                             struct label_state *state)
3759{
3760        struct labels_entry *labels_entry;
3761        struct string_entry *string_entry;
3762        struct object_id dummy;
3763        size_t len;
3764        int i;
3765
3766        string_entry = oidmap_get(&state->commit2label, oid);
3767        if (string_entry)
3768                return string_entry->string;
3769
3770        /*
3771         * For "uninteresting" commits, i.e. commits that are not to be
3772         * rebased, and which can therefore not be labeled, we use a unique
3773         * abbreviation of the commit name. This is slightly more complicated
3774         * than calling find_unique_abbrev() because we also need to make
3775         * sure that the abbreviation does not conflict with any other
3776         * label.
3777         *
3778         * We disallow "interesting" commits to be labeled by a string that
3779         * is a valid full-length hash, to ensure that we always can find an
3780         * abbreviation for any uninteresting commit's names that does not
3781         * clash with any other label.
3782         */
3783        if (!label) {
3784                char *p;
3785
3786                strbuf_reset(&state->buf);
3787                strbuf_grow(&state->buf, GIT_SHA1_HEXSZ);
3788                label = p = state->buf.buf;
3789
3790                find_unique_abbrev_r(p, oid, default_abbrev);
3791
3792                /*
3793                 * We may need to extend the abbreviated hash so that there is
3794                 * no conflicting label.
3795                 */
3796                if (hashmap_get_from_hash(&state->labels, strihash(p), p)) {
3797                        size_t i = strlen(p) + 1;
3798
3799                        oid_to_hex_r(p, oid);
3800                        for (; i < GIT_SHA1_HEXSZ; i++) {
3801                                char save = p[i];
3802                                p[i] = '\0';
3803                                if (!hashmap_get_from_hash(&state->labels,
3804                                                           strihash(p), p))
3805                                        break;
3806                                p[i] = save;
3807                        }
3808                }
3809        } else if (((len = strlen(label)) == the_hash_algo->hexsz &&
3810                    !get_oid_hex(label, &dummy)) ||
3811                   (len == 1 && *label == '#') ||
3812                   hashmap_get_from_hash(&state->labels,
3813                                         strihash(label), label)) {
3814                /*
3815                 * If the label already exists, or if the label is a valid full
3816                 * OID, or the label is a '#' (which we use as a separator
3817                 * between merge heads and oneline), we append a dash and a
3818                 * number to make it unique.
3819                 */
3820                struct strbuf *buf = &state->buf;
3821
3822                strbuf_reset(buf);
3823                strbuf_add(buf, label, len);
3824
3825                for (i = 2; ; i++) {
3826                        strbuf_setlen(buf, len);
3827                        strbuf_addf(buf, "-%d", i);
3828                        if (!hashmap_get_from_hash(&state->labels,
3829                                                   strihash(buf->buf),
3830                                                   buf->buf))
3831                                break;
3832                }
3833
3834                label = buf->buf;
3835        }
3836
3837        FLEX_ALLOC_STR(labels_entry, label, label);
3838        hashmap_entry_init(labels_entry, strihash(label));
3839        hashmap_add(&state->labels, labels_entry);
3840
3841        FLEX_ALLOC_STR(string_entry, string, label);
3842        oidcpy(&string_entry->entry.oid, oid);
3843        oidmap_put(&state->commit2label, string_entry);
3844
3845        return string_entry->string;
3846}
3847
3848static int make_script_with_merges(struct pretty_print_context *pp,
3849                                   struct rev_info *revs, FILE *out,
3850                                   unsigned flags)
3851{
3852        int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
3853        int rebase_cousins = flags & TODO_LIST_REBASE_COUSINS;
3854        struct strbuf buf = STRBUF_INIT, oneline = STRBUF_INIT;
3855        struct strbuf label = STRBUF_INIT;
3856        struct commit_list *commits = NULL, **tail = &commits, *iter;
3857        struct commit_list *tips = NULL, **tips_tail = &tips;
3858        struct commit *commit;
3859        struct oidmap commit2todo = OIDMAP_INIT;
3860        struct string_entry *entry;
3861        struct oidset interesting = OIDSET_INIT, child_seen = OIDSET_INIT,
3862                shown = OIDSET_INIT;
3863        struct label_state state = { OIDMAP_INIT, { NULL }, STRBUF_INIT };
3864
3865        int abbr = flags & TODO_LIST_ABBREVIATE_CMDS;
3866        const char *cmd_pick = abbr ? "p" : "pick",
3867                *cmd_label = abbr ? "l" : "label",
3868                *cmd_reset = abbr ? "t" : "reset",
3869                *cmd_merge = abbr ? "m" : "merge";
3870
3871        oidmap_init(&commit2todo, 0);
3872        oidmap_init(&state.commit2label, 0);
3873        hashmap_init(&state.labels, (hashmap_cmp_fn) labels_cmp, NULL, 0);
3874        strbuf_init(&state.buf, 32);
3875
3876        if (revs->cmdline.nr && (revs->cmdline.rev[0].flags & BOTTOM)) {
3877                struct object_id *oid = &revs->cmdline.rev[0].item->oid;
3878                FLEX_ALLOC_STR(entry, string, "onto");
3879                oidcpy(&entry->entry.oid, oid);
3880                oidmap_put(&state.commit2label, entry);
3881        }
3882
3883        /*
3884         * First phase:
3885         * - get onelines for all commits
3886         * - gather all branch tips (i.e. 2nd or later parents of merges)
3887         * - label all branch tips
3888         */
3889        while ((commit = get_revision(revs))) {
3890                struct commit_list *to_merge;
3891                int is_octopus;
3892                const char *p1, *p2;
3893                struct object_id *oid;
3894                int is_empty;
3895
3896                tail = &commit_list_insert(commit, tail)->next;
3897                oidset_insert(&interesting, &commit->object.oid);
3898
3899                is_empty = is_original_commit_empty(commit);
3900                if (!is_empty && (commit->object.flags & PATCHSAME))
3901                        continue;
3902
3903                strbuf_reset(&oneline);
3904                pretty_print_commit(pp, commit, &oneline);
3905
3906                to_merge = commit->parents ? commit->parents->next : NULL;
3907                if (!to_merge) {
3908                        /* non-merge commit: easy case */
3909                        strbuf_reset(&buf);
3910                        if (!keep_empty && is_empty)
3911                                strbuf_addf(&buf, "%c ", comment_line_char);
3912                        strbuf_addf(&buf, "%s %s %s", cmd_pick,
3913                                    oid_to_hex(&commit->object.oid),
3914                                    oneline.buf);
3915
3916                        FLEX_ALLOC_STR(entry, string, buf.buf);
3917                        oidcpy(&entry->entry.oid, &commit->object.oid);
3918                        oidmap_put(&commit2todo, entry);
3919
3920                        continue;
3921                }
3922
3923                is_octopus = to_merge && to_merge->next;
3924
3925                if (is_octopus)
3926                        BUG("Octopus merges not yet supported");
3927
3928                /* Create a label */
3929                strbuf_reset(&label);
3930                if (skip_prefix(oneline.buf, "Merge ", &p1) &&
3931                    (p1 = strchr(p1, '\'')) &&
3932                    (p2 = strchr(++p1, '\'')))
3933                        strbuf_add(&label, p1, p2 - p1);
3934                else if (skip_prefix(oneline.buf, "Merge pull request ",
3935                                     &p1) &&
3936                         (p1 = strstr(p1, " from ")))
3937                        strbuf_addstr(&label, p1 + strlen(" from "));
3938                else
3939                        strbuf_addbuf(&label, &oneline);
3940
3941                for (p1 = label.buf; *p1; p1++)
3942                        if (isspace(*p1))
3943                                *(char *)p1 = '-';
3944
3945                strbuf_reset(&buf);
3946                strbuf_addf(&buf, "%s -C %s",
3947                            cmd_merge, oid_to_hex(&commit->object.oid));
3948
3949                /* label the tip of merged branch */
3950                oid = &to_merge->item->object.oid;
3951                strbuf_addch(&buf, ' ');
3952
3953                if (!oidset_contains(&interesting, oid))
3954                        strbuf_addstr(&buf, label_oid(oid, NULL, &state));
3955                else {
3956                        tips_tail = &commit_list_insert(to_merge->item,
3957                                                        tips_tail)->next;
3958
3959                        strbuf_addstr(&buf, label_oid(oid, label.buf, &state));
3960                }
3961                strbuf_addf(&buf, " # %s", oneline.buf);
3962
3963                FLEX_ALLOC_STR(entry, string, buf.buf);
3964                oidcpy(&entry->entry.oid, &commit->object.oid);
3965                oidmap_put(&commit2todo, entry);
3966        }
3967
3968        /*
3969         * Second phase:
3970         * - label branch points
3971         * - add HEAD to the branch tips
3972         */
3973        for (iter = commits; iter; iter = iter->next) {
3974                struct commit_list *parent = iter->item->parents;
3975                for (; parent; parent = parent->next) {
3976                        struct object_id *oid = &parent->item->object.oid;
3977                        if (!oidset_contains(&interesting, oid))
3978                                continue;
3979                        if (!oidset_contains(&child_seen, oid))
3980                                oidset_insert(&child_seen, oid);
3981                        else
3982                                label_oid(oid, "branch-point", &state);
3983                }
3984
3985                /* Add HEAD as implict "tip of branch" */
3986                if (!iter->next)
3987                        tips_tail = &commit_list_insert(iter->item,
3988                                                        tips_tail)->next;
3989        }
3990
3991        /*
3992         * Third phase: output the todo list. This is a bit tricky, as we
3993         * want to avoid jumping back and forth between revisions. To
3994         * accomplish that goal, we walk backwards from the branch tips,
3995         * gathering commits not yet shown, reversing the list on the fly,
3996         * then outputting that list (labeling revisions as needed).
3997         */
3998        fprintf(out, "%s onto\n", cmd_label);
3999        for (iter = tips; iter; iter = iter->next) {
4000                struct commit_list *list = NULL, *iter2;
4001
4002                commit = iter->item;
4003                if (oidset_contains(&shown, &commit->object.oid))
4004                        continue;
4005                entry = oidmap_get(&state.commit2label, &commit->object.oid);
4006
4007                if (entry)
4008                        fprintf(out, "\n# Branch %s\n", entry->string);
4009                else
4010                        fprintf(out, "\n");
4011
4012                while (oidset_contains(&interesting, &commit->object.oid) &&
4013                       !oidset_contains(&shown, &commit->object.oid)) {
4014                        commit_list_insert(commit, &list);
4015                        if (!commit->parents) {
4016                                commit = NULL;
4017                                break;
4018                        }
4019                        commit = commit->parents->item;
4020                }
4021
4022                if (!commit)
4023                        fprintf(out, "%s %s\n", cmd_reset,
4024                                rebase_cousins ? "onto" : "[new root]");
4025                else {
4026                        const char *to = NULL;
4027
4028                        entry = oidmap_get(&state.commit2label,
4029                                           &commit->object.oid);
4030                        if (entry)
4031                                to = entry->string;
4032                        else if (!rebase_cousins)
4033                                to = label_oid(&commit->object.oid, NULL,
4034                                               &state);
4035
4036                        if (!to || !strcmp(to, "onto"))
4037                                fprintf(out, "%s onto\n", cmd_reset);
4038                        else {
4039                                strbuf_reset(&oneline);
4040                                pretty_print_commit(pp, commit, &oneline);
4041                                fprintf(out, "%s %s # %s\n",
4042                                        cmd_reset, to, oneline.buf);
4043                        }
4044                }
4045
4046                for (iter2 = list; iter2; iter2 = iter2->next) {
4047                        struct object_id *oid = &iter2->item->object.oid;
4048                        entry = oidmap_get(&commit2todo, oid);
4049                        /* only show if not already upstream */
4050                        if (entry)
4051                                fprintf(out, "%s\n", entry->string);
4052                        entry = oidmap_get(&state.commit2label, oid);
4053                        if (entry)
4054                                fprintf(out, "%s %s\n",
4055                                        cmd_label, entry->string);
4056                        oidset_insert(&shown, oid);
4057                }
4058
4059                free_commit_list(list);
4060        }
4061
4062        free_commit_list(commits);
4063        free_commit_list(tips);
4064
4065        strbuf_release(&label);
4066        strbuf_release(&oneline);
4067        strbuf_release(&buf);
4068
4069        oidmap_free(&commit2todo, 1);
4070        oidmap_free(&state.commit2label, 1);
4071        hashmap_free(&state.labels, 1);
4072        strbuf_release(&state.buf);
4073
4074        return 0;
4075}
4076
4077int sequencer_make_script(FILE *out, int argc, const char **argv,
4078                          unsigned flags)
4079{
4080        char *format = NULL;
4081        struct pretty_print_context pp = {0};
4082        struct strbuf buf = STRBUF_INIT;
4083        struct rev_info revs;
4084        struct commit *commit;
4085        int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
4086        const char *insn = flags & TODO_LIST_ABBREVIATE_CMDS ? "p" : "pick";
4087        int rebase_merges = flags & TODO_LIST_REBASE_MERGES;
4088
4089        init_revisions(&revs, NULL);
4090        revs.verbose_header = 1;
4091        if (!rebase_merges)
4092                revs.max_parents = 1;
4093        revs.cherry_mark = 1;
4094        revs.limited = 1;
4095        revs.reverse = 1;
4096        revs.right_only = 1;
4097        revs.sort_order = REV_SORT_IN_GRAPH_ORDER;
4098        revs.topo_order = 1;
4099
4100        revs.pretty_given = 1;
4101        git_config_get_string("rebase.instructionFormat", &format);
4102        if (!format || !*format) {
4103                free(format);
4104                format = xstrdup("%s");
4105        }
4106        get_commit_format(format, &revs);
4107        free(format);
4108        pp.fmt = revs.commit_format;
4109        pp.output_encoding = get_log_output_encoding();
4110
4111        if (setup_revisions(argc, argv, &revs, NULL) > 1)
4112                return error(_("make_script: unhandled options"));
4113
4114        if (prepare_revision_walk(&revs) < 0)
4115                return error(_("make_script: error preparing revisions"));
4116
4117        if (rebase_merges)
4118                return make_script_with_merges(&pp, &revs, out, flags);
4119
4120        while ((commit = get_revision(&revs))) {
4121                int is_empty  = is_original_commit_empty(commit);
4122
4123                if (!is_empty && (commit->object.flags & PATCHSAME))
4124                        continue;
4125                strbuf_reset(&buf);
4126                if (!keep_empty && is_empty)
4127                        strbuf_addf(&buf, "%c ", comment_line_char);
4128                strbuf_addf(&buf, "%s %s ", insn,
4129                            oid_to_hex(&commit->object.oid));
4130                pretty_print_commit(&pp, commit, &buf);
4131                strbuf_addch(&buf, '\n');
4132                fputs(buf.buf, out);
4133        }
4134        strbuf_release(&buf);
4135        return 0;
4136}
4137
4138/*
4139 * Add commands after pick and (series of) squash/fixup commands
4140 * in the todo list.
4141 */
4142int sequencer_add_exec_commands(const char *commands)
4143{
4144        const char *todo_file = rebase_path_todo();
4145        struct todo_list todo_list = TODO_LIST_INIT;
4146        struct todo_item *item;
4147        struct strbuf *buf = &todo_list.buf;
4148        size_t offset = 0, commands_len = strlen(commands);
4149        int i, first;
4150
4151        if (strbuf_read_file(&todo_list.buf, todo_file, 0) < 0)
4152                return error(_("could not read '%s'."), todo_file);
4153
4154        if (parse_insn_buffer(todo_list.buf.buf, &todo_list)) {
4155                todo_list_release(&todo_list);
4156                return error(_("unusable todo list: '%s'"), todo_file);
4157        }
4158
4159        first = 1;
4160        /* insert <commands> before every pick except the first one */
4161        for (item = todo_list.items, i = 0; i < todo_list.nr; i++, item++) {
4162                if (item->command == TODO_PICK && !first) {
4163                        strbuf_insert(buf, item->offset_in_buf + offset,
4164                                      commands, commands_len);
4165                        offset += commands_len;
4166                }
4167                first = 0;
4168        }
4169
4170        /* append final <commands> */
4171        strbuf_add(buf, commands, commands_len);
4172
4173        i = write_message(buf->buf, buf->len, todo_file, 0);
4174        todo_list_release(&todo_list);
4175        return i;
4176}
4177
4178int transform_todos(unsigned flags)
4179{
4180        const char *todo_file = rebase_path_todo();
4181        struct todo_list todo_list = TODO_LIST_INIT;
4182        struct strbuf buf = STRBUF_INIT;
4183        struct todo_item *item;
4184        int i;
4185
4186        if (strbuf_read_file(&todo_list.buf, todo_file, 0) < 0)
4187                return error(_("could not read '%s'."), todo_file);
4188
4189        if (parse_insn_buffer(todo_list.buf.buf, &todo_list)) {
4190                todo_list_release(&todo_list);
4191                return error(_("unusable todo list: '%s'"), todo_file);
4192        }
4193
4194        for (item = todo_list.items, i = 0; i < todo_list.nr; i++, item++) {
4195                /* if the item is not a command write it and continue */
4196                if (item->command >= TODO_COMMENT) {
4197                        strbuf_addf(&buf, "%.*s\n", item->arg_len, item->arg);
4198                        continue;
4199                }
4200
4201                /* add command to the buffer */
4202                if (flags & TODO_LIST_ABBREVIATE_CMDS)
4203                        strbuf_addch(&buf, command_to_char(item->command));
4204                else
4205                        strbuf_addstr(&buf, command_to_string(item->command));
4206
4207                /* add commit id */
4208                if (item->commit) {
4209                        const char *oid = flags & TODO_LIST_SHORTEN_IDS ?
4210                                          short_commit_name(item->commit) :
4211                                          oid_to_hex(&item->commit->object.oid);
4212
4213                        if (item->command == TODO_MERGE) {
4214                                if (item->flags & TODO_EDIT_MERGE_MSG)
4215                                        strbuf_addstr(&buf, " -c");
4216                                else
4217                                        strbuf_addstr(&buf, " -C");
4218                        }
4219
4220                        strbuf_addf(&buf, " %s", oid);
4221                }
4222
4223                /* add all the rest */
4224                if (!item->arg_len)
4225                        strbuf_addch(&buf, '\n');
4226                else
4227                        strbuf_addf(&buf, " %.*s\n", item->arg_len, item->arg);
4228        }
4229
4230        i = write_message(buf.buf, buf.len, todo_file, 0);
4231        todo_list_release(&todo_list);
4232        return i;
4233}
4234
4235enum check_level {
4236        CHECK_IGNORE = 0, CHECK_WARN, CHECK_ERROR
4237};
4238
4239static enum check_level get_missing_commit_check_level(void)
4240{
4241        const char *value;
4242
4243        if (git_config_get_value("rebase.missingcommitscheck", &value) ||
4244                        !strcasecmp("ignore", value))
4245                return CHECK_IGNORE;
4246        if (!strcasecmp("warn", value))
4247                return CHECK_WARN;
4248        if (!strcasecmp("error", value))
4249                return CHECK_ERROR;
4250        warning(_("unrecognized setting %s for option "
4251                  "rebase.missingCommitsCheck. Ignoring."), value);
4252        return CHECK_IGNORE;
4253}
4254
4255/*
4256 * Check if the user dropped some commits by mistake
4257 * Behaviour determined by rebase.missingCommitsCheck.
4258 * Check if there is an unrecognized command or a
4259 * bad SHA-1 in a command.
4260 */
4261int check_todo_list(void)
4262{
4263        enum check_level check_level = get_missing_commit_check_level();
4264        struct strbuf todo_file = STRBUF_INIT;
4265        struct todo_list todo_list = TODO_LIST_INIT;
4266        struct strbuf missing = STRBUF_INIT;
4267        int advise_to_edit_todo = 0, res = 0, i;
4268
4269        strbuf_addstr(&todo_file, rebase_path_todo());
4270        if (strbuf_read_file_or_whine(&todo_list.buf, todo_file.buf) < 0) {
4271                res = -1;
4272                goto leave_check;
4273        }
4274        advise_to_edit_todo = res =
4275                parse_insn_buffer(todo_list.buf.buf, &todo_list);
4276
4277        if (res || check_level == CHECK_IGNORE)
4278                goto leave_check;
4279
4280        /* Mark the commits in git-rebase-todo as seen */
4281        for (i = 0; i < todo_list.nr; i++) {
4282                struct commit *commit = todo_list.items[i].commit;
4283                if (commit)
4284                        commit->util = (void *)1;
4285        }
4286
4287        todo_list_release(&todo_list);
4288        strbuf_addstr(&todo_file, ".backup");
4289        if (strbuf_read_file_or_whine(&todo_list.buf, todo_file.buf) < 0) {
4290                res = -1;
4291                goto leave_check;
4292        }
4293        strbuf_release(&todo_file);
4294        res = !!parse_insn_buffer(todo_list.buf.buf, &todo_list);
4295
4296        /* Find commits in git-rebase-todo.backup yet unseen */
4297        for (i = todo_list.nr - 1; i >= 0; i--) {
4298                struct todo_item *item = todo_list.items + i;
4299                struct commit *commit = item->commit;
4300                if (commit && !commit->util) {
4301                        strbuf_addf(&missing, " - %s %.*s\n",
4302                                    short_commit_name(commit),
4303                                    item->arg_len, item->arg);
4304                        commit->util = (void *)1;
4305                }
4306        }
4307
4308        /* Warn about missing commits */
4309        if (!missing.len)
4310                goto leave_check;
4311
4312        if (check_level == CHECK_ERROR)
4313                advise_to_edit_todo = res = 1;
4314
4315        fprintf(stderr,
4316                _("Warning: some commits may have been dropped accidentally.\n"
4317                "Dropped commits (newer to older):\n"));
4318
4319        /* Make the list user-friendly and display */
4320        fputs(missing.buf, stderr);
4321        strbuf_release(&missing);
4322
4323        fprintf(stderr, _("To avoid this message, use \"drop\" to "
4324                "explicitly remove a commit.\n\n"
4325                "Use 'git config rebase.missingCommitsCheck' to change "
4326                "the level of warnings.\n"
4327                "The possible behaviours are: ignore, warn, error.\n\n"));
4328
4329leave_check:
4330        strbuf_release(&todo_file);
4331        todo_list_release(&todo_list);
4332
4333        if (advise_to_edit_todo)
4334                fprintf(stderr,
4335                        _("You can fix this with 'git rebase --edit-todo' "
4336                          "and then run 'git rebase --continue'.\n"
4337                          "Or you can abort the rebase with 'git rebase"
4338                          " --abort'.\n"));
4339
4340        return res;
4341}
4342
4343static int rewrite_file(const char *path, const char *buf, size_t len)
4344{
4345        int rc = 0;
4346        int fd = open(path, O_WRONLY | O_TRUNC);
4347        if (fd < 0)
4348                return error_errno(_("could not open '%s' for writing"), path);
4349        if (write_in_full(fd, buf, len) < 0)
4350                rc = error_errno(_("could not write to '%s'"), path);
4351        if (close(fd) && !rc)
4352                rc = error_errno(_("could not close '%s'"), path);
4353        return rc;
4354}
4355
4356/* skip picking commits whose parents are unchanged */
4357int skip_unnecessary_picks(void)
4358{
4359        const char *todo_file = rebase_path_todo();
4360        struct strbuf buf = STRBUF_INIT;
4361        struct todo_list todo_list = TODO_LIST_INIT;
4362        struct object_id onto_oid, *oid = &onto_oid, *parent_oid;
4363        int fd, i;
4364
4365        if (!read_oneliner(&buf, rebase_path_onto(), 0))
4366                return error(_("could not read 'onto'"));
4367        if (get_oid(buf.buf, &onto_oid)) {
4368                strbuf_release(&buf);
4369                return error(_("need a HEAD to fixup"));
4370        }
4371        strbuf_release(&buf);
4372
4373        if (strbuf_read_file_or_whine(&todo_list.buf, todo_file) < 0)
4374                return -1;
4375        if (parse_insn_buffer(todo_list.buf.buf, &todo_list) < 0) {
4376                todo_list_release(&todo_list);
4377                return -1;
4378        }
4379
4380        for (i = 0; i < todo_list.nr; i++) {
4381                struct todo_item *item = todo_list.items + i;
4382
4383                if (item->command >= TODO_NOOP)
4384                        continue;
4385                if (item->command != TODO_PICK)
4386                        break;
4387                if (parse_commit(item->commit)) {
4388                        todo_list_release(&todo_list);
4389                        return error(_("could not parse commit '%s'"),
4390                                oid_to_hex(&item->commit->object.oid));
4391                }
4392                if (!item->commit->parents)
4393                        break; /* root commit */
4394                if (item->commit->parents->next)
4395                        break; /* merge commit */
4396                parent_oid = &item->commit->parents->item->object.oid;
4397                if (hashcmp(parent_oid->hash, oid->hash))
4398                        break;
4399                oid = &item->commit->object.oid;
4400        }
4401        if (i > 0) {
4402                int offset = get_item_line_offset(&todo_list, i);
4403                const char *done_path = rebase_path_done();
4404
4405                fd = open(done_path, O_CREAT | O_WRONLY | O_APPEND, 0666);
4406                if (fd < 0) {
4407                        error_errno(_("could not open '%s' for writing"),
4408                                    done_path);
4409                        todo_list_release(&todo_list);
4410                        return -1;
4411                }
4412                if (write_in_full(fd, todo_list.buf.buf, offset) < 0) {
4413                        error_errno(_("could not write to '%s'"), done_path);
4414                        todo_list_release(&todo_list);
4415                        close(fd);
4416                        return -1;
4417                }
4418                close(fd);
4419
4420                if (rewrite_file(rebase_path_todo(), todo_list.buf.buf + offset,
4421                                 todo_list.buf.len - offset) < 0) {
4422                        todo_list_release(&todo_list);
4423                        return -1;
4424                }
4425
4426                todo_list.current = i;
4427                if (is_fixup(peek_command(&todo_list, 0)))
4428                        record_in_rewritten(oid, peek_command(&todo_list, 0));
4429        }
4430
4431        todo_list_release(&todo_list);
4432        printf("%s\n", oid_to_hex(oid));
4433
4434        return 0;
4435}
4436
4437struct subject2item_entry {
4438        struct hashmap_entry entry;
4439        int i;
4440        char subject[FLEX_ARRAY];
4441};
4442
4443static int subject2item_cmp(const void *fndata,
4444                            const struct subject2item_entry *a,
4445                            const struct subject2item_entry *b, const void *key)
4446{
4447        return key ? strcmp(a->subject, key) : strcmp(a->subject, b->subject);
4448}
4449
4450/*
4451 * Rearrange the todo list that has both "pick commit-id msg" and "pick
4452 * commit-id fixup!/squash! msg" in it so that the latter is put immediately
4453 * after the former, and change "pick" to "fixup"/"squash".
4454 *
4455 * Note that if the config has specified a custom instruction format, each log
4456 * message will have to be retrieved from the commit (as the oneline in the
4457 * script cannot be trusted) in order to normalize the autosquash arrangement.
4458 */
4459int rearrange_squash(void)
4460{
4461        const char *todo_file = rebase_path_todo();
4462        struct todo_list todo_list = TODO_LIST_INIT;
4463        struct hashmap subject2item;
4464        int res = 0, rearranged = 0, *next, *tail, i;
4465        char **subjects;
4466
4467        if (strbuf_read_file_or_whine(&todo_list.buf, todo_file) < 0)
4468                return -1;
4469        if (parse_insn_buffer(todo_list.buf.buf, &todo_list) < 0) {
4470                todo_list_release(&todo_list);
4471                return -1;
4472        }
4473
4474        /*
4475         * The hashmap maps onelines to the respective todo list index.
4476         *
4477         * If any items need to be rearranged, the next[i] value will indicate
4478         * which item was moved directly after the i'th.
4479         *
4480         * In that case, last[i] will indicate the index of the latest item to
4481         * be moved to appear after the i'th.
4482         */
4483        hashmap_init(&subject2item, (hashmap_cmp_fn) subject2item_cmp,
4484                     NULL, todo_list.nr);
4485        ALLOC_ARRAY(next, todo_list.nr);
4486        ALLOC_ARRAY(tail, todo_list.nr);
4487        ALLOC_ARRAY(subjects, todo_list.nr);
4488        for (i = 0; i < todo_list.nr; i++) {
4489                struct strbuf buf = STRBUF_INIT;
4490                struct todo_item *item = todo_list.items + i;
4491                const char *commit_buffer, *subject, *p;
4492                size_t subject_len;
4493                int i2 = -1;
4494                struct subject2item_entry *entry;
4495
4496                next[i] = tail[i] = -1;
4497                if (!item->commit || item->command == TODO_DROP) {
4498                        subjects[i] = NULL;
4499                        continue;
4500                }
4501
4502                if (is_fixup(item->command)) {
4503                        todo_list_release(&todo_list);
4504                        return error(_("the script was already rearranged."));
4505                }
4506
4507                item->commit->util = item;
4508
4509                parse_commit(item->commit);
4510                commit_buffer = get_commit_buffer(item->commit, NULL);
4511                find_commit_subject(commit_buffer, &subject);
4512                format_subject(&buf, subject, " ");
4513                subject = subjects[i] = strbuf_detach(&buf, &subject_len);
4514                unuse_commit_buffer(item->commit, commit_buffer);
4515                if ((skip_prefix(subject, "fixup! ", &p) ||
4516                     skip_prefix(subject, "squash! ", &p))) {
4517                        struct commit *commit2;
4518
4519                        for (;;) {
4520                                while (isspace(*p))
4521                                        p++;
4522                                if (!skip_prefix(p, "fixup! ", &p) &&
4523                                    !skip_prefix(p, "squash! ", &p))
4524                                        break;
4525                        }
4526
4527                        if ((entry = hashmap_get_from_hash(&subject2item,
4528                                                           strhash(p), p)))
4529                                /* found by title */
4530                                i2 = entry->i;
4531                        else if (!strchr(p, ' ') &&
4532                                 (commit2 =
4533                                  lookup_commit_reference_by_name(p)) &&
4534                                 commit2->util)
4535                                /* found by commit name */
4536                                i2 = (struct todo_item *)commit2->util
4537                                        - todo_list.items;
4538                        else {
4539                                /* copy can be a prefix of the commit subject */
4540                                for (i2 = 0; i2 < i; i2++)
4541                                        if (subjects[i2] &&
4542                                            starts_with(subjects[i2], p))
4543                                                break;
4544                                if (i2 == i)
4545                                        i2 = -1;
4546                        }
4547                }
4548                if (i2 >= 0) {
4549                        rearranged = 1;
4550                        todo_list.items[i].command =
4551                                starts_with(subject, "fixup!") ?
4552                                TODO_FIXUP : TODO_SQUASH;
4553                        if (next[i2] < 0)
4554                                next[i2] = i;
4555                        else
4556                                next[tail[i2]] = i;
4557                        tail[i2] = i;
4558                } else if (!hashmap_get_from_hash(&subject2item,
4559                                                strhash(subject), subject)) {
4560                        FLEX_ALLOC_MEM(entry, subject, subject, subject_len);
4561                        entry->i = i;
4562                        hashmap_entry_init(entry, strhash(entry->subject));
4563                        hashmap_put(&subject2item, entry);
4564                }
4565        }
4566
4567        if (rearranged) {
4568                struct strbuf buf = STRBUF_INIT;
4569
4570                for (i = 0; i < todo_list.nr; i++) {
4571                        enum todo_command command = todo_list.items[i].command;
4572                        int cur = i;
4573
4574                        /*
4575                         * Initially, all commands are 'pick's. If it is a
4576                         * fixup or a squash now, we have rearranged it.
4577                         */
4578                        if (is_fixup(command))
4579                                continue;
4580
4581                        while (cur >= 0) {
4582                                const char *bol =
4583                                        get_item_line(&todo_list, cur);
4584                                const char *eol =
4585                                        get_item_line(&todo_list, cur + 1);
4586
4587                                /* replace 'pick', by 'fixup' or 'squash' */
4588                                command = todo_list.items[cur].command;
4589                                if (is_fixup(command)) {
4590                                        strbuf_addstr(&buf,
4591                                                todo_command_info[command].str);
4592                                        bol += strcspn(bol, " \t");
4593                                }
4594
4595                                strbuf_add(&buf, bol, eol - bol);
4596
4597                                cur = next[cur];
4598                        }
4599                }
4600
4601                res = rewrite_file(todo_file, buf.buf, buf.len);
4602                strbuf_release(&buf);
4603        }
4604
4605        free(next);
4606        free(tail);
4607        for (i = 0; i < todo_list.nr; i++)
4608                free(subjects[i]);
4609        free(subjects);
4610        hashmap_free(&subject2item, 1);
4611        todo_list_release(&todo_list);
4612
4613        return res;
4614}