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