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