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