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