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