a9e0ad49fb1707077ba5261877d8f40d705ab2f4
   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
  27#define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
  28
  29const char sign_off_header[] = "Signed-off-by: ";
  30static const char cherry_picked_prefix[] = "(cherry picked from commit ";
  31
  32GIT_PATH_FUNC(git_path_seq_dir, "sequencer")
  33
  34static GIT_PATH_FUNC(git_path_todo_file, "sequencer/todo")
  35static GIT_PATH_FUNC(git_path_opts_file, "sequencer/opts")
  36static GIT_PATH_FUNC(git_path_head_file, "sequencer/head")
  37static GIT_PATH_FUNC(git_path_abort_safety_file, "sequencer/abort-safety")
  38
  39static GIT_PATH_FUNC(rebase_path, "rebase-merge")
  40/*
  41 * The file containing rebase commands, comments, and empty lines.
  42 * This file is created by "git rebase -i" then edited by the user. As
  43 * the lines are processed, they are removed from the front of this
  44 * file and written to the tail of 'done'.
  45 */
  46static GIT_PATH_FUNC(rebase_path_todo, "rebase-merge/git-rebase-todo")
  47/*
  48 * The rebase command lines that have already been processed. A line
  49 * is moved here when it is first handled, before any associated user
  50 * actions.
  51 */
  52static GIT_PATH_FUNC(rebase_path_done, "rebase-merge/done")
  53/*
  54 * The file to keep track of how many commands were already processed (e.g.
  55 * for the prompt).
  56 */
  57static GIT_PATH_FUNC(rebase_path_msgnum, "rebase-merge/msgnum");
  58/*
  59 * The file to keep track of how many commands are to be processed in total
  60 * (e.g. for the prompt).
  61 */
  62static GIT_PATH_FUNC(rebase_path_msgtotal, "rebase-merge/end");
  63/*
  64 * The commit message that is planned to be used for any changes that
  65 * need to be committed following a user interaction.
  66 */
  67static GIT_PATH_FUNC(rebase_path_message, "rebase-merge/message")
  68/*
  69 * The file into which is accumulated the suggested commit message for
  70 * squash/fixup commands. When the first of a series of squash/fixups
  71 * is seen, the file is created and the commit message from the
  72 * previous commit and from the first squash/fixup commit are written
  73 * to it. The commit message for each subsequent squash/fixup commit
  74 * is appended to the file as it is processed.
  75 *
  76 * The first line of the file is of the form
  77 *     # This is a combination of $count commits.
  78 * where $count is the number of commits whose messages have been
  79 * written to the file so far (including the initial "pick" commit).
  80 * Each time that a commit message is processed, this line is read and
  81 * updated. It is deleted just before the combined commit is made.
  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 * A script to set the GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL, and
  94 * GIT_AUTHOR_DATE that will be used for the commit that is currently
  95 * being rebased.
  96 */
  97static GIT_PATH_FUNC(rebase_path_author_script, "rebase-merge/author-script")
  98/*
  99 * When an "edit" rebase command is being processed, the SHA1 of the
 100 * commit to be edited is recorded in this file.  When "git rebase
 101 * --continue" is executed, if there are any staged changes then they
 102 * will be amended to the HEAD commit, but only provided the HEAD
 103 * commit is still the commit to be edited.  When any other rebase
 104 * command is processed, this file is deleted.
 105 */
 106static GIT_PATH_FUNC(rebase_path_amend, "rebase-merge/amend")
 107/*
 108 * When we stop at a given patch via the "edit" command, this file contains
 109 * the abbreviated commit name of the corresponding patch.
 110 */
 111static GIT_PATH_FUNC(rebase_path_stopped_sha, "rebase-merge/stopped-sha")
 112/*
 113 * For the post-rewrite hook, we make a list of rewritten commits and
 114 * their new sha1s.  The rewritten-pending list keeps the sha1s of
 115 * commits that have been processed, but not committed yet,
 116 * e.g. because they are waiting for a 'squash' command.
 117 */
 118static GIT_PATH_FUNC(rebase_path_rewritten_list, "rebase-merge/rewritten-list")
 119static GIT_PATH_FUNC(rebase_path_rewritten_pending,
 120        "rebase-merge/rewritten-pending")
 121/*
 122 * The following files are written by git-rebase just after parsing the
 123 * command-line (and are only consumed, not modified, by the sequencer).
 124 */
 125static GIT_PATH_FUNC(rebase_path_gpg_sign_opt, "rebase-merge/gpg_sign_opt")
 126static GIT_PATH_FUNC(rebase_path_orig_head, "rebase-merge/orig-head")
 127static GIT_PATH_FUNC(rebase_path_verbose, "rebase-merge/verbose")
 128static GIT_PATH_FUNC(rebase_path_head_name, "rebase-merge/head-name")
 129static GIT_PATH_FUNC(rebase_path_onto, "rebase-merge/onto")
 130static GIT_PATH_FUNC(rebase_path_autostash, "rebase-merge/autostash")
 131static GIT_PATH_FUNC(rebase_path_strategy, "rebase-merge/strategy")
 132static GIT_PATH_FUNC(rebase_path_strategy_opts, "rebase-merge/strategy_opts")
 133static GIT_PATH_FUNC(rebase_path_allow_rerere_autoupdate, "rebase-merge/allow_rerere_autoupdate")
 134
 135static inline int is_rebase_i(const struct replay_opts *opts)
 136{
 137        return opts->action == REPLAY_INTERACTIVE_REBASE;
 138}
 139
 140static const char *get_dir(const struct replay_opts *opts)
 141{
 142        if (is_rebase_i(opts))
 143                return rebase_path();
 144        return git_path_seq_dir();
 145}
 146
 147static const char *get_todo_path(const struct replay_opts *opts)
 148{
 149        if (is_rebase_i(opts))
 150                return rebase_path_todo();
 151        return git_path_todo_file();
 152}
 153
 154/*
 155 * Returns 0 for non-conforming footer
 156 * Returns 1 for conforming footer
 157 * Returns 2 when sob exists within conforming footer
 158 * Returns 3 when sob exists within conforming footer as last entry
 159 */
 160static int has_conforming_footer(struct strbuf *sb, struct strbuf *sob,
 161        int ignore_footer)
 162{
 163        struct trailer_info info;
 164        int i;
 165        int found_sob = 0, found_sob_last = 0;
 166
 167        trailer_info_get(&info, sb->buf);
 168
 169        if (info.trailer_start == info.trailer_end)
 170                return 0;
 171
 172        for (i = 0; i < info.trailer_nr; i++)
 173                if (sob && !strncmp(info.trailers[i], sob->buf, sob->len)) {
 174                        found_sob = 1;
 175                        if (i == info.trailer_nr - 1)
 176                                found_sob_last = 1;
 177                }
 178
 179        trailer_info_release(&info);
 180
 181        if (found_sob_last)
 182                return 3;
 183        if (found_sob)
 184                return 2;
 185        return 1;
 186}
 187
 188static const char *gpg_sign_opt_quoted(struct replay_opts *opts)
 189{
 190        static struct strbuf buf = STRBUF_INIT;
 191
 192        strbuf_reset(&buf);
 193        if (opts->gpg_sign)
 194                sq_quotef(&buf, "-S%s", opts->gpg_sign);
 195        return buf.buf;
 196}
 197
 198int sequencer_remove_state(struct replay_opts *opts)
 199{
 200        struct strbuf dir = STRBUF_INIT;
 201        int i;
 202
 203        free(opts->gpg_sign);
 204        free(opts->strategy);
 205        for (i = 0; i < opts->xopts_nr; i++)
 206                free(opts->xopts[i]);
 207        free(opts->xopts);
 208
 209        strbuf_addstr(&dir, get_dir(opts));
 210        remove_dir_recursively(&dir, 0);
 211        strbuf_release(&dir);
 212
 213        return 0;
 214}
 215
 216static const char *action_name(const struct replay_opts *opts)
 217{
 218        switch (opts->action) {
 219        case REPLAY_REVERT:
 220                return N_("revert");
 221        case REPLAY_PICK:
 222                return N_("cherry-pick");
 223        case REPLAY_INTERACTIVE_REBASE:
 224                return N_("rebase -i");
 225        }
 226        die(_("Unknown action: %d"), opts->action);
 227}
 228
 229struct commit_message {
 230        char *parent_label;
 231        char *label;
 232        char *subject;
 233        const char *message;
 234};
 235
 236static const char *short_commit_name(struct commit *commit)
 237{
 238        return find_unique_abbrev(commit->object.oid.hash, DEFAULT_ABBREV);
 239}
 240
 241static int get_message(struct commit *commit, struct commit_message *out)
 242{
 243        const char *abbrev, *subject;
 244        int subject_len;
 245
 246        out->message = logmsg_reencode(commit, NULL, get_commit_output_encoding());
 247        abbrev = short_commit_name(commit);
 248
 249        subject_len = find_commit_subject(out->message, &subject);
 250
 251        out->subject = xmemdupz(subject, subject_len);
 252        out->label = xstrfmt("%s... %s", abbrev, out->subject);
 253        out->parent_label = xstrfmt("parent of %s", out->label);
 254
 255        return 0;
 256}
 257
 258static void free_message(struct commit *commit, struct commit_message *msg)
 259{
 260        free(msg->parent_label);
 261        free(msg->label);
 262        free(msg->subject);
 263        unuse_commit_buffer(commit, msg->message);
 264}
 265
 266static void print_advice(int show_hint, struct replay_opts *opts)
 267{
 268        char *msg = getenv("GIT_CHERRY_PICK_HELP");
 269
 270        if (msg) {
 271                fprintf(stderr, "%s\n", msg);
 272                /*
 273                 * A conflict has occurred but the porcelain
 274                 * (typically rebase --interactive) wants to take care
 275                 * of the commit itself so remove CHERRY_PICK_HEAD
 276                 */
 277                unlink(git_path_cherry_pick_head());
 278                return;
 279        }
 280
 281        if (show_hint) {
 282                if (opts->no_commit)
 283                        advise(_("after resolving the conflicts, mark the corrected paths\n"
 284                                 "with 'git add <paths>' or 'git rm <paths>'"));
 285                else
 286                        advise(_("after resolving the conflicts, mark the corrected paths\n"
 287                                 "with 'git add <paths>' or 'git rm <paths>'\n"
 288                                 "and commit the result with 'git commit'"));
 289        }
 290}
 291
 292static int write_message(const void *buf, size_t len, const char *filename,
 293                         int append_eol)
 294{
 295        static struct lock_file msg_file;
 296
 297        int msg_fd = hold_lock_file_for_update(&msg_file, filename, 0);
 298        if (msg_fd < 0)
 299                return error_errno(_("could not lock '%s'"), filename);
 300        if (write_in_full(msg_fd, buf, len) < 0) {
 301                rollback_lock_file(&msg_file);
 302                return error_errno(_("could not write to '%s'"), filename);
 303        }
 304        if (append_eol && write(msg_fd, "\n", 1) < 0) {
 305                rollback_lock_file(&msg_file);
 306                return error_errno(_("could not write eol to '%s'"), filename);
 307        }
 308        if (commit_lock_file(&msg_file) < 0) {
 309                rollback_lock_file(&msg_file);
 310                return error(_("failed to finalize '%s'."), filename);
 311        }
 312
 313        return 0;
 314}
 315
 316/*
 317 * Reads a file that was presumably written by a shell script, i.e. with an
 318 * end-of-line marker that needs to be stripped.
 319 *
 320 * Note that only the last end-of-line marker is stripped, consistent with the
 321 * behavior of "$(cat path)" in a shell script.
 322 *
 323 * Returns 1 if the file was read, 0 if it could not be read or does not exist.
 324 */
 325static int read_oneliner(struct strbuf *buf,
 326        const char *path, int skip_if_empty)
 327{
 328        int orig_len = buf->len;
 329
 330        if (!file_exists(path))
 331                return 0;
 332
 333        if (strbuf_read_file(buf, path, 0) < 0) {
 334                warning_errno(_("could not read '%s'"), path);
 335                return 0;
 336        }
 337
 338        if (buf->len > orig_len && buf->buf[buf->len - 1] == '\n') {
 339                if (--buf->len > orig_len && buf->buf[buf->len - 1] == '\r')
 340                        --buf->len;
 341                buf->buf[buf->len] = '\0';
 342        }
 343
 344        if (skip_if_empty && buf->len == orig_len)
 345                return 0;
 346
 347        return 1;
 348}
 349
 350static struct tree *empty_tree(void)
 351{
 352        return lookup_tree(&empty_tree_oid);
 353}
 354
 355static int error_dirty_index(struct replay_opts *opts)
 356{
 357        if (read_cache_unmerged())
 358                return error_resolve_conflict(_(action_name(opts)));
 359
 360        error(_("your local changes would be overwritten by %s."),
 361                _(action_name(opts)));
 362
 363        if (advice_commit_before_merge)
 364                advise(_("commit your changes or stash them to proceed."));
 365        return -1;
 366}
 367
 368static void update_abort_safety_file(void)
 369{
 370        struct object_id head;
 371
 372        /* Do nothing on a single-pick */
 373        if (!file_exists(git_path_seq_dir()))
 374                return;
 375
 376        if (!get_oid("HEAD", &head))
 377                write_file(git_path_abort_safety_file(), "%s", oid_to_hex(&head));
 378        else
 379                write_file(git_path_abort_safety_file(), "%s", "");
 380}
 381
 382static int fast_forward_to(const struct object_id *to, const struct object_id *from,
 383                        int unborn, struct replay_opts *opts)
 384{
 385        struct ref_transaction *transaction;
 386        struct strbuf sb = STRBUF_INIT;
 387        struct strbuf err = STRBUF_INIT;
 388
 389        read_cache();
 390        if (checkout_fast_forward(from, to, 1))
 391                return -1; /* the callee should have complained already */
 392
 393        strbuf_addf(&sb, _("%s: fast-forward"), _(action_name(opts)));
 394
 395        transaction = ref_transaction_begin(&err);
 396        if (!transaction ||
 397            ref_transaction_update(transaction, "HEAD",
 398                                   to, unborn ? &null_oid : from,
 399                                   0, sb.buf, &err) ||
 400            ref_transaction_commit(transaction, &err)) {
 401                ref_transaction_free(transaction);
 402                error("%s", err.buf);
 403                strbuf_release(&sb);
 404                strbuf_release(&err);
 405                return -1;
 406        }
 407
 408        strbuf_release(&sb);
 409        strbuf_release(&err);
 410        ref_transaction_free(transaction);
 411        update_abort_safety_file();
 412        return 0;
 413}
 414
 415void append_conflicts_hint(struct strbuf *msgbuf)
 416{
 417        int i;
 418
 419        strbuf_addch(msgbuf, '\n');
 420        strbuf_commented_addf(msgbuf, "Conflicts:\n");
 421        for (i = 0; i < active_nr;) {
 422                const struct cache_entry *ce = active_cache[i++];
 423                if (ce_stage(ce)) {
 424                        strbuf_commented_addf(msgbuf, "\t%s\n", ce->name);
 425                        while (i < active_nr && !strcmp(ce->name,
 426                                                        active_cache[i]->name))
 427                                i++;
 428                }
 429        }
 430}
 431
 432static int do_recursive_merge(struct commit *base, struct commit *next,
 433                              const char *base_label, const char *next_label,
 434                              struct object_id *head, struct strbuf *msgbuf,
 435                              struct replay_opts *opts)
 436{
 437        struct merge_options o;
 438        struct tree *result, *next_tree, *base_tree, *head_tree;
 439        int clean;
 440        char **xopt;
 441        static struct lock_file index_lock;
 442
 443        hold_locked_index(&index_lock, LOCK_DIE_ON_ERROR);
 444
 445        read_cache();
 446
 447        init_merge_options(&o);
 448        o.ancestor = base ? base_label : "(empty tree)";
 449        o.branch1 = "HEAD";
 450        o.branch2 = next ? next_label : "(empty tree)";
 451        if (is_rebase_i(opts))
 452                o.buffer_output = 2;
 453
 454        head_tree = parse_tree_indirect(head);
 455        next_tree = next ? next->tree : empty_tree();
 456        base_tree = base ? base->tree : empty_tree();
 457
 458        for (xopt = opts->xopts; xopt != opts->xopts + opts->xopts_nr; xopt++)
 459                parse_merge_opt(&o, *xopt);
 460
 461        clean = merge_trees(&o,
 462                            head_tree,
 463                            next_tree, base_tree, &result);
 464        if (is_rebase_i(opts) && clean <= 0)
 465                fputs(o.obuf.buf, stdout);
 466        strbuf_release(&o.obuf);
 467        if (clean < 0)
 468                return clean;
 469
 470        if (active_cache_changed &&
 471            write_locked_index(&the_index, &index_lock, COMMIT_LOCK))
 472                /*
 473                 * TRANSLATORS: %s will be "revert", "cherry-pick" or
 474                 * "rebase -i".
 475                 */
 476                return error(_("%s: Unable to write new index file"),
 477                        _(action_name(opts)));
 478        rollback_lock_file(&index_lock);
 479
 480        if (!clean)
 481                append_conflicts_hint(msgbuf);
 482
 483        return !clean;
 484}
 485
 486static int is_index_unchanged(void)
 487{
 488        struct object_id head_oid;
 489        struct commit *head_commit;
 490
 491        if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, &head_oid, NULL))
 492                return error(_("could not resolve HEAD commit\n"));
 493
 494        head_commit = lookup_commit(&head_oid);
 495
 496        /*
 497         * If head_commit is NULL, check_commit, called from
 498         * lookup_commit, would have indicated that head_commit is not
 499         * a commit object already.  parse_commit() will return failure
 500         * without further complaints in such a case.  Otherwise, if
 501         * the commit is invalid, parse_commit() will complain.  So
 502         * there is nothing for us to say here.  Just return failure.
 503         */
 504        if (parse_commit(head_commit))
 505                return -1;
 506
 507        if (!active_cache_tree)
 508                active_cache_tree = cache_tree();
 509
 510        if (!cache_tree_fully_valid(active_cache_tree))
 511                if (cache_tree_update(&the_index, 0))
 512                        return error(_("unable to update cache tree\n"));
 513
 514        return !oidcmp(&active_cache_tree->oid,
 515                       &head_commit->tree->object.oid);
 516}
 517
 518static int write_author_script(const char *message)
 519{
 520        struct strbuf buf = STRBUF_INIT;
 521        const char *eol;
 522        int res;
 523
 524        for (;;)
 525                if (!*message || starts_with(message, "\n")) {
 526missing_author:
 527                        /* Missing 'author' line? */
 528                        unlink(rebase_path_author_script());
 529                        return 0;
 530                } else if (skip_prefix(message, "author ", &message))
 531                        break;
 532                else if ((eol = strchr(message, '\n')))
 533                        message = eol + 1;
 534                else
 535                        goto missing_author;
 536
 537        strbuf_addstr(&buf, "GIT_AUTHOR_NAME='");
 538        while (*message && *message != '\n' && *message != '\r')
 539                if (skip_prefix(message, " <", &message))
 540                        break;
 541                else if (*message != '\'')
 542                        strbuf_addch(&buf, *(message++));
 543                else
 544                        strbuf_addf(&buf, "'\\\\%c'", *(message++));
 545        strbuf_addstr(&buf, "'\nGIT_AUTHOR_EMAIL='");
 546        while (*message && *message != '\n' && *message != '\r')
 547                if (skip_prefix(message, "> ", &message))
 548                        break;
 549                else if (*message != '\'')
 550                        strbuf_addch(&buf, *(message++));
 551                else
 552                        strbuf_addf(&buf, "'\\\\%c'", *(message++));
 553        strbuf_addstr(&buf, "'\nGIT_AUTHOR_DATE='@");
 554        while (*message && *message != '\n' && *message != '\r')
 555                if (*message != '\'')
 556                        strbuf_addch(&buf, *(message++));
 557                else
 558                        strbuf_addf(&buf, "'\\\\%c'", *(message++));
 559        res = write_message(buf.buf, buf.len, rebase_path_author_script(), 1);
 560        strbuf_release(&buf);
 561        return res;
 562}
 563
 564/*
 565 * Read a list of environment variable assignments (such as the author-script
 566 * file) into an environment block. Returns -1 on error, 0 otherwise.
 567 */
 568static int read_env_script(struct argv_array *env)
 569{
 570        struct strbuf script = STRBUF_INIT;
 571        int i, count = 0;
 572        char *p, *p2;
 573
 574        if (strbuf_read_file(&script, rebase_path_author_script(), 256) <= 0)
 575                return -1;
 576
 577        for (p = script.buf; *p; p++)
 578                if (skip_prefix(p, "'\\\\''", (const char **)&p2))
 579                        strbuf_splice(&script, p - script.buf, p2 - p, "'", 1);
 580                else if (*p == '\'')
 581                        strbuf_splice(&script, p-- - script.buf, 1, "", 0);
 582                else if (*p == '\n') {
 583                        *p = '\0';
 584                        count++;
 585                }
 586
 587        for (i = 0, p = script.buf; i < count; i++) {
 588                argv_array_push(env, p);
 589                p += strlen(p) + 1;
 590        }
 591
 592        return 0;
 593}
 594
 595static const char staged_changes_advice[] =
 596N_("you have staged changes in your working tree\n"
 597"If these changes are meant to be squashed into the previous commit, run:\n"
 598"\n"
 599"  git commit --amend %s\n"
 600"\n"
 601"If they are meant to go into a new commit, run:\n"
 602"\n"
 603"  git commit %s\n"
 604"\n"
 605"In both cases, once you're done, continue with:\n"
 606"\n"
 607"  git rebase --continue\n");
 608
 609#define ALLOW_EMPTY (1<<0)
 610#define EDIT_MSG    (1<<1)
 611#define AMEND_MSG   (1<<2)
 612#define CLEANUP_MSG (1<<3)
 613#define VERIFY_MSG  (1<<4)
 614
 615/*
 616 * If we are cherry-pick, and if the merge did not result in
 617 * hand-editing, we will hit this commit and inherit the original
 618 * author date and name.
 619 *
 620 * If we are revert, or if our cherry-pick results in a hand merge,
 621 * we had better say that the current user is responsible for that.
 622 *
 623 * An exception is when run_git_commit() is called during an
 624 * interactive rebase: in that case, we will want to retain the
 625 * author metadata.
 626 */
 627static int run_git_commit(const char *defmsg, struct replay_opts *opts,
 628                          unsigned int flags)
 629{
 630        struct child_process cmd = CHILD_PROCESS_INIT;
 631        const char *value;
 632
 633        cmd.git_cmd = 1;
 634
 635        if (is_rebase_i(opts)) {
 636                if (!(flags & EDIT_MSG)) {
 637                        cmd.stdout_to_stderr = 1;
 638                        cmd.err = -1;
 639                }
 640
 641                if (read_env_script(&cmd.env_array)) {
 642                        const char *gpg_opt = gpg_sign_opt_quoted(opts);
 643
 644                        return error(_(staged_changes_advice),
 645                                     gpg_opt, gpg_opt);
 646                }
 647        }
 648
 649        argv_array_push(&cmd.args, "commit");
 650
 651        if (!(flags & VERIFY_MSG))
 652                argv_array_push(&cmd.args, "-n");
 653        if ((flags & AMEND_MSG))
 654                argv_array_push(&cmd.args, "--amend");
 655        if (opts->gpg_sign)
 656                argv_array_pushf(&cmd.args, "-S%s", opts->gpg_sign);
 657        if (defmsg)
 658                argv_array_pushl(&cmd.args, "-F", defmsg, NULL);
 659        if ((flags & CLEANUP_MSG))
 660                argv_array_push(&cmd.args, "--cleanup=strip");
 661        if ((flags & EDIT_MSG))
 662                argv_array_push(&cmd.args, "-e");
 663        else if (!(flags & CLEANUP_MSG) &&
 664                 !opts->signoff && !opts->record_origin &&
 665                 git_config_get_value("commit.cleanup", &value))
 666                argv_array_push(&cmd.args, "--cleanup=verbatim");
 667
 668        if ((flags & ALLOW_EMPTY))
 669                argv_array_push(&cmd.args, "--allow-empty");
 670
 671        if (opts->allow_empty_message)
 672                argv_array_push(&cmd.args, "--allow-empty-message");
 673
 674        if (cmd.err == -1) {
 675                /* hide stderr on success */
 676                struct strbuf buf = STRBUF_INIT;
 677                int rc = pipe_command(&cmd,
 678                                      NULL, 0,
 679                                      /* stdout is already redirected */
 680                                      NULL, 0,
 681                                      &buf, 0);
 682                if (rc)
 683                        fputs(buf.buf, stderr);
 684                strbuf_release(&buf);
 685                return rc;
 686        }
 687
 688        return run_command(&cmd);
 689}
 690
 691static int rest_is_empty(const struct strbuf *sb, int start)
 692{
 693        int i, eol;
 694        const char *nl;
 695
 696        /* Check if the rest is just whitespace and Signed-off-by's. */
 697        for (i = start; i < sb->len; i++) {
 698                nl = memchr(sb->buf + i, '\n', sb->len - i);
 699                if (nl)
 700                        eol = nl - sb->buf;
 701                else
 702                        eol = sb->len;
 703
 704                if (strlen(sign_off_header) <= eol - i &&
 705                    starts_with(sb->buf + i, sign_off_header)) {
 706                        i = eol;
 707                        continue;
 708                }
 709                while (i < eol)
 710                        if (!isspace(sb->buf[i++]))
 711                                return 0;
 712        }
 713
 714        return 1;
 715}
 716
 717/*
 718 * Find out if the message in the strbuf contains only whitespace and
 719 * Signed-off-by lines.
 720 */
 721int message_is_empty(const struct strbuf *sb,
 722                     enum commit_msg_cleanup_mode cleanup_mode)
 723{
 724        if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
 725                return 0;
 726        return rest_is_empty(sb, 0);
 727}
 728
 729/*
 730 * See if the user edited the message in the editor or left what
 731 * was in the template intact
 732 */
 733int template_untouched(const struct strbuf *sb, const char *template_file,
 734                       enum commit_msg_cleanup_mode cleanup_mode)
 735{
 736        struct strbuf tmpl = STRBUF_INIT;
 737        const char *start;
 738
 739        if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
 740                return 0;
 741
 742        if (!template_file || strbuf_read_file(&tmpl, template_file, 0) <= 0)
 743                return 0;
 744
 745        strbuf_stripspace(&tmpl, cleanup_mode == COMMIT_MSG_CLEANUP_ALL);
 746        if (!skip_prefix(sb->buf, tmpl.buf, &start))
 747                start = sb->buf;
 748        strbuf_release(&tmpl);
 749        return rest_is_empty(sb, start - sb->buf);
 750}
 751
 752int update_head_with_reflog(const struct commit *old_head,
 753                            const struct object_id *new_head,
 754                            const char *action, const struct strbuf *msg,
 755                            struct strbuf *err)
 756{
 757        struct ref_transaction *transaction;
 758        struct strbuf sb = STRBUF_INIT;
 759        const char *nl;
 760        int ret = 0;
 761
 762        if (action) {
 763                strbuf_addstr(&sb, action);
 764                strbuf_addstr(&sb, ": ");
 765        }
 766
 767        nl = strchr(msg->buf, '\n');
 768        if (nl) {
 769                strbuf_add(&sb, msg->buf, nl + 1 - msg->buf);
 770        } else {
 771                strbuf_addbuf(&sb, msg);
 772                strbuf_addch(&sb, '\n');
 773        }
 774
 775        transaction = ref_transaction_begin(err);
 776        if (!transaction ||
 777            ref_transaction_update(transaction, "HEAD", new_head,
 778                                   old_head ? &old_head->object.oid : &null_oid,
 779                                   0, sb.buf, err) ||
 780            ref_transaction_commit(transaction, err)) {
 781                ret = -1;
 782        }
 783        ref_transaction_free(transaction);
 784        strbuf_release(&sb);
 785
 786        return ret;
 787}
 788
 789static int run_rewrite_hook(const struct object_id *oldoid,
 790                            const struct object_id *newoid)
 791{
 792        struct child_process proc = CHILD_PROCESS_INIT;
 793        const char *argv[3];
 794        int code;
 795        struct strbuf sb = STRBUF_INIT;
 796
 797        argv[0] = find_hook("post-rewrite");
 798        if (!argv[0])
 799                return 0;
 800
 801        argv[1] = "amend";
 802        argv[2] = NULL;
 803
 804        proc.argv = argv;
 805        proc.in = -1;
 806        proc.stdout_to_stderr = 1;
 807
 808        code = start_command(&proc);
 809        if (code)
 810                return code;
 811        strbuf_addf(&sb, "%s %s\n", oid_to_hex(oldoid), oid_to_hex(newoid));
 812        sigchain_push(SIGPIPE, SIG_IGN);
 813        write_in_full(proc.in, sb.buf, sb.len);
 814        close(proc.in);
 815        strbuf_release(&sb);
 816        sigchain_pop(SIGPIPE);
 817        return finish_command(&proc);
 818}
 819
 820void commit_post_rewrite(const struct commit *old_head,
 821                         const struct object_id *new_head)
 822{
 823        struct notes_rewrite_cfg *cfg;
 824
 825        cfg = init_copy_notes_for_rewrite("amend");
 826        if (cfg) {
 827                /* we are amending, so old_head is not NULL */
 828                copy_note_for_rewrite(cfg, &old_head->object.oid, new_head);
 829                finish_copy_notes_for_rewrite(cfg, "Notes added by 'git commit --amend'");
 830        }
 831        run_rewrite_hook(&old_head->object.oid, new_head);
 832}
 833
 834static const char implicit_ident_advice_noconfig[] =
 835N_("Your name and email address were configured automatically based\n"
 836"on your username and hostname. Please check that they are accurate.\n"
 837"You can suppress this message by setting them explicitly. Run the\n"
 838"following command and follow the instructions in your editor to edit\n"
 839"your configuration file:\n"
 840"\n"
 841"    git config --global --edit\n"
 842"\n"
 843"After doing this, you may fix the identity used for this commit with:\n"
 844"\n"
 845"    git commit --amend --reset-author\n");
 846
 847static const char implicit_ident_advice_config[] =
 848N_("Your name and email address were configured automatically based\n"
 849"on your username and hostname. Please check that they are accurate.\n"
 850"You can suppress this message by setting them explicitly:\n"
 851"\n"
 852"    git config --global user.name \"Your Name\"\n"
 853"    git config --global user.email you@example.com\n"
 854"\n"
 855"After doing this, you may fix the identity used for this commit with:\n"
 856"\n"
 857"    git commit --amend --reset-author\n");
 858
 859static const char *implicit_ident_advice(void)
 860{
 861        char *user_config = expand_user_path("~/.gitconfig", 0);
 862        char *xdg_config = xdg_config_home("config");
 863        int config_exists = file_exists(user_config) || file_exists(xdg_config);
 864
 865        free(user_config);
 866        free(xdg_config);
 867
 868        if (config_exists)
 869                return _(implicit_ident_advice_config);
 870        else
 871                return _(implicit_ident_advice_noconfig);
 872
 873}
 874
 875void print_commit_summary(const char *prefix, const struct object_id *oid,
 876                          unsigned int flags)
 877{
 878        struct rev_info rev;
 879        struct commit *commit;
 880        struct strbuf format = STRBUF_INIT;
 881        const char *head;
 882        struct pretty_print_context pctx = {0};
 883        struct strbuf author_ident = STRBUF_INIT;
 884        struct strbuf committer_ident = STRBUF_INIT;
 885
 886        commit = lookup_commit(oid);
 887        if (!commit)
 888                die(_("couldn't look up newly created commit"));
 889        if (parse_commit(commit))
 890                die(_("could not parse newly created commit"));
 891
 892        strbuf_addstr(&format, "format:%h] %s");
 893
 894        format_commit_message(commit, "%an <%ae>", &author_ident, &pctx);
 895        format_commit_message(commit, "%cn <%ce>", &committer_ident, &pctx);
 896        if (strbuf_cmp(&author_ident, &committer_ident)) {
 897                strbuf_addstr(&format, "\n Author: ");
 898                strbuf_addbuf_percentquote(&format, &author_ident);
 899        }
 900        if (flags & SUMMARY_SHOW_AUTHOR_DATE) {
 901                struct strbuf date = STRBUF_INIT;
 902
 903                format_commit_message(commit, "%ad", &date, &pctx);
 904                strbuf_addstr(&format, "\n Date: ");
 905                strbuf_addbuf_percentquote(&format, &date);
 906                strbuf_release(&date);
 907        }
 908        if (!committer_ident_sufficiently_given()) {
 909                strbuf_addstr(&format, "\n Committer: ");
 910                strbuf_addbuf_percentquote(&format, &committer_ident);
 911                if (advice_implicit_identity) {
 912                        strbuf_addch(&format, '\n');
 913                        strbuf_addstr(&format, implicit_ident_advice());
 914                }
 915        }
 916        strbuf_release(&author_ident);
 917        strbuf_release(&committer_ident);
 918
 919        init_revisions(&rev, prefix);
 920        setup_revisions(0, NULL, &rev, NULL);
 921
 922        rev.diff = 1;
 923        rev.diffopt.output_format =
 924                DIFF_FORMAT_SHORTSTAT | DIFF_FORMAT_SUMMARY;
 925
 926        rev.verbose_header = 1;
 927        rev.show_root_diff = 1;
 928        get_commit_format(format.buf, &rev);
 929        rev.always_show_header = 0;
 930        rev.diffopt.detect_rename = 1;
 931        rev.diffopt.break_opt = 0;
 932        diff_setup_done(&rev.diffopt);
 933
 934        head = resolve_ref_unsafe("HEAD", 0, NULL, NULL);
 935        if (!head)
 936                die_errno(_("unable to resolve HEAD after creating commit"));
 937        if (!strcmp(head, "HEAD"))
 938                head = _("detached HEAD");
 939        else
 940                skip_prefix(head, "refs/heads/", &head);
 941        printf("[%s%s ", head, (flags & SUMMARY_INITIAL_COMMIT) ?
 942                                                _(" (root-commit)") : "");
 943
 944        if (!log_tree_commit(&rev, commit)) {
 945                rev.always_show_header = 1;
 946                rev.use_terminator = 1;
 947                log_tree_commit(&rev, commit);
 948        }
 949
 950        strbuf_release(&format);
 951}
 952
 953static int is_original_commit_empty(struct commit *commit)
 954{
 955        const struct object_id *ptree_oid;
 956
 957        if (parse_commit(commit))
 958                return error(_("could not parse commit %s\n"),
 959                             oid_to_hex(&commit->object.oid));
 960        if (commit->parents) {
 961                struct commit *parent = commit->parents->item;
 962                if (parse_commit(parent))
 963                        return error(_("could not parse parent commit %s\n"),
 964                                oid_to_hex(&parent->object.oid));
 965                ptree_oid = &parent->tree->object.oid;
 966        } else {
 967                ptree_oid = &empty_tree_oid; /* commit is root */
 968        }
 969
 970        return !oidcmp(ptree_oid, &commit->tree->object.oid);
 971}
 972
 973/*
 974 * Do we run "git commit" with "--allow-empty"?
 975 */
 976static int allow_empty(struct replay_opts *opts, struct commit *commit)
 977{
 978        int index_unchanged, empty_commit;
 979
 980        /*
 981         * Three cases:
 982         *
 983         * (1) we do not allow empty at all and error out.
 984         *
 985         * (2) we allow ones that were initially empty, but
 986         * forbid the ones that become empty;
 987         *
 988         * (3) we allow both.
 989         */
 990        if (!opts->allow_empty)
 991                return 0; /* let "git commit" barf as necessary */
 992
 993        index_unchanged = is_index_unchanged();
 994        if (index_unchanged < 0)
 995                return index_unchanged;
 996        if (!index_unchanged)
 997                return 0; /* we do not have to say --allow-empty */
 998
 999        if (opts->keep_redundant_commits)
1000                return 1;
1001
1002        empty_commit = is_original_commit_empty(commit);
1003        if (empty_commit < 0)
1004                return empty_commit;
1005        if (!empty_commit)
1006                return 0;
1007        else
1008                return 1;
1009}
1010
1011/*
1012 * Note that ordering matters in this enum. Not only must it match the mapping
1013 * below, it is also divided into several sections that matter.  When adding
1014 * new commands, make sure you add it in the right section.
1015 */
1016enum todo_command {
1017        /* commands that handle commits */
1018        TODO_PICK = 0,
1019        TODO_REVERT,
1020        TODO_EDIT,
1021        TODO_REWORD,
1022        TODO_FIXUP,
1023        TODO_SQUASH,
1024        /* commands that do something else than handling a single commit */
1025        TODO_EXEC,
1026        /* commands that do nothing but are counted for reporting progress */
1027        TODO_NOOP,
1028        TODO_DROP,
1029        /* comments (not counted for reporting progress) */
1030        TODO_COMMENT
1031};
1032
1033static struct {
1034        char c;
1035        const char *str;
1036} todo_command_info[] = {
1037        { 'p', "pick" },
1038        { 0,   "revert" },
1039        { 'e', "edit" },
1040        { 'r', "reword" },
1041        { 'f', "fixup" },
1042        { 's', "squash" },
1043        { 'x', "exec" },
1044        { 0,   "noop" },
1045        { 'd', "drop" },
1046        { 0,   NULL }
1047};
1048
1049static const char *command_to_string(const enum todo_command command)
1050{
1051        if (command < TODO_COMMENT)
1052                return todo_command_info[command].str;
1053        die("Unknown command: %d", command);
1054}
1055
1056static int is_noop(const enum todo_command command)
1057{
1058        return TODO_NOOP <= command;
1059}
1060
1061static int is_fixup(enum todo_command command)
1062{
1063        return command == TODO_FIXUP || command == TODO_SQUASH;
1064}
1065
1066static int update_squash_messages(enum todo_command command,
1067                struct commit *commit, struct replay_opts *opts)
1068{
1069        struct strbuf buf = STRBUF_INIT;
1070        int count, res;
1071        const char *message, *body;
1072
1073        if (file_exists(rebase_path_squash_msg())) {
1074                struct strbuf header = STRBUF_INIT;
1075                char *eol, *p;
1076
1077                if (strbuf_read_file(&buf, rebase_path_squash_msg(), 2048) <= 0)
1078                        return error(_("could not read '%s'"),
1079                                rebase_path_squash_msg());
1080
1081                p = buf.buf + 1;
1082                eol = strchrnul(buf.buf, '\n');
1083                if (buf.buf[0] != comment_line_char ||
1084                    (p += strcspn(p, "0123456789\n")) == eol)
1085                        return error(_("unexpected 1st line of squash message:"
1086                                       "\n\n\t%.*s"),
1087                                     (int)(eol - buf.buf), buf.buf);
1088                count = strtol(p, NULL, 10);
1089
1090                if (count < 1)
1091                        return error(_("invalid 1st line of squash message:\n"
1092                                       "\n\t%.*s"),
1093                                     (int)(eol - buf.buf), buf.buf);
1094
1095                strbuf_addf(&header, "%c ", comment_line_char);
1096                strbuf_addf(&header,
1097                            _("This is a combination of %d commits."), ++count);
1098                strbuf_splice(&buf, 0, eol - buf.buf, header.buf, header.len);
1099                strbuf_release(&header);
1100        } else {
1101                struct object_id head;
1102                struct commit *head_commit;
1103                const char *head_message, *body;
1104
1105                if (get_oid("HEAD", &head))
1106                        return error(_("need a HEAD to fixup"));
1107                if (!(head_commit = lookup_commit_reference(&head)))
1108                        return error(_("could not read HEAD"));
1109                if (!(head_message = get_commit_buffer(head_commit, NULL)))
1110                        return error(_("could not read HEAD's commit message"));
1111
1112                find_commit_subject(head_message, &body);
1113                if (write_message(body, strlen(body),
1114                                  rebase_path_fixup_msg(), 0)) {
1115                        unuse_commit_buffer(head_commit, head_message);
1116                        return error(_("cannot write '%s'"),
1117                                     rebase_path_fixup_msg());
1118                }
1119
1120                count = 2;
1121                strbuf_addf(&buf, "%c ", comment_line_char);
1122                strbuf_addf(&buf, _("This is a combination of %d commits."),
1123                            count);
1124                strbuf_addf(&buf, "\n%c ", comment_line_char);
1125                strbuf_addstr(&buf, _("This is the 1st commit message:"));
1126                strbuf_addstr(&buf, "\n\n");
1127                strbuf_addstr(&buf, body);
1128
1129                unuse_commit_buffer(head_commit, head_message);
1130        }
1131
1132        if (!(message = get_commit_buffer(commit, NULL)))
1133                return error(_("could not read commit message of %s"),
1134                             oid_to_hex(&commit->object.oid));
1135        find_commit_subject(message, &body);
1136
1137        if (command == TODO_SQUASH) {
1138                unlink(rebase_path_fixup_msg());
1139                strbuf_addf(&buf, "\n%c ", comment_line_char);
1140                strbuf_addf(&buf, _("This is the commit message #%d:"), count);
1141                strbuf_addstr(&buf, "\n\n");
1142                strbuf_addstr(&buf, body);
1143        } else if (command == TODO_FIXUP) {
1144                strbuf_addf(&buf, "\n%c ", comment_line_char);
1145                strbuf_addf(&buf, _("The commit message #%d will be skipped:"),
1146                            count);
1147                strbuf_addstr(&buf, "\n\n");
1148                strbuf_add_commented_lines(&buf, body, strlen(body));
1149        } else
1150                return error(_("unknown command: %d"), command);
1151        unuse_commit_buffer(commit, message);
1152
1153        res = write_message(buf.buf, buf.len, rebase_path_squash_msg(), 0);
1154        strbuf_release(&buf);
1155        return res;
1156}
1157
1158static void flush_rewritten_pending(void) {
1159        struct strbuf buf = STRBUF_INIT;
1160        struct object_id newoid;
1161        FILE *out;
1162
1163        if (strbuf_read_file(&buf, rebase_path_rewritten_pending(), (GIT_MAX_HEXSZ + 1) * 2) > 0 &&
1164            !get_oid("HEAD", &newoid) &&
1165            (out = fopen_or_warn(rebase_path_rewritten_list(), "a"))) {
1166                char *bol = buf.buf, *eol;
1167
1168                while (*bol) {
1169                        eol = strchrnul(bol, '\n');
1170                        fprintf(out, "%.*s %s\n", (int)(eol - bol),
1171                                        bol, oid_to_hex(&newoid));
1172                        if (!*eol)
1173                                break;
1174                        bol = eol + 1;
1175                }
1176                fclose(out);
1177                unlink(rebase_path_rewritten_pending());
1178        }
1179        strbuf_release(&buf);
1180}
1181
1182static void record_in_rewritten(struct object_id *oid,
1183                enum todo_command next_command) {
1184        FILE *out = fopen_or_warn(rebase_path_rewritten_pending(), "a");
1185
1186        if (!out)
1187                return;
1188
1189        fprintf(out, "%s\n", oid_to_hex(oid));
1190        fclose(out);
1191
1192        if (!is_fixup(next_command))
1193                flush_rewritten_pending();
1194}
1195
1196static int do_pick_commit(enum todo_command command, struct commit *commit,
1197                struct replay_opts *opts, int final_fixup)
1198{
1199        unsigned int flags = opts->edit ? EDIT_MSG : 0;
1200        const char *msg_file = opts->edit ? NULL : git_path_merge_msg();
1201        struct object_id head;
1202        struct commit *base, *next, *parent;
1203        const char *base_label, *next_label;
1204        struct commit_message msg = { NULL, NULL, NULL, NULL };
1205        struct strbuf msgbuf = STRBUF_INIT;
1206        int res, unborn = 0, allow;
1207
1208        if (opts->no_commit) {
1209                /*
1210                 * We do not intend to commit immediately.  We just want to
1211                 * merge the differences in, so let's compute the tree
1212                 * that represents the "current" state for merge-recursive
1213                 * to work on.
1214                 */
1215                if (write_cache_as_tree(head.hash, 0, NULL))
1216                        return error(_("your index file is unmerged."));
1217        } else {
1218                unborn = get_oid("HEAD", &head);
1219                if (unborn)
1220                        oidcpy(&head, &empty_tree_oid);
1221                if (index_differs_from(unborn ? EMPTY_TREE_SHA1_HEX : "HEAD",
1222                                       NULL, 0))
1223                        return error_dirty_index(opts);
1224        }
1225        discard_cache();
1226
1227        if (!commit->parents)
1228                parent = NULL;
1229        else if (commit->parents->next) {
1230                /* Reverting or cherry-picking a merge commit */
1231                int cnt;
1232                struct commit_list *p;
1233
1234                if (!opts->mainline)
1235                        return error(_("commit %s is a merge but no -m option was given."),
1236                                oid_to_hex(&commit->object.oid));
1237
1238                for (cnt = 1, p = commit->parents;
1239                     cnt != opts->mainline && p;
1240                     cnt++)
1241                        p = p->next;
1242                if (cnt != opts->mainline || !p)
1243                        return error(_("commit %s does not have parent %d"),
1244                                oid_to_hex(&commit->object.oid), opts->mainline);
1245                parent = p->item;
1246        } else if (0 < opts->mainline)
1247                return error(_("mainline was specified but commit %s is not a merge."),
1248                        oid_to_hex(&commit->object.oid));
1249        else
1250                parent = commit->parents->item;
1251
1252        if (get_message(commit, &msg) != 0)
1253                return error(_("cannot get commit message for %s"),
1254                        oid_to_hex(&commit->object.oid));
1255
1256        if (opts->allow_ff && !is_fixup(command) &&
1257            ((parent && !oidcmp(&parent->object.oid, &head)) ||
1258             (!parent && unborn))) {
1259                if (is_rebase_i(opts))
1260                        write_author_script(msg.message);
1261                res = fast_forward_to(&commit->object.oid, &head, unborn,
1262                        opts);
1263                if (res || command != TODO_REWORD)
1264                        goto leave;
1265                flags |= EDIT_MSG | AMEND_MSG;
1266                if (command == TODO_REWORD)
1267                        flags |= VERIFY_MSG;
1268                msg_file = NULL;
1269                goto fast_forward_edit;
1270        }
1271        if (parent && parse_commit(parent) < 0)
1272                /* TRANSLATORS: The first %s will be a "todo" command like
1273                   "revert" or "pick", the second %s a SHA1. */
1274                return error(_("%s: cannot parse parent commit %s"),
1275                        command_to_string(command),
1276                        oid_to_hex(&parent->object.oid));
1277
1278        /*
1279         * "commit" is an existing commit.  We would want to apply
1280         * the difference it introduces since its first parent "prev"
1281         * on top of the current HEAD if we are cherry-pick.  Or the
1282         * reverse of it if we are revert.
1283         */
1284
1285        if (command == TODO_REVERT) {
1286                base = commit;
1287                base_label = msg.label;
1288                next = parent;
1289                next_label = msg.parent_label;
1290                strbuf_addstr(&msgbuf, "Revert \"");
1291                strbuf_addstr(&msgbuf, msg.subject);
1292                strbuf_addstr(&msgbuf, "\"\n\nThis reverts commit ");
1293                strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
1294
1295                if (commit->parents && commit->parents->next) {
1296                        strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
1297                        strbuf_addstr(&msgbuf, oid_to_hex(&parent->object.oid));
1298                }
1299                strbuf_addstr(&msgbuf, ".\n");
1300        } else {
1301                const char *p;
1302
1303                base = parent;
1304                base_label = msg.parent_label;
1305                next = commit;
1306                next_label = msg.label;
1307
1308                /* Append the commit log message to msgbuf. */
1309                if (find_commit_subject(msg.message, &p))
1310                        strbuf_addstr(&msgbuf, p);
1311
1312                if (opts->record_origin) {
1313                        strbuf_complete_line(&msgbuf);
1314                        if (!has_conforming_footer(&msgbuf, NULL, 0))
1315                                strbuf_addch(&msgbuf, '\n');
1316                        strbuf_addstr(&msgbuf, cherry_picked_prefix);
1317                        strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
1318                        strbuf_addstr(&msgbuf, ")\n");
1319                }
1320        }
1321
1322        if (command == TODO_REWORD)
1323                flags |= EDIT_MSG | VERIFY_MSG;
1324        else if (is_fixup(command)) {
1325                if (update_squash_messages(command, commit, opts))
1326                        return -1;
1327                flags |= AMEND_MSG;
1328                if (!final_fixup)
1329                        msg_file = rebase_path_squash_msg();
1330                else if (file_exists(rebase_path_fixup_msg())) {
1331                        flags |= CLEANUP_MSG;
1332                        msg_file = rebase_path_fixup_msg();
1333                } else {
1334                        const char *dest = git_path_squash_msg();
1335                        unlink(dest);
1336                        if (copy_file(dest, rebase_path_squash_msg(), 0666))
1337                                return error(_("could not rename '%s' to '%s'"),
1338                                             rebase_path_squash_msg(), dest);
1339                        unlink(git_path_merge_msg());
1340                        msg_file = dest;
1341                        flags |= EDIT_MSG;
1342                }
1343        }
1344
1345        if (opts->signoff)
1346                append_signoff(&msgbuf, 0, 0);
1347
1348        if (is_rebase_i(opts) && write_author_script(msg.message) < 0)
1349                res = -1;
1350        else if (!opts->strategy || !strcmp(opts->strategy, "recursive") || command == TODO_REVERT) {
1351                res = do_recursive_merge(base, next, base_label, next_label,
1352                                         &head, &msgbuf, opts);
1353                if (res < 0)
1354                        return res;
1355                res |= write_message(msgbuf.buf, msgbuf.len,
1356                                     git_path_merge_msg(), 0);
1357        } else {
1358                struct commit_list *common = NULL;
1359                struct commit_list *remotes = NULL;
1360
1361                res = write_message(msgbuf.buf, msgbuf.len,
1362                                    git_path_merge_msg(), 0);
1363
1364                commit_list_insert(base, &common);
1365                commit_list_insert(next, &remotes);
1366                res |= try_merge_command(opts->strategy,
1367                                         opts->xopts_nr, (const char **)opts->xopts,
1368                                        common, oid_to_hex(&head), remotes);
1369                free_commit_list(common);
1370                free_commit_list(remotes);
1371        }
1372        strbuf_release(&msgbuf);
1373
1374        /*
1375         * If the merge was clean or if it failed due to conflict, we write
1376         * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
1377         * However, if the merge did not even start, then we don't want to
1378         * write it at all.
1379         */
1380        if (command == TODO_PICK && !opts->no_commit && (res == 0 || res == 1) &&
1381            update_ref(NULL, "CHERRY_PICK_HEAD", &commit->object.oid, NULL,
1382                       REF_NODEREF, UPDATE_REFS_MSG_ON_ERR))
1383                res = -1;
1384        if (command == TODO_REVERT && ((opts->no_commit && res == 0) || res == 1) &&
1385            update_ref(NULL, "REVERT_HEAD", &commit->object.oid, NULL,
1386                       REF_NODEREF, UPDATE_REFS_MSG_ON_ERR))
1387                res = -1;
1388
1389        if (res) {
1390                error(command == TODO_REVERT
1391                      ? _("could not revert %s... %s")
1392                      : _("could not apply %s... %s"),
1393                      short_commit_name(commit), msg.subject);
1394                print_advice(res == 1, opts);
1395                rerere(opts->allow_rerere_auto);
1396                goto leave;
1397        }
1398
1399        allow = allow_empty(opts, commit);
1400        if (allow < 0) {
1401                res = allow;
1402                goto leave;
1403        } else if (allow)
1404                flags |= ALLOW_EMPTY;
1405        if (!opts->no_commit)
1406fast_forward_edit:
1407                res = run_git_commit(msg_file, opts, flags);
1408
1409        if (!res && final_fixup) {
1410                unlink(rebase_path_fixup_msg());
1411                unlink(rebase_path_squash_msg());
1412        }
1413
1414leave:
1415        free_message(commit, &msg);
1416        update_abort_safety_file();
1417
1418        return res;
1419}
1420
1421static int prepare_revs(struct replay_opts *opts)
1422{
1423        /*
1424         * picking (but not reverting) ranges (but not individual revisions)
1425         * should be done in reverse
1426         */
1427        if (opts->action == REPLAY_PICK && !opts->revs->no_walk)
1428                opts->revs->reverse ^= 1;
1429
1430        if (prepare_revision_walk(opts->revs))
1431                return error(_("revision walk setup failed"));
1432
1433        if (!opts->revs->commits)
1434                return error(_("empty commit set passed"));
1435        return 0;
1436}
1437
1438static int read_and_refresh_cache(struct replay_opts *opts)
1439{
1440        static struct lock_file index_lock;
1441        int index_fd = hold_locked_index(&index_lock, 0);
1442        if (read_index_preload(&the_index, NULL) < 0) {
1443                rollback_lock_file(&index_lock);
1444                return error(_("git %s: failed to read the index"),
1445                        _(action_name(opts)));
1446        }
1447        refresh_index(&the_index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
1448        if (the_index.cache_changed && index_fd >= 0) {
1449                if (write_locked_index(&the_index, &index_lock, COMMIT_LOCK)) {
1450                        return error(_("git %s: failed to refresh the index"),
1451                                _(action_name(opts)));
1452                }
1453        }
1454        rollback_lock_file(&index_lock);
1455        return 0;
1456}
1457
1458struct todo_item {
1459        enum todo_command command;
1460        struct commit *commit;
1461        const char *arg;
1462        int arg_len;
1463        size_t offset_in_buf;
1464};
1465
1466struct todo_list {
1467        struct strbuf buf;
1468        struct todo_item *items;
1469        int nr, alloc, current;
1470        int done_nr, total_nr;
1471        struct stat_data stat;
1472};
1473
1474#define TODO_LIST_INIT { STRBUF_INIT }
1475
1476static void todo_list_release(struct todo_list *todo_list)
1477{
1478        strbuf_release(&todo_list->buf);
1479        FREE_AND_NULL(todo_list->items);
1480        todo_list->nr = todo_list->alloc = 0;
1481}
1482
1483static struct todo_item *append_new_todo(struct todo_list *todo_list)
1484{
1485        ALLOC_GROW(todo_list->items, todo_list->nr + 1, todo_list->alloc);
1486        return todo_list->items + todo_list->nr++;
1487}
1488
1489static int parse_insn_line(struct todo_item *item, const char *bol, char *eol)
1490{
1491        struct object_id commit_oid;
1492        char *end_of_object_name;
1493        int i, saved, status, padding;
1494
1495        /* left-trim */
1496        bol += strspn(bol, " \t");
1497
1498        if (bol == eol || *bol == '\r' || *bol == comment_line_char) {
1499                item->command = TODO_COMMENT;
1500                item->commit = NULL;
1501                item->arg = bol;
1502                item->arg_len = eol - bol;
1503                return 0;
1504        }
1505
1506        for (i = 0; i < TODO_COMMENT; i++)
1507                if (skip_prefix(bol, todo_command_info[i].str, &bol)) {
1508                        item->command = i;
1509                        break;
1510                } else if (bol[1] == ' ' && *bol == todo_command_info[i].c) {
1511                        bol++;
1512                        item->command = i;
1513                        break;
1514                }
1515        if (i >= TODO_COMMENT)
1516                return -1;
1517
1518        if (item->command == TODO_NOOP) {
1519                item->commit = NULL;
1520                item->arg = bol;
1521                item->arg_len = eol - bol;
1522                return 0;
1523        }
1524
1525        /* Eat up extra spaces/ tabs before object name */
1526        padding = strspn(bol, " \t");
1527        if (!padding)
1528                return -1;
1529        bol += padding;
1530
1531        if (item->command == TODO_EXEC) {
1532                item->arg = bol;
1533                item->arg_len = (int)(eol - bol);
1534                return 0;
1535        }
1536
1537        end_of_object_name = (char *) bol + strcspn(bol, " \t\n");
1538        saved = *end_of_object_name;
1539        *end_of_object_name = '\0';
1540        status = get_oid(bol, &commit_oid);
1541        *end_of_object_name = saved;
1542
1543        item->arg = end_of_object_name + strspn(end_of_object_name, " \t");
1544        item->arg_len = (int)(eol - item->arg);
1545
1546        if (status < 0)
1547                return -1;
1548
1549        item->commit = lookup_commit_reference(&commit_oid);
1550        return !item->commit;
1551}
1552
1553static int parse_insn_buffer(char *buf, struct todo_list *todo_list)
1554{
1555        struct todo_item *item;
1556        char *p = buf, *next_p;
1557        int i, res = 0, fixup_okay = file_exists(rebase_path_done());
1558
1559        for (i = 1; *p; i++, p = next_p) {
1560                char *eol = strchrnul(p, '\n');
1561
1562                next_p = *eol ? eol + 1 /* skip LF */ : eol;
1563
1564                if (p != eol && eol[-1] == '\r')
1565                        eol--; /* strip Carriage Return */
1566
1567                item = append_new_todo(todo_list);
1568                item->offset_in_buf = p - todo_list->buf.buf;
1569                if (parse_insn_line(item, p, eol)) {
1570                        res = error(_("invalid line %d: %.*s"),
1571                                i, (int)(eol - p), p);
1572                        item->command = TODO_NOOP;
1573                }
1574
1575                if (fixup_okay)
1576                        ; /* do nothing */
1577                else if (is_fixup(item->command))
1578                        return error(_("cannot '%s' without a previous commit"),
1579                                command_to_string(item->command));
1580                else if (!is_noop(item->command))
1581                        fixup_okay = 1;
1582        }
1583
1584        return res;
1585}
1586
1587static int count_commands(struct todo_list *todo_list)
1588{
1589        int count = 0, i;
1590
1591        for (i = 0; i < todo_list->nr; i++)
1592                if (todo_list->items[i].command != TODO_COMMENT)
1593                        count++;
1594
1595        return count;
1596}
1597
1598static int read_populate_todo(struct todo_list *todo_list,
1599                        struct replay_opts *opts)
1600{
1601        struct stat st;
1602        const char *todo_file = get_todo_path(opts);
1603        int fd, res;
1604
1605        strbuf_reset(&todo_list->buf);
1606        fd = open(todo_file, O_RDONLY);
1607        if (fd < 0)
1608                return error_errno(_("could not open '%s'"), todo_file);
1609        if (strbuf_read(&todo_list->buf, fd, 0) < 0) {
1610                close(fd);
1611                return error(_("could not read '%s'."), todo_file);
1612        }
1613        close(fd);
1614
1615        res = stat(todo_file, &st);
1616        if (res)
1617                return error(_("could not stat '%s'"), todo_file);
1618        fill_stat_data(&todo_list->stat, &st);
1619
1620        res = parse_insn_buffer(todo_list->buf.buf, todo_list);
1621        if (res) {
1622                if (is_rebase_i(opts))
1623                        return error(_("please fix this using "
1624                                       "'git rebase --edit-todo'."));
1625                return error(_("unusable instruction sheet: '%s'"), todo_file);
1626        }
1627
1628        if (!todo_list->nr &&
1629            (!is_rebase_i(opts) || !file_exists(rebase_path_done())))
1630                return error(_("no commits parsed."));
1631
1632        if (!is_rebase_i(opts)) {
1633                enum todo_command valid =
1634                        opts->action == REPLAY_PICK ? TODO_PICK : TODO_REVERT;
1635                int i;
1636
1637                for (i = 0; i < todo_list->nr; i++)
1638                        if (valid == todo_list->items[i].command)
1639                                continue;
1640                        else if (valid == TODO_PICK)
1641                                return error(_("cannot cherry-pick during a revert."));
1642                        else
1643                                return error(_("cannot revert during a cherry-pick."));
1644        }
1645
1646        if (is_rebase_i(opts)) {
1647                struct todo_list done = TODO_LIST_INIT;
1648                FILE *f = fopen_or_warn(rebase_path_msgtotal(), "w");
1649
1650                if (strbuf_read_file(&done.buf, rebase_path_done(), 0) > 0 &&
1651                                !parse_insn_buffer(done.buf.buf, &done))
1652                        todo_list->done_nr = count_commands(&done);
1653                else
1654                        todo_list->done_nr = 0;
1655
1656                todo_list->total_nr = todo_list->done_nr
1657                        + count_commands(todo_list);
1658                todo_list_release(&done);
1659
1660                if (f) {
1661                        fprintf(f, "%d\n", todo_list->total_nr);
1662                        fclose(f);
1663                }
1664        }
1665
1666        return 0;
1667}
1668
1669static int git_config_string_dup(char **dest,
1670                                 const char *var, const char *value)
1671{
1672        if (!value)
1673                return config_error_nonbool(var);
1674        free(*dest);
1675        *dest = xstrdup(value);
1676        return 0;
1677}
1678
1679static int populate_opts_cb(const char *key, const char *value, void *data)
1680{
1681        struct replay_opts *opts = data;
1682        int error_flag = 1;
1683
1684        if (!value)
1685                error_flag = 0;
1686        else if (!strcmp(key, "options.no-commit"))
1687                opts->no_commit = git_config_bool_or_int(key, value, &error_flag);
1688        else if (!strcmp(key, "options.edit"))
1689                opts->edit = git_config_bool_or_int(key, value, &error_flag);
1690        else if (!strcmp(key, "options.signoff"))
1691                opts->signoff = git_config_bool_or_int(key, value, &error_flag);
1692        else if (!strcmp(key, "options.record-origin"))
1693                opts->record_origin = git_config_bool_or_int(key, value, &error_flag);
1694        else if (!strcmp(key, "options.allow-ff"))
1695                opts->allow_ff = git_config_bool_or_int(key, value, &error_flag);
1696        else if (!strcmp(key, "options.mainline"))
1697                opts->mainline = git_config_int(key, value);
1698        else if (!strcmp(key, "options.strategy"))
1699                git_config_string_dup(&opts->strategy, key, value);
1700        else if (!strcmp(key, "options.gpg-sign"))
1701                git_config_string_dup(&opts->gpg_sign, key, value);
1702        else if (!strcmp(key, "options.strategy-option")) {
1703                ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
1704                opts->xopts[opts->xopts_nr++] = xstrdup(value);
1705        } else if (!strcmp(key, "options.allow-rerere-auto"))
1706                opts->allow_rerere_auto =
1707                        git_config_bool_or_int(key, value, &error_flag) ?
1708                                RERERE_AUTOUPDATE : RERERE_NOAUTOUPDATE;
1709        else
1710                return error(_("invalid key: %s"), key);
1711
1712        if (!error_flag)
1713                return error(_("invalid value for %s: %s"), key, value);
1714
1715        return 0;
1716}
1717
1718static void read_strategy_opts(struct replay_opts *opts, struct strbuf *buf)
1719{
1720        int i;
1721
1722        strbuf_reset(buf);
1723        if (!read_oneliner(buf, rebase_path_strategy(), 0))
1724                return;
1725        opts->strategy = strbuf_detach(buf, NULL);
1726        if (!read_oneliner(buf, rebase_path_strategy_opts(), 0))
1727                return;
1728
1729        opts->xopts_nr = split_cmdline(buf->buf, (const char ***)&opts->xopts);
1730        for (i = 0; i < opts->xopts_nr; i++) {
1731                const char *arg = opts->xopts[i];
1732
1733                skip_prefix(arg, "--", &arg);
1734                opts->xopts[i] = xstrdup(arg);
1735        }
1736}
1737
1738static int read_populate_opts(struct replay_opts *opts)
1739{
1740        if (is_rebase_i(opts)) {
1741                struct strbuf buf = STRBUF_INIT;
1742
1743                if (read_oneliner(&buf, rebase_path_gpg_sign_opt(), 1)) {
1744                        if (!starts_with(buf.buf, "-S"))
1745                                strbuf_reset(&buf);
1746                        else {
1747                                free(opts->gpg_sign);
1748                                opts->gpg_sign = xstrdup(buf.buf + 2);
1749                        }
1750                        strbuf_reset(&buf);
1751                }
1752
1753                if (read_oneliner(&buf, rebase_path_allow_rerere_autoupdate(), 1)) {
1754                        if (!strcmp(buf.buf, "--rerere-autoupdate"))
1755                                opts->allow_rerere_auto = RERERE_AUTOUPDATE;
1756                        else if (!strcmp(buf.buf, "--no-rerere-autoupdate"))
1757                                opts->allow_rerere_auto = RERERE_NOAUTOUPDATE;
1758                        strbuf_reset(&buf);
1759                }
1760
1761                if (file_exists(rebase_path_verbose()))
1762                        opts->verbose = 1;
1763
1764                read_strategy_opts(opts, &buf);
1765                strbuf_release(&buf);
1766
1767                return 0;
1768        }
1769
1770        if (!file_exists(git_path_opts_file()))
1771                return 0;
1772        /*
1773         * The function git_parse_source(), called from git_config_from_file(),
1774         * may die() in case of a syntactically incorrect file. We do not care
1775         * about this case, though, because we wrote that file ourselves, so we
1776         * are pretty certain that it is syntactically correct.
1777         */
1778        if (git_config_from_file(populate_opts_cb, git_path_opts_file(), opts) < 0)
1779                return error(_("malformed options sheet: '%s'"),
1780                        git_path_opts_file());
1781        return 0;
1782}
1783
1784static int walk_revs_populate_todo(struct todo_list *todo_list,
1785                                struct replay_opts *opts)
1786{
1787        enum todo_command command = opts->action == REPLAY_PICK ?
1788                TODO_PICK : TODO_REVERT;
1789        const char *command_string = todo_command_info[command].str;
1790        struct commit *commit;
1791
1792        if (prepare_revs(opts))
1793                return -1;
1794
1795        while ((commit = get_revision(opts->revs))) {
1796                struct todo_item *item = append_new_todo(todo_list);
1797                const char *commit_buffer = get_commit_buffer(commit, NULL);
1798                const char *subject;
1799                int subject_len;
1800
1801                item->command = command;
1802                item->commit = commit;
1803                item->arg = NULL;
1804                item->arg_len = 0;
1805                item->offset_in_buf = todo_list->buf.len;
1806                subject_len = find_commit_subject(commit_buffer, &subject);
1807                strbuf_addf(&todo_list->buf, "%s %s %.*s\n", command_string,
1808                        short_commit_name(commit), subject_len, subject);
1809                unuse_commit_buffer(commit, commit_buffer);
1810        }
1811        return 0;
1812}
1813
1814static int create_seq_dir(void)
1815{
1816        if (file_exists(git_path_seq_dir())) {
1817                error(_("a cherry-pick or revert is already in progress"));
1818                advise(_("try \"git cherry-pick (--continue | --quit | --abort)\""));
1819                return -1;
1820        } else if (mkdir(git_path_seq_dir(), 0777) < 0)
1821                return error_errno(_("could not create sequencer directory '%s'"),
1822                                   git_path_seq_dir());
1823        return 0;
1824}
1825
1826static int save_head(const char *head)
1827{
1828        static struct lock_file head_lock;
1829        struct strbuf buf = STRBUF_INIT;
1830        int fd;
1831        ssize_t written;
1832
1833        fd = hold_lock_file_for_update(&head_lock, git_path_head_file(), 0);
1834        if (fd < 0) {
1835                rollback_lock_file(&head_lock);
1836                return error_errno(_("could not lock HEAD"));
1837        }
1838        strbuf_addf(&buf, "%s\n", head);
1839        written = write_in_full(fd, buf.buf, buf.len);
1840        strbuf_release(&buf);
1841        if (written < 0) {
1842                rollback_lock_file(&head_lock);
1843                return error_errno(_("could not write to '%s'"),
1844                                   git_path_head_file());
1845        }
1846        if (commit_lock_file(&head_lock) < 0) {
1847                rollback_lock_file(&head_lock);
1848                return error(_("failed to finalize '%s'."), git_path_head_file());
1849        }
1850        return 0;
1851}
1852
1853static int rollback_is_safe(void)
1854{
1855        struct strbuf sb = STRBUF_INIT;
1856        struct object_id expected_head, actual_head;
1857
1858        if (strbuf_read_file(&sb, git_path_abort_safety_file(), 0) >= 0) {
1859                strbuf_trim(&sb);
1860                if (get_oid_hex(sb.buf, &expected_head)) {
1861                        strbuf_release(&sb);
1862                        die(_("could not parse %s"), git_path_abort_safety_file());
1863                }
1864                strbuf_release(&sb);
1865        }
1866        else if (errno == ENOENT)
1867                oidclr(&expected_head);
1868        else
1869                die_errno(_("could not read '%s'"), git_path_abort_safety_file());
1870
1871        if (get_oid("HEAD", &actual_head))
1872                oidclr(&actual_head);
1873
1874        return !oidcmp(&actual_head, &expected_head);
1875}
1876
1877static int reset_for_rollback(const struct object_id *oid)
1878{
1879        const char *argv[4];    /* reset --merge <arg> + NULL */
1880
1881        argv[0] = "reset";
1882        argv[1] = "--merge";
1883        argv[2] = oid_to_hex(oid);
1884        argv[3] = NULL;
1885        return run_command_v_opt(argv, RUN_GIT_CMD);
1886}
1887
1888static int rollback_single_pick(void)
1889{
1890        struct object_id head_oid;
1891
1892        if (!file_exists(git_path_cherry_pick_head()) &&
1893            !file_exists(git_path_revert_head()))
1894                return error(_("no cherry-pick or revert in progress"));
1895        if (read_ref_full("HEAD", 0, &head_oid, NULL))
1896                return error(_("cannot resolve HEAD"));
1897        if (is_null_oid(&head_oid))
1898                return error(_("cannot abort from a branch yet to be born"));
1899        return reset_for_rollback(&head_oid);
1900}
1901
1902int sequencer_rollback(struct replay_opts *opts)
1903{
1904        FILE *f;
1905        struct object_id oid;
1906        struct strbuf buf = STRBUF_INIT;
1907        const char *p;
1908
1909        f = fopen(git_path_head_file(), "r");
1910        if (!f && errno == ENOENT) {
1911                /*
1912                 * There is no multiple-cherry-pick in progress.
1913                 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
1914                 * a single-cherry-pick in progress, abort that.
1915                 */
1916                return rollback_single_pick();
1917        }
1918        if (!f)
1919                return error_errno(_("cannot open '%s'"), git_path_head_file());
1920        if (strbuf_getline_lf(&buf, f)) {
1921                error(_("cannot read '%s': %s"), git_path_head_file(),
1922                      ferror(f) ?  strerror(errno) : _("unexpected end of file"));
1923                fclose(f);
1924                goto fail;
1925        }
1926        fclose(f);
1927        if (parse_oid_hex(buf.buf, &oid, &p) || *p != '\0') {
1928                error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
1929                        git_path_head_file());
1930                goto fail;
1931        }
1932        if (is_null_oid(&oid)) {
1933                error(_("cannot abort from a branch yet to be born"));
1934                goto fail;
1935        }
1936
1937        if (!rollback_is_safe()) {
1938                /* Do not error, just do not rollback */
1939                warning(_("You seem to have moved HEAD. "
1940                          "Not rewinding, check your HEAD!"));
1941        } else
1942        if (reset_for_rollback(&oid))
1943                goto fail;
1944        strbuf_release(&buf);
1945        return sequencer_remove_state(opts);
1946fail:
1947        strbuf_release(&buf);
1948        return -1;
1949}
1950
1951static int save_todo(struct todo_list *todo_list, struct replay_opts *opts)
1952{
1953        static struct lock_file todo_lock;
1954        const char *todo_path = get_todo_path(opts);
1955        int next = todo_list->current, offset, fd;
1956
1957        /*
1958         * rebase -i writes "git-rebase-todo" without the currently executing
1959         * command, appending it to "done" instead.
1960         */
1961        if (is_rebase_i(opts))
1962                next++;
1963
1964        fd = hold_lock_file_for_update(&todo_lock, todo_path, 0);
1965        if (fd < 0)
1966                return error_errno(_("could not lock '%s'"), todo_path);
1967        offset = next < todo_list->nr ?
1968                todo_list->items[next].offset_in_buf : todo_list->buf.len;
1969        if (write_in_full(fd, todo_list->buf.buf + offset,
1970                        todo_list->buf.len - offset) < 0)
1971                return error_errno(_("could not write to '%s'"), todo_path);
1972        if (commit_lock_file(&todo_lock) < 0)
1973                return error(_("failed to finalize '%s'."), todo_path);
1974
1975        if (is_rebase_i(opts)) {
1976                const char *done_path = rebase_path_done();
1977                int fd = open(done_path, O_CREAT | O_WRONLY | O_APPEND, 0666);
1978                int prev_offset = !next ? 0 :
1979                        todo_list->items[next - 1].offset_in_buf;
1980
1981                if (fd >= 0 && offset > prev_offset &&
1982                    write_in_full(fd, todo_list->buf.buf + prev_offset,
1983                                  offset - prev_offset) < 0) {
1984                        close(fd);
1985                        return error_errno(_("could not write to '%s'"),
1986                                           done_path);
1987                }
1988                if (fd >= 0)
1989                        close(fd);
1990        }
1991        return 0;
1992}
1993
1994static int save_opts(struct replay_opts *opts)
1995{
1996        const char *opts_file = git_path_opts_file();
1997        int res = 0;
1998
1999        if (opts->no_commit)
2000                res |= git_config_set_in_file_gently(opts_file, "options.no-commit", "true");
2001        if (opts->edit)
2002                res |= git_config_set_in_file_gently(opts_file, "options.edit", "true");
2003        if (opts->signoff)
2004                res |= git_config_set_in_file_gently(opts_file, "options.signoff", "true");
2005        if (opts->record_origin)
2006                res |= git_config_set_in_file_gently(opts_file, "options.record-origin", "true");
2007        if (opts->allow_ff)
2008                res |= git_config_set_in_file_gently(opts_file, "options.allow-ff", "true");
2009        if (opts->mainline) {
2010                struct strbuf buf = STRBUF_INIT;
2011                strbuf_addf(&buf, "%d", opts->mainline);
2012                res |= git_config_set_in_file_gently(opts_file, "options.mainline", buf.buf);
2013                strbuf_release(&buf);
2014        }
2015        if (opts->strategy)
2016                res |= git_config_set_in_file_gently(opts_file, "options.strategy", opts->strategy);
2017        if (opts->gpg_sign)
2018                res |= git_config_set_in_file_gently(opts_file, "options.gpg-sign", opts->gpg_sign);
2019        if (opts->xopts) {
2020                int i;
2021                for (i = 0; i < opts->xopts_nr; i++)
2022                        res |= git_config_set_multivar_in_file_gently(opts_file,
2023                                                        "options.strategy-option",
2024                                                        opts->xopts[i], "^$", 0);
2025        }
2026        if (opts->allow_rerere_auto)
2027                res |= git_config_set_in_file_gently(opts_file, "options.allow-rerere-auto",
2028                                                     opts->allow_rerere_auto == RERERE_AUTOUPDATE ?
2029                                                     "true" : "false");
2030        return res;
2031}
2032
2033static int make_patch(struct commit *commit, struct replay_opts *opts)
2034{
2035        struct strbuf buf = STRBUF_INIT;
2036        struct rev_info log_tree_opt;
2037        const char *subject, *p;
2038        int res = 0;
2039
2040        p = short_commit_name(commit);
2041        if (write_message(p, strlen(p), rebase_path_stopped_sha(), 1) < 0)
2042                return -1;
2043
2044        strbuf_addf(&buf, "%s/patch", get_dir(opts));
2045        memset(&log_tree_opt, 0, sizeof(log_tree_opt));
2046        init_revisions(&log_tree_opt, NULL);
2047        log_tree_opt.abbrev = 0;
2048        log_tree_opt.diff = 1;
2049        log_tree_opt.diffopt.output_format = DIFF_FORMAT_PATCH;
2050        log_tree_opt.disable_stdin = 1;
2051        log_tree_opt.no_commit_id = 1;
2052        log_tree_opt.diffopt.file = fopen(buf.buf, "w");
2053        log_tree_opt.diffopt.use_color = GIT_COLOR_NEVER;
2054        if (!log_tree_opt.diffopt.file)
2055                res |= error_errno(_("could not open '%s'"), buf.buf);
2056        else {
2057                res |= log_tree_commit(&log_tree_opt, commit);
2058                fclose(log_tree_opt.diffopt.file);
2059        }
2060        strbuf_reset(&buf);
2061
2062        strbuf_addf(&buf, "%s/message", get_dir(opts));
2063        if (!file_exists(buf.buf)) {
2064                const char *commit_buffer = get_commit_buffer(commit, NULL);
2065                find_commit_subject(commit_buffer, &subject);
2066                res |= write_message(subject, strlen(subject), buf.buf, 1);
2067                unuse_commit_buffer(commit, commit_buffer);
2068        }
2069        strbuf_release(&buf);
2070
2071        return res;
2072}
2073
2074static int intend_to_amend(void)
2075{
2076        struct object_id head;
2077        char *p;
2078
2079        if (get_oid("HEAD", &head))
2080                return error(_("cannot read HEAD"));
2081
2082        p = oid_to_hex(&head);
2083        return write_message(p, strlen(p), rebase_path_amend(), 1);
2084}
2085
2086static int error_with_patch(struct commit *commit,
2087        const char *subject, int subject_len,
2088        struct replay_opts *opts, int exit_code, int to_amend)
2089{
2090        if (make_patch(commit, opts))
2091                return -1;
2092
2093        if (to_amend) {
2094                if (intend_to_amend())
2095                        return -1;
2096
2097                fprintf(stderr, "You can amend the commit now, with\n"
2098                        "\n"
2099                        "  git commit --amend %s\n"
2100                        "\n"
2101                        "Once you are satisfied with your changes, run\n"
2102                        "\n"
2103                        "  git rebase --continue\n", gpg_sign_opt_quoted(opts));
2104        } else if (exit_code)
2105                fprintf(stderr, "Could not apply %s... %.*s\n",
2106                        short_commit_name(commit), subject_len, subject);
2107
2108        return exit_code;
2109}
2110
2111static int error_failed_squash(struct commit *commit,
2112        struct replay_opts *opts, int subject_len, const char *subject)
2113{
2114        if (rename(rebase_path_squash_msg(), rebase_path_message()))
2115                return error(_("could not rename '%s' to '%s'"),
2116                        rebase_path_squash_msg(), rebase_path_message());
2117        unlink(rebase_path_fixup_msg());
2118        unlink(git_path_merge_msg());
2119        if (copy_file(git_path_merge_msg(), rebase_path_message(), 0666))
2120                return error(_("could not copy '%s' to '%s'"),
2121                             rebase_path_message(), git_path_merge_msg());
2122        return error_with_patch(commit, subject, subject_len, opts, 1, 0);
2123}
2124
2125static int do_exec(const char *command_line)
2126{
2127        struct argv_array child_env = ARGV_ARRAY_INIT;
2128        const char *child_argv[] = { NULL, NULL };
2129        int dirty, status;
2130
2131        fprintf(stderr, "Executing: %s\n", command_line);
2132        child_argv[0] = command_line;
2133        argv_array_pushf(&child_env, "GIT_DIR=%s", absolute_path(get_git_dir()));
2134        status = run_command_v_opt_cd_env(child_argv, RUN_USING_SHELL, NULL,
2135                                          child_env.argv);
2136
2137        /* force re-reading of the cache */
2138        if (discard_cache() < 0 || read_cache() < 0)
2139                return error(_("could not read index"));
2140
2141        dirty = require_clean_work_tree("rebase", NULL, 1, 1);
2142
2143        if (status) {
2144                warning(_("execution failed: %s\n%s"
2145                          "You can fix the problem, and then run\n"
2146                          "\n"
2147                          "  git rebase --continue\n"
2148                          "\n"),
2149                        command_line,
2150                        dirty ? N_("and made changes to the index and/or the "
2151                                "working tree\n") : "");
2152                if (status == 127)
2153                        /* command not found */
2154                        status = 1;
2155        } else if (dirty) {
2156                warning(_("execution succeeded: %s\nbut "
2157                          "left changes to the index and/or the working tree\n"
2158                          "Commit or stash your changes, and then run\n"
2159                          "\n"
2160                          "  git rebase --continue\n"
2161                          "\n"), command_line);
2162                status = 1;
2163        }
2164
2165        argv_array_clear(&child_env);
2166
2167        return status;
2168}
2169
2170static int is_final_fixup(struct todo_list *todo_list)
2171{
2172        int i = todo_list->current;
2173
2174        if (!is_fixup(todo_list->items[i].command))
2175                return 0;
2176
2177        while (++i < todo_list->nr)
2178                if (is_fixup(todo_list->items[i].command))
2179                        return 0;
2180                else if (!is_noop(todo_list->items[i].command))
2181                        break;
2182        return 1;
2183}
2184
2185static enum todo_command peek_command(struct todo_list *todo_list, int offset)
2186{
2187        int i;
2188
2189        for (i = todo_list->current + offset; i < todo_list->nr; i++)
2190                if (!is_noop(todo_list->items[i].command))
2191                        return todo_list->items[i].command;
2192
2193        return -1;
2194}
2195
2196static int apply_autostash(struct replay_opts *opts)
2197{
2198        struct strbuf stash_sha1 = STRBUF_INIT;
2199        struct child_process child = CHILD_PROCESS_INIT;
2200        int ret = 0;
2201
2202        if (!read_oneliner(&stash_sha1, rebase_path_autostash(), 1)) {
2203                strbuf_release(&stash_sha1);
2204                return 0;
2205        }
2206        strbuf_trim(&stash_sha1);
2207
2208        child.git_cmd = 1;
2209        child.no_stdout = 1;
2210        child.no_stderr = 1;
2211        argv_array_push(&child.args, "stash");
2212        argv_array_push(&child.args, "apply");
2213        argv_array_push(&child.args, stash_sha1.buf);
2214        if (!run_command(&child))
2215                fprintf(stderr, _("Applied autostash.\n"));
2216        else {
2217                struct child_process store = CHILD_PROCESS_INIT;
2218
2219                store.git_cmd = 1;
2220                argv_array_push(&store.args, "stash");
2221                argv_array_push(&store.args, "store");
2222                argv_array_push(&store.args, "-m");
2223                argv_array_push(&store.args, "autostash");
2224                argv_array_push(&store.args, "-q");
2225                argv_array_push(&store.args, stash_sha1.buf);
2226                if (run_command(&store))
2227                        ret = error(_("cannot store %s"), stash_sha1.buf);
2228                else
2229                        fprintf(stderr,
2230                                _("Applying autostash resulted in conflicts.\n"
2231                                  "Your changes are safe in the stash.\n"
2232                                  "You can run \"git stash pop\" or"
2233                                  " \"git stash drop\" at any time.\n"));
2234        }
2235
2236        strbuf_release(&stash_sha1);
2237        return ret;
2238}
2239
2240static const char *reflog_message(struct replay_opts *opts,
2241        const char *sub_action, const char *fmt, ...)
2242{
2243        va_list ap;
2244        static struct strbuf buf = STRBUF_INIT;
2245
2246        va_start(ap, fmt);
2247        strbuf_reset(&buf);
2248        strbuf_addstr(&buf, action_name(opts));
2249        if (sub_action)
2250                strbuf_addf(&buf, " (%s)", sub_action);
2251        if (fmt) {
2252                strbuf_addstr(&buf, ": ");
2253                strbuf_vaddf(&buf, fmt, ap);
2254        }
2255        va_end(ap);
2256
2257        return buf.buf;
2258}
2259
2260static int pick_commits(struct todo_list *todo_list, struct replay_opts *opts)
2261{
2262        int res = 0;
2263
2264        setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
2265        if (opts->allow_ff)
2266                assert(!(opts->signoff || opts->no_commit ||
2267                                opts->record_origin || opts->edit));
2268        if (read_and_refresh_cache(opts))
2269                return -1;
2270
2271        while (todo_list->current < todo_list->nr) {
2272                struct todo_item *item = todo_list->items + todo_list->current;
2273                if (save_todo(todo_list, opts))
2274                        return -1;
2275                if (is_rebase_i(opts)) {
2276                        if (item->command != TODO_COMMENT) {
2277                                FILE *f = fopen(rebase_path_msgnum(), "w");
2278
2279                                todo_list->done_nr++;
2280
2281                                if (f) {
2282                                        fprintf(f, "%d\n", todo_list->done_nr);
2283                                        fclose(f);
2284                                }
2285                                fprintf(stderr, "Rebasing (%d/%d)%s",
2286                                        todo_list->done_nr,
2287                                        todo_list->total_nr,
2288                                        opts->verbose ? "\n" : "\r");
2289                        }
2290                        unlink(rebase_path_message());
2291                        unlink(rebase_path_author_script());
2292                        unlink(rebase_path_stopped_sha());
2293                        unlink(rebase_path_amend());
2294                }
2295                if (item->command <= TODO_SQUASH) {
2296                        if (is_rebase_i(opts))
2297                                setenv("GIT_REFLOG_ACTION", reflog_message(opts,
2298                                        command_to_string(item->command), NULL),
2299                                        1);
2300                        res = do_pick_commit(item->command, item->commit,
2301                                        opts, is_final_fixup(todo_list));
2302                        if (is_rebase_i(opts) && res < 0) {
2303                                /* Reschedule */
2304                                todo_list->current--;
2305                                if (save_todo(todo_list, opts))
2306                                        return -1;
2307                        }
2308                        if (item->command == TODO_EDIT) {
2309                                struct commit *commit = item->commit;
2310                                if (!res)
2311                                        fprintf(stderr,
2312                                                _("Stopped at %s...  %.*s\n"),
2313                                                short_commit_name(commit),
2314                                                item->arg_len, item->arg);
2315                                return error_with_patch(commit,
2316                                        item->arg, item->arg_len, opts, res,
2317                                        !res);
2318                        }
2319                        if (is_rebase_i(opts) && !res)
2320                                record_in_rewritten(&item->commit->object.oid,
2321                                        peek_command(todo_list, 1));
2322                        if (res && is_fixup(item->command)) {
2323                                if (res == 1)
2324                                        intend_to_amend();
2325                                return error_failed_squash(item->commit, opts,
2326                                        item->arg_len, item->arg);
2327                        } else if (res && is_rebase_i(opts))
2328                                return res | error_with_patch(item->commit,
2329                                        item->arg, item->arg_len, opts, res,
2330                                        item->command == TODO_REWORD);
2331                } else if (item->command == TODO_EXEC) {
2332                        char *end_of_arg = (char *)(item->arg + item->arg_len);
2333                        int saved = *end_of_arg;
2334                        struct stat st;
2335
2336                        *end_of_arg = '\0';
2337                        res = do_exec(item->arg);
2338                        *end_of_arg = saved;
2339
2340                        /* Reread the todo file if it has changed. */
2341                        if (res)
2342                                ; /* fall through */
2343                        else if (stat(get_todo_path(opts), &st))
2344                                res = error_errno(_("could not stat '%s'"),
2345                                                  get_todo_path(opts));
2346                        else if (match_stat_data(&todo_list->stat, &st)) {
2347                                todo_list_release(todo_list);
2348                                if (read_populate_todo(todo_list, opts))
2349                                        res = -1; /* message was printed */
2350                                /* `current` will be incremented below */
2351                                todo_list->current = -1;
2352                        }
2353                } else if (!is_noop(item->command))
2354                        return error(_("unknown command %d"), item->command);
2355
2356                todo_list->current++;
2357                if (res)
2358                        return res;
2359        }
2360
2361        if (is_rebase_i(opts)) {
2362                struct strbuf head_ref = STRBUF_INIT, buf = STRBUF_INIT;
2363                struct stat st;
2364
2365                /* Stopped in the middle, as planned? */
2366                if (todo_list->current < todo_list->nr)
2367                        return 0;
2368
2369                if (read_oneliner(&head_ref, rebase_path_head_name(), 0) &&
2370                                starts_with(head_ref.buf, "refs/")) {
2371                        const char *msg;
2372                        struct object_id head, orig;
2373                        int res;
2374
2375                        if (get_oid("HEAD", &head)) {
2376                                res = error(_("cannot read HEAD"));
2377cleanup_head_ref:
2378                                strbuf_release(&head_ref);
2379                                strbuf_release(&buf);
2380                                return res;
2381                        }
2382                        if (!read_oneliner(&buf, rebase_path_orig_head(), 0) ||
2383                                        get_oid_hex(buf.buf, &orig)) {
2384                                res = error(_("could not read orig-head"));
2385                                goto cleanup_head_ref;
2386                        }
2387                        strbuf_reset(&buf);
2388                        if (!read_oneliner(&buf, rebase_path_onto(), 0)) {
2389                                res = error(_("could not read 'onto'"));
2390                                goto cleanup_head_ref;
2391                        }
2392                        msg = reflog_message(opts, "finish", "%s onto %s",
2393                                head_ref.buf, buf.buf);
2394                        if (update_ref(msg, head_ref.buf, &head, &orig,
2395                                       REF_NODEREF, UPDATE_REFS_MSG_ON_ERR)) {
2396                                res = error(_("could not update %s"),
2397                                        head_ref.buf);
2398                                goto cleanup_head_ref;
2399                        }
2400                        msg = reflog_message(opts, "finish", "returning to %s",
2401                                head_ref.buf);
2402                        if (create_symref("HEAD", head_ref.buf, msg)) {
2403                                res = error(_("could not update HEAD to %s"),
2404                                        head_ref.buf);
2405                                goto cleanup_head_ref;
2406                        }
2407                        strbuf_reset(&buf);
2408                }
2409
2410                if (opts->verbose) {
2411                        struct rev_info log_tree_opt;
2412                        struct object_id orig, head;
2413
2414                        memset(&log_tree_opt, 0, sizeof(log_tree_opt));
2415                        init_revisions(&log_tree_opt, NULL);
2416                        log_tree_opt.diff = 1;
2417                        log_tree_opt.diffopt.output_format =
2418                                DIFF_FORMAT_DIFFSTAT;
2419                        log_tree_opt.disable_stdin = 1;
2420
2421                        if (read_oneliner(&buf, rebase_path_orig_head(), 0) &&
2422                            !get_oid(buf.buf, &orig) &&
2423                            !get_oid("HEAD", &head)) {
2424                                diff_tree_oid(&orig, &head, "",
2425                                              &log_tree_opt.diffopt);
2426                                log_tree_diff_flush(&log_tree_opt);
2427                        }
2428                }
2429                flush_rewritten_pending();
2430                if (!stat(rebase_path_rewritten_list(), &st) &&
2431                                st.st_size > 0) {
2432                        struct child_process child = CHILD_PROCESS_INIT;
2433                        const char *post_rewrite_hook =
2434                                find_hook("post-rewrite");
2435
2436                        child.in = open(rebase_path_rewritten_list(), O_RDONLY);
2437                        child.git_cmd = 1;
2438                        argv_array_push(&child.args, "notes");
2439                        argv_array_push(&child.args, "copy");
2440                        argv_array_push(&child.args, "--for-rewrite=rebase");
2441                        /* we don't care if this copying failed */
2442                        run_command(&child);
2443
2444                        if (post_rewrite_hook) {
2445                                struct child_process hook = CHILD_PROCESS_INIT;
2446
2447                                hook.in = open(rebase_path_rewritten_list(),
2448                                        O_RDONLY);
2449                                hook.stdout_to_stderr = 1;
2450                                argv_array_push(&hook.args, post_rewrite_hook);
2451                                argv_array_push(&hook.args, "rebase");
2452                                /* we don't care if this hook failed */
2453                                run_command(&hook);
2454                        }
2455                }
2456                apply_autostash(opts);
2457
2458                fprintf(stderr, "Successfully rebased and updated %s.\n",
2459                        head_ref.buf);
2460
2461                strbuf_release(&buf);
2462                strbuf_release(&head_ref);
2463        }
2464
2465        /*
2466         * Sequence of picks finished successfully; cleanup by
2467         * removing the .git/sequencer directory
2468         */
2469        return sequencer_remove_state(opts);
2470}
2471
2472static int continue_single_pick(void)
2473{
2474        const char *argv[] = { "commit", NULL };
2475
2476        if (!file_exists(git_path_cherry_pick_head()) &&
2477            !file_exists(git_path_revert_head()))
2478                return error(_("no cherry-pick or revert in progress"));
2479        return run_command_v_opt(argv, RUN_GIT_CMD);
2480}
2481
2482static int commit_staged_changes(struct replay_opts *opts)
2483{
2484        unsigned int flags = ALLOW_EMPTY | EDIT_MSG;
2485
2486        if (has_unstaged_changes(1))
2487                return error(_("cannot rebase: You have unstaged changes."));
2488        if (!has_uncommitted_changes(0)) {
2489                const char *cherry_pick_head = git_path_cherry_pick_head();
2490
2491                if (file_exists(cherry_pick_head) && unlink(cherry_pick_head))
2492                        return error(_("could not remove CHERRY_PICK_HEAD"));
2493                return 0;
2494        }
2495
2496        if (file_exists(rebase_path_amend())) {
2497                struct strbuf rev = STRBUF_INIT;
2498                struct object_id head, to_amend;
2499
2500                if (get_oid("HEAD", &head))
2501                        return error(_("cannot amend non-existing commit"));
2502                if (!read_oneliner(&rev, rebase_path_amend(), 0))
2503                        return error(_("invalid file: '%s'"), rebase_path_amend());
2504                if (get_oid_hex(rev.buf, &to_amend))
2505                        return error(_("invalid contents: '%s'"),
2506                                rebase_path_amend());
2507                if (oidcmp(&head, &to_amend))
2508                        return error(_("\nYou have uncommitted changes in your "
2509                                       "working tree. Please, commit them\n"
2510                                       "first and then run 'git rebase "
2511                                       "--continue' again."));
2512
2513                strbuf_release(&rev);
2514                flags |= AMEND_MSG;
2515        }
2516
2517        if (run_git_commit(rebase_path_message(), opts, flags))
2518                return error(_("could not commit staged changes."));
2519        unlink(rebase_path_amend());
2520        return 0;
2521}
2522
2523int sequencer_continue(struct replay_opts *opts)
2524{
2525        struct todo_list todo_list = TODO_LIST_INIT;
2526        int res;
2527
2528        if (read_and_refresh_cache(opts))
2529                return -1;
2530
2531        if (is_rebase_i(opts)) {
2532                if (commit_staged_changes(opts))
2533                        return -1;
2534        } else if (!file_exists(get_todo_path(opts)))
2535                return continue_single_pick();
2536        if (read_populate_opts(opts))
2537                return -1;
2538        if ((res = read_populate_todo(&todo_list, opts)))
2539                goto release_todo_list;
2540
2541        if (!is_rebase_i(opts)) {
2542                /* Verify that the conflict has been resolved */
2543                if (file_exists(git_path_cherry_pick_head()) ||
2544                    file_exists(git_path_revert_head())) {
2545                        res = continue_single_pick();
2546                        if (res)
2547                                goto release_todo_list;
2548                }
2549                if (index_differs_from("HEAD", NULL, 0)) {
2550                        res = error_dirty_index(opts);
2551                        goto release_todo_list;
2552                }
2553                todo_list.current++;
2554        } else if (file_exists(rebase_path_stopped_sha())) {
2555                struct strbuf buf = STRBUF_INIT;
2556                struct object_id oid;
2557
2558                if (read_oneliner(&buf, rebase_path_stopped_sha(), 1) &&
2559                    !get_oid_committish(buf.buf, &oid))
2560                        record_in_rewritten(&oid, peek_command(&todo_list, 0));
2561                strbuf_release(&buf);
2562        }
2563
2564        res = pick_commits(&todo_list, opts);
2565release_todo_list:
2566        todo_list_release(&todo_list);
2567        return res;
2568}
2569
2570static int single_pick(struct commit *cmit, struct replay_opts *opts)
2571{
2572        setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
2573        return do_pick_commit(opts->action == REPLAY_PICK ?
2574                TODO_PICK : TODO_REVERT, cmit, opts, 0);
2575}
2576
2577int sequencer_pick_revisions(struct replay_opts *opts)
2578{
2579        struct todo_list todo_list = TODO_LIST_INIT;
2580        struct object_id oid;
2581        int i, res;
2582
2583        assert(opts->revs);
2584        if (read_and_refresh_cache(opts))
2585                return -1;
2586
2587        for (i = 0; i < opts->revs->pending.nr; i++) {
2588                struct object_id oid;
2589                const char *name = opts->revs->pending.objects[i].name;
2590
2591                /* This happens when using --stdin. */
2592                if (!strlen(name))
2593                        continue;
2594
2595                if (!get_oid(name, &oid)) {
2596                        if (!lookup_commit_reference_gently(&oid, 1)) {
2597                                enum object_type type = sha1_object_info(oid.hash, NULL);
2598                                return error(_("%s: can't cherry-pick a %s"),
2599                                        name, typename(type));
2600                        }
2601                } else
2602                        return error(_("%s: bad revision"), name);
2603        }
2604
2605        /*
2606         * If we were called as "git cherry-pick <commit>", just
2607         * cherry-pick/revert it, set CHERRY_PICK_HEAD /
2608         * REVERT_HEAD, and don't touch the sequencer state.
2609         * This means it is possible to cherry-pick in the middle
2610         * of a cherry-pick sequence.
2611         */
2612        if (opts->revs->cmdline.nr == 1 &&
2613            opts->revs->cmdline.rev->whence == REV_CMD_REV &&
2614            opts->revs->no_walk &&
2615            !opts->revs->cmdline.rev->flags) {
2616                struct commit *cmit;
2617                if (prepare_revision_walk(opts->revs))
2618                        return error(_("revision walk setup failed"));
2619                cmit = get_revision(opts->revs);
2620                if (!cmit || get_revision(opts->revs))
2621                        return error("BUG: expected exactly one commit from walk");
2622                return single_pick(cmit, opts);
2623        }
2624
2625        /*
2626         * Start a new cherry-pick/ revert sequence; but
2627         * first, make sure that an existing one isn't in
2628         * progress
2629         */
2630
2631        if (walk_revs_populate_todo(&todo_list, opts) ||
2632                        create_seq_dir() < 0)
2633                return -1;
2634        if (get_oid("HEAD", &oid) && (opts->action == REPLAY_REVERT))
2635                return error(_("can't revert as initial commit"));
2636        if (save_head(oid_to_hex(&oid)))
2637                return -1;
2638        if (save_opts(opts))
2639                return -1;
2640        update_abort_safety_file();
2641        res = pick_commits(&todo_list, opts);
2642        todo_list_release(&todo_list);
2643        return res;
2644}
2645
2646void append_signoff(struct strbuf *msgbuf, int ignore_footer, unsigned flag)
2647{
2648        unsigned no_dup_sob = flag & APPEND_SIGNOFF_DEDUP;
2649        struct strbuf sob = STRBUF_INIT;
2650        int has_footer;
2651
2652        strbuf_addstr(&sob, sign_off_header);
2653        strbuf_addstr(&sob, fmt_name(getenv("GIT_COMMITTER_NAME"),
2654                                getenv("GIT_COMMITTER_EMAIL")));
2655        strbuf_addch(&sob, '\n');
2656
2657        if (!ignore_footer)
2658                strbuf_complete_line(msgbuf);
2659
2660        /*
2661         * If the whole message buffer is equal to the sob, pretend that we
2662         * found a conforming footer with a matching sob
2663         */
2664        if (msgbuf->len - ignore_footer == sob.len &&
2665            !strncmp(msgbuf->buf, sob.buf, sob.len))
2666                has_footer = 3;
2667        else
2668                has_footer = has_conforming_footer(msgbuf, &sob, ignore_footer);
2669
2670        if (!has_footer) {
2671                const char *append_newlines = NULL;
2672                size_t len = msgbuf->len - ignore_footer;
2673
2674                if (!len) {
2675                        /*
2676                         * The buffer is completely empty.  Leave foom for
2677                         * the title and body to be filled in by the user.
2678                         */
2679                        append_newlines = "\n\n";
2680                } else if (len == 1) {
2681                        /*
2682                         * Buffer contains a single newline.  Add another
2683                         * so that we leave room for the title and body.
2684                         */
2685                        append_newlines = "\n";
2686                } else if (msgbuf->buf[len - 2] != '\n') {
2687                        /*
2688                         * Buffer ends with a single newline.  Add another
2689                         * so that there is an empty line between the message
2690                         * body and the sob.
2691                         */
2692                        append_newlines = "\n";
2693                } /* else, the buffer already ends with two newlines. */
2694
2695                if (append_newlines)
2696                        strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
2697                                append_newlines, strlen(append_newlines));
2698        }
2699
2700        if (has_footer != 3 && (!no_dup_sob || has_footer != 2))
2701                strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
2702                                sob.buf, sob.len);
2703
2704        strbuf_release(&sob);
2705}
2706
2707int sequencer_make_script(int keep_empty, FILE *out,
2708                int argc, const char **argv)
2709{
2710        char *format = NULL;
2711        struct pretty_print_context pp = {0};
2712        struct strbuf buf = STRBUF_INIT;
2713        struct rev_info revs;
2714        struct commit *commit;
2715
2716        init_revisions(&revs, NULL);
2717        revs.verbose_header = 1;
2718        revs.max_parents = 1;
2719        revs.cherry_pick = 1;
2720        revs.limited = 1;
2721        revs.reverse = 1;
2722        revs.right_only = 1;
2723        revs.sort_order = REV_SORT_IN_GRAPH_ORDER;
2724        revs.topo_order = 1;
2725
2726        revs.pretty_given = 1;
2727        git_config_get_string("rebase.instructionFormat", &format);
2728        if (!format || !*format) {
2729                free(format);
2730                format = xstrdup("%s");
2731        }
2732        get_commit_format(format, &revs);
2733        free(format);
2734        pp.fmt = revs.commit_format;
2735        pp.output_encoding = get_log_output_encoding();
2736
2737        if (setup_revisions(argc, argv, &revs, NULL) > 1)
2738                return error(_("make_script: unhandled options"));
2739
2740        if (prepare_revision_walk(&revs) < 0)
2741                return error(_("make_script: error preparing revisions"));
2742
2743        while ((commit = get_revision(&revs))) {
2744                strbuf_reset(&buf);
2745                if (!keep_empty && is_original_commit_empty(commit))
2746                        strbuf_addf(&buf, "%c ", comment_line_char);
2747                strbuf_addf(&buf, "pick %s ", oid_to_hex(&commit->object.oid));
2748                pretty_print_commit(&pp, commit, &buf);
2749                strbuf_addch(&buf, '\n');
2750                fputs(buf.buf, out);
2751        }
2752        strbuf_release(&buf);
2753        return 0;
2754}
2755
2756
2757int transform_todo_ids(int shorten_ids)
2758{
2759        const char *todo_file = rebase_path_todo();
2760        struct todo_list todo_list = TODO_LIST_INIT;
2761        int fd, res, i;
2762        FILE *out;
2763
2764        strbuf_reset(&todo_list.buf);
2765        fd = open(todo_file, O_RDONLY);
2766        if (fd < 0)
2767                return error_errno(_("could not open '%s'"), todo_file);
2768        if (strbuf_read(&todo_list.buf, fd, 0) < 0) {
2769                close(fd);
2770                return error(_("could not read '%s'."), todo_file);
2771        }
2772        close(fd);
2773
2774        res = parse_insn_buffer(todo_list.buf.buf, &todo_list);
2775        if (res) {
2776                todo_list_release(&todo_list);
2777                return error(_("unusable todo list: '%s'"), todo_file);
2778        }
2779
2780        out = fopen(todo_file, "w");
2781        if (!out) {
2782                todo_list_release(&todo_list);
2783                return error(_("unable to open '%s' for writing"), todo_file);
2784        }
2785        for (i = 0; i < todo_list.nr; i++) {
2786                struct todo_item *item = todo_list.items + i;
2787                int bol = item->offset_in_buf;
2788                const char *p = todo_list.buf.buf + bol;
2789                int eol = i + 1 < todo_list.nr ?
2790                        todo_list.items[i + 1].offset_in_buf :
2791                        todo_list.buf.len;
2792
2793                if (item->command >= TODO_EXEC && item->command != TODO_DROP)
2794                        fwrite(p, eol - bol, 1, out);
2795                else {
2796                        const char *id = shorten_ids ?
2797                                short_commit_name(item->commit) :
2798                                oid_to_hex(&item->commit->object.oid);
2799                        int len;
2800
2801                        p += strspn(p, " \t"); /* left-trim command */
2802                        len = strcspn(p, " \t"); /* length of command */
2803
2804                        fprintf(out, "%.*s %s %.*s\n",
2805                                len, p, id, item->arg_len, item->arg);
2806                }
2807        }
2808        fclose(out);
2809        todo_list_release(&todo_list);
2810        return 0;
2811}
2812
2813enum check_level {
2814        CHECK_IGNORE = 0, CHECK_WARN, CHECK_ERROR
2815};
2816
2817static enum check_level get_missing_commit_check_level(void)
2818{
2819        const char *value;
2820
2821        if (git_config_get_value("rebase.missingcommitscheck", &value) ||
2822                        !strcasecmp("ignore", value))
2823                return CHECK_IGNORE;
2824        if (!strcasecmp("warn", value))
2825                return CHECK_WARN;
2826        if (!strcasecmp("error", value))
2827                return CHECK_ERROR;
2828        warning(_("unrecognized setting %s for option "
2829                  "rebase.missingCommitsCheck. Ignoring."), value);
2830        return CHECK_IGNORE;
2831}
2832
2833/*
2834 * Check if the user dropped some commits by mistake
2835 * Behaviour determined by rebase.missingCommitsCheck.
2836 * Check if there is an unrecognized command or a
2837 * bad SHA-1 in a command.
2838 */
2839int check_todo_list(void)
2840{
2841        enum check_level check_level = get_missing_commit_check_level();
2842        struct strbuf todo_file = STRBUF_INIT;
2843        struct todo_list todo_list = TODO_LIST_INIT;
2844        struct strbuf missing = STRBUF_INIT;
2845        int advise_to_edit_todo = 0, res = 0, fd, i;
2846
2847        strbuf_addstr(&todo_file, rebase_path_todo());
2848        fd = open(todo_file.buf, O_RDONLY);
2849        if (fd < 0) {
2850                res = error_errno(_("could not open '%s'"), todo_file.buf);
2851                goto leave_check;
2852        }
2853        if (strbuf_read(&todo_list.buf, fd, 0) < 0) {
2854                close(fd);
2855                res = error(_("could not read '%s'."), todo_file.buf);
2856                goto leave_check;
2857        }
2858        close(fd);
2859        advise_to_edit_todo = res =
2860                parse_insn_buffer(todo_list.buf.buf, &todo_list);
2861
2862        if (res || check_level == CHECK_IGNORE)
2863                goto leave_check;
2864
2865        /* Mark the commits in git-rebase-todo as seen */
2866        for (i = 0; i < todo_list.nr; i++) {
2867                struct commit *commit = todo_list.items[i].commit;
2868                if (commit)
2869                        commit->util = (void *)1;
2870        }
2871
2872        todo_list_release(&todo_list);
2873        strbuf_addstr(&todo_file, ".backup");
2874        fd = open(todo_file.buf, O_RDONLY);
2875        if (fd < 0) {
2876                res = error_errno(_("could not open '%s'"), todo_file.buf);
2877                goto leave_check;
2878        }
2879        if (strbuf_read(&todo_list.buf, fd, 0) < 0) {
2880                close(fd);
2881                res = error(_("could not read '%s'."), todo_file.buf);
2882                goto leave_check;
2883        }
2884        close(fd);
2885        strbuf_release(&todo_file);
2886        res = !!parse_insn_buffer(todo_list.buf.buf, &todo_list);
2887
2888        /* Find commits in git-rebase-todo.backup yet unseen */
2889        for (i = todo_list.nr - 1; i >= 0; i--) {
2890                struct todo_item *item = todo_list.items + i;
2891                struct commit *commit = item->commit;
2892                if (commit && !commit->util) {
2893                        strbuf_addf(&missing, " - %s %.*s\n",
2894                                    short_commit_name(commit),
2895                                    item->arg_len, item->arg);
2896                        commit->util = (void *)1;
2897                }
2898        }
2899
2900        /* Warn about missing commits */
2901        if (!missing.len)
2902                goto leave_check;
2903
2904        if (check_level == CHECK_ERROR)
2905                advise_to_edit_todo = res = 1;
2906
2907        fprintf(stderr,
2908                _("Warning: some commits may have been dropped accidentally.\n"
2909                "Dropped commits (newer to older):\n"));
2910
2911        /* Make the list user-friendly and display */
2912        fputs(missing.buf, stderr);
2913        strbuf_release(&missing);
2914
2915        fprintf(stderr, _("To avoid this message, use \"drop\" to "
2916                "explicitly remove a commit.\n\n"
2917                "Use 'git config rebase.missingCommitsCheck' to change "
2918                "the level of warnings.\n"
2919                "The possible behaviours are: ignore, warn, error.\n\n"));
2920
2921leave_check:
2922        strbuf_release(&todo_file);
2923        todo_list_release(&todo_list);
2924
2925        if (advise_to_edit_todo)
2926                fprintf(stderr,
2927                        _("You can fix this with 'git rebase --edit-todo' "
2928                          "and then run 'git rebase --continue'.\n"
2929                          "Or you can abort the rebase with 'git rebase"
2930                          " --abort'.\n"));
2931
2932        return res;
2933}
2934
2935/* skip picking commits whose parents are unchanged */
2936int skip_unnecessary_picks(void)
2937{
2938        const char *todo_file = rebase_path_todo();
2939        struct strbuf buf = STRBUF_INIT;
2940        struct todo_list todo_list = TODO_LIST_INIT;
2941        struct object_id onto_oid, *oid = &onto_oid, *parent_oid;
2942        int fd, i;
2943
2944        if (!read_oneliner(&buf, rebase_path_onto(), 0))
2945                return error(_("could not read 'onto'"));
2946        if (get_oid(buf.buf, &onto_oid)) {
2947                strbuf_release(&buf);
2948                return error(_("need a HEAD to fixup"));
2949        }
2950        strbuf_release(&buf);
2951
2952        fd = open(todo_file, O_RDONLY);
2953        if (fd < 0) {
2954                return error_errno(_("could not open '%s'"), todo_file);
2955        }
2956        if (strbuf_read(&todo_list.buf, fd, 0) < 0) {
2957                close(fd);
2958                return error(_("could not read '%s'."), todo_file);
2959        }
2960        close(fd);
2961        if (parse_insn_buffer(todo_list.buf.buf, &todo_list) < 0) {
2962                todo_list_release(&todo_list);
2963                return -1;
2964        }
2965
2966        for (i = 0; i < todo_list.nr; i++) {
2967                struct todo_item *item = todo_list.items + i;
2968
2969                if (item->command >= TODO_NOOP)
2970                        continue;
2971                if (item->command != TODO_PICK)
2972                        break;
2973                if (parse_commit(item->commit)) {
2974                        todo_list_release(&todo_list);
2975                        return error(_("could not parse commit '%s'"),
2976                                oid_to_hex(&item->commit->object.oid));
2977                }
2978                if (!item->commit->parents)
2979                        break; /* root commit */
2980                if (item->commit->parents->next)
2981                        break; /* merge commit */
2982                parent_oid = &item->commit->parents->item->object.oid;
2983                if (hashcmp(parent_oid->hash, oid->hash))
2984                        break;
2985                oid = &item->commit->object.oid;
2986        }
2987        if (i > 0) {
2988                int offset = i < todo_list.nr ?
2989                        todo_list.items[i].offset_in_buf : todo_list.buf.len;
2990                const char *done_path = rebase_path_done();
2991
2992                fd = open(done_path, O_CREAT | O_WRONLY | O_APPEND, 0666);
2993                if (fd < 0) {
2994                        error_errno(_("could not open '%s' for writing"),
2995                                    done_path);
2996                        todo_list_release(&todo_list);
2997                        return -1;
2998                }
2999                if (write_in_full(fd, todo_list.buf.buf, offset) < 0) {
3000                        error_errno(_("could not write to '%s'"), done_path);
3001                        todo_list_release(&todo_list);
3002                        close(fd);
3003                        return -1;
3004                }
3005                close(fd);
3006
3007                fd = open(rebase_path_todo(), O_WRONLY, 0666);
3008                if (fd < 0) {
3009                        error_errno(_("could not open '%s' for writing"),
3010                                    rebase_path_todo());
3011                        todo_list_release(&todo_list);
3012                        return -1;
3013                }
3014                if (write_in_full(fd, todo_list.buf.buf + offset,
3015                                todo_list.buf.len - offset) < 0) {
3016                        error_errno(_("could not write to '%s'"),
3017                                    rebase_path_todo());
3018                        close(fd);
3019                        todo_list_release(&todo_list);
3020                        return -1;
3021                }
3022                if (ftruncate(fd, todo_list.buf.len - offset) < 0) {
3023                        error_errno(_("could not truncate '%s'"),
3024                                    rebase_path_todo());
3025                        todo_list_release(&todo_list);
3026                        close(fd);
3027                        return -1;
3028                }
3029                close(fd);
3030
3031                todo_list.current = i;
3032                if (is_fixup(peek_command(&todo_list, 0)))
3033                        record_in_rewritten(oid, peek_command(&todo_list, 0));
3034        }
3035
3036        todo_list_release(&todo_list);
3037        printf("%s\n", oid_to_hex(oid));
3038
3039        return 0;
3040}
3041
3042struct subject2item_entry {
3043        struct hashmap_entry entry;
3044        int i;
3045        char subject[FLEX_ARRAY];
3046};
3047
3048static int subject2item_cmp(const void *fndata,
3049                            const struct subject2item_entry *a,
3050                            const struct subject2item_entry *b, const void *key)
3051{
3052        return key ? strcmp(a->subject, key) : strcmp(a->subject, b->subject);
3053}
3054
3055/*
3056 * Rearrange the todo list that has both "pick commit-id msg" and "pick
3057 * commit-id fixup!/squash! msg" in it so that the latter is put immediately
3058 * after the former, and change "pick" to "fixup"/"squash".
3059 *
3060 * Note that if the config has specified a custom instruction format, each log
3061 * message will have to be retrieved from the commit (as the oneline in the
3062 * script cannot be trusted) in order to normalize the autosquash arrangement.
3063 */
3064int rearrange_squash(void)
3065{
3066        const char *todo_file = rebase_path_todo();
3067        struct todo_list todo_list = TODO_LIST_INIT;
3068        struct hashmap subject2item;
3069        int res = 0, rearranged = 0, *next, *tail, fd, i;
3070        char **subjects;
3071
3072        fd = open(todo_file, O_RDONLY);
3073        if (fd < 0)
3074                return error_errno(_("could not open '%s'"), todo_file);
3075        if (strbuf_read(&todo_list.buf, fd, 0) < 0) {
3076                close(fd);
3077                return error(_("could not read '%s'."), todo_file);
3078        }
3079        close(fd);
3080        if (parse_insn_buffer(todo_list.buf.buf, &todo_list) < 0) {
3081                todo_list_release(&todo_list);
3082                return -1;
3083        }
3084
3085        /*
3086         * The hashmap maps onelines to the respective todo list index.
3087         *
3088         * If any items need to be rearranged, the next[i] value will indicate
3089         * which item was moved directly after the i'th.
3090         *
3091         * In that case, last[i] will indicate the index of the latest item to
3092         * be moved to appear after the i'th.
3093         */
3094        hashmap_init(&subject2item, (hashmap_cmp_fn) subject2item_cmp,
3095                     NULL, todo_list.nr);
3096        ALLOC_ARRAY(next, todo_list.nr);
3097        ALLOC_ARRAY(tail, todo_list.nr);
3098        ALLOC_ARRAY(subjects, todo_list.nr);
3099        for (i = 0; i < todo_list.nr; i++) {
3100                struct strbuf buf = STRBUF_INIT;
3101                struct todo_item *item = todo_list.items + i;
3102                const char *commit_buffer, *subject, *p;
3103                size_t subject_len;
3104                int i2 = -1;
3105                struct subject2item_entry *entry;
3106
3107                next[i] = tail[i] = -1;
3108                if (item->command >= TODO_EXEC) {
3109                        subjects[i] = NULL;
3110                        continue;
3111                }
3112
3113                if (is_fixup(item->command)) {
3114                        todo_list_release(&todo_list);
3115                        return error(_("the script was already rearranged."));
3116                }
3117
3118                item->commit->util = item;
3119
3120                parse_commit(item->commit);
3121                commit_buffer = get_commit_buffer(item->commit, NULL);
3122                find_commit_subject(commit_buffer, &subject);
3123                format_subject(&buf, subject, " ");
3124                subject = subjects[i] = strbuf_detach(&buf, &subject_len);
3125                unuse_commit_buffer(item->commit, commit_buffer);
3126                if ((skip_prefix(subject, "fixup! ", &p) ||
3127                     skip_prefix(subject, "squash! ", &p))) {
3128                        struct commit *commit2;
3129
3130                        for (;;) {
3131                                while (isspace(*p))
3132                                        p++;
3133                                if (!skip_prefix(p, "fixup! ", &p) &&
3134                                    !skip_prefix(p, "squash! ", &p))
3135                                        break;
3136                        }
3137
3138                        if ((entry = hashmap_get_from_hash(&subject2item,
3139                                                           strhash(p), p)))
3140                                /* found by title */
3141                                i2 = entry->i;
3142                        else if (!strchr(p, ' ') &&
3143                                 (commit2 =
3144                                  lookup_commit_reference_by_name(p)) &&
3145                                 commit2->util)
3146                                /* found by commit name */
3147                                i2 = (struct todo_item *)commit2->util
3148                                        - todo_list.items;
3149                        else {
3150                                /* copy can be a prefix of the commit subject */
3151                                for (i2 = 0; i2 < i; i2++)
3152                                        if (subjects[i2] &&
3153                                            starts_with(subjects[i2], p))
3154                                                break;
3155                                if (i2 == i)
3156                                        i2 = -1;
3157                        }
3158                }
3159                if (i2 >= 0) {
3160                        rearranged = 1;
3161                        todo_list.items[i].command =
3162                                starts_with(subject, "fixup!") ?
3163                                TODO_FIXUP : TODO_SQUASH;
3164                        if (next[i2] < 0)
3165                                next[i2] = i;
3166                        else
3167                                next[tail[i2]] = i;
3168                        tail[i2] = i;
3169                } else if (!hashmap_get_from_hash(&subject2item,
3170                                                strhash(subject), subject)) {
3171                        FLEX_ALLOC_MEM(entry, subject, subject, subject_len);
3172                        entry->i = i;
3173                        hashmap_entry_init(entry, strhash(entry->subject));
3174                        hashmap_put(&subject2item, entry);
3175                }
3176        }
3177
3178        if (rearranged) {
3179                struct strbuf buf = STRBUF_INIT;
3180
3181                for (i = 0; i < todo_list.nr; i++) {
3182                        enum todo_command command = todo_list.items[i].command;
3183                        int cur = i;
3184
3185                        /*
3186                         * Initially, all commands are 'pick's. If it is a
3187                         * fixup or a squash now, we have rearranged it.
3188                         */
3189                        if (is_fixup(command))
3190                                continue;
3191
3192                        while (cur >= 0) {
3193                                int offset = todo_list.items[cur].offset_in_buf;
3194                                int end_offset = cur + 1 < todo_list.nr ?
3195                                        todo_list.items[cur + 1].offset_in_buf :
3196                                        todo_list.buf.len;
3197                                char *bol = todo_list.buf.buf + offset;
3198                                char *eol = todo_list.buf.buf + end_offset;
3199
3200                                /* replace 'pick', by 'fixup' or 'squash' */
3201                                command = todo_list.items[cur].command;
3202                                if (is_fixup(command)) {
3203                                        strbuf_addstr(&buf,
3204                                                todo_command_info[command].str);
3205                                        bol += strcspn(bol, " \t");
3206                                }
3207
3208                                strbuf_add(&buf, bol, eol - bol);
3209
3210                                cur = next[cur];
3211                        }
3212                }
3213
3214                fd = open(todo_file, O_WRONLY);
3215                if (fd < 0)
3216                        res = error_errno(_("could not open '%s'"), todo_file);
3217                else if (write(fd, buf.buf, buf.len) < 0)
3218                        res = error_errno(_("could not write to '%s'"), todo_file);
3219                else if (ftruncate(fd, buf.len) < 0)
3220                        res = error_errno(_("could not truncate '%s'"),
3221                                           todo_file);
3222                close(fd);
3223                strbuf_release(&buf);
3224        }
3225
3226        free(next);
3227        free(tail);
3228        for (i = 0; i < todo_list.nr; i++)
3229                free(subjects[i]);
3230        free(subjects);
3231        hashmap_free(&subject2item, 1);
3232        todo_list_release(&todo_list);
3233
3234        return res;
3235}