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