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