41f80ea2c42095684978854daa061be087d6d1bb
   1#include "cache.h"
   2#include "lockfile.h"
   3#include "sequencer.h"
   4#include "dir.h"
   5#include "object.h"
   6#include "commit.h"
   7#include "tag.h"
   8#include "run-command.h"
   9#include "exec_cmd.h"
  10#include "utf8.h"
  11#include "cache-tree.h"
  12#include "diff.h"
  13#include "revision.h"
  14#include "rerere.h"
  15#include "merge-recursive.h"
  16#include "refs.h"
  17#include "argv-array.h"
  18#include "quote.h"
  19#include "trailer.h"
  20#include "log-tree.h"
  21#include "wt-status.h"
  22
  23#define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
  24
  25const char sign_off_header[] = "Signed-off-by: ";
  26static const char cherry_picked_prefix[] = "(cherry picked from commit ";
  27
  28GIT_PATH_FUNC(git_path_seq_dir, "sequencer")
  29
  30static GIT_PATH_FUNC(git_path_todo_file, "sequencer/todo")
  31static GIT_PATH_FUNC(git_path_opts_file, "sequencer/opts")
  32static GIT_PATH_FUNC(git_path_head_file, "sequencer/head")
  33static GIT_PATH_FUNC(git_path_abort_safety_file, "sequencer/abort-safety")
  34
  35static GIT_PATH_FUNC(rebase_path, "rebase-merge")
  36/*
  37 * The file containing rebase commands, comments, and empty lines.
  38 * This file is created by "git rebase -i" then edited by the user. As
  39 * the lines are processed, they are removed from the front of this
  40 * file and written to the tail of 'done'.
  41 */
  42static GIT_PATH_FUNC(rebase_path_todo, "rebase-merge/git-rebase-todo")
  43/*
  44 * The rebase command lines that have already been processed. A line
  45 * is moved here when it is first handled, before any associated user
  46 * actions.
  47 */
  48static GIT_PATH_FUNC(rebase_path_done, "rebase-merge/done")
  49/*
  50 * The commit message that is planned to be used for any changes that
  51 * need to be committed following a user interaction.
  52 */
  53static GIT_PATH_FUNC(rebase_path_message, "rebase-merge/message")
  54/*
  55 * The file into which is accumulated the suggested commit message for
  56 * squash/fixup commands. When the first of a series of squash/fixups
  57 * is seen, the file is created and the commit message from the
  58 * previous commit and from the first squash/fixup commit are written
  59 * to it. The commit message for each subsequent squash/fixup commit
  60 * is appended to the file as it is processed.
  61 *
  62 * The first line of the file is of the form
  63 *     # This is a combination of $count commits.
  64 * where $count is the number of commits whose messages have been
  65 * written to the file so far (including the initial "pick" commit).
  66 * Each time that a commit message is processed, this line is read and
  67 * updated. It is deleted just before the combined commit is made.
  68 */
  69static GIT_PATH_FUNC(rebase_path_squash_msg, "rebase-merge/message-squash")
  70/*
  71 * If the current series of squash/fixups has not yet included a squash
  72 * command, then this file exists and holds the commit message of the
  73 * original "pick" commit.  (If the series ends without a "squash"
  74 * command, then this can be used as the commit message of the combined
  75 * commit without opening the editor.)
  76 */
  77static GIT_PATH_FUNC(rebase_path_fixup_msg, "rebase-merge/message-fixup")
  78/*
  79 * A script to set the GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL, and
  80 * GIT_AUTHOR_DATE that will be used for the commit that is currently
  81 * being rebased.
  82 */
  83static GIT_PATH_FUNC(rebase_path_author_script, "rebase-merge/author-script")
  84/*
  85 * When an "edit" rebase command is being processed, the SHA1 of the
  86 * commit to be edited is recorded in this file.  When "git rebase
  87 * --continue" is executed, if there are any staged changes then they
  88 * will be amended to the HEAD commit, but only provided the HEAD
  89 * commit is still the commit to be edited.  When any other rebase
  90 * command is processed, this file is deleted.
  91 */
  92static GIT_PATH_FUNC(rebase_path_amend, "rebase-merge/amend")
  93/*
  94 * When we stop at a given patch via the "edit" command, this file contains
  95 * the abbreviated commit name of the corresponding patch.
  96 */
  97static GIT_PATH_FUNC(rebase_path_stopped_sha, "rebase-merge/stopped-sha")
  98/*
  99 * For the post-rewrite hook, we make a list of rewritten commits and
 100 * their new sha1s.  The rewritten-pending list keeps the sha1s of
 101 * commits that have been processed, but not committed yet,
 102 * e.g. because they are waiting for a 'squash' command.
 103 */
 104static GIT_PATH_FUNC(rebase_path_rewritten_list, "rebase-merge/rewritten-list")
 105static GIT_PATH_FUNC(rebase_path_rewritten_pending,
 106        "rebase-merge/rewritten-pending")
 107/*
 108 * The following files are written by git-rebase just after parsing the
 109 * command-line (and are only consumed, not modified, by the sequencer).
 110 */
 111static GIT_PATH_FUNC(rebase_path_gpg_sign_opt, "rebase-merge/gpg_sign_opt")
 112static GIT_PATH_FUNC(rebase_path_orig_head, "rebase-merge/orig-head")
 113static GIT_PATH_FUNC(rebase_path_verbose, "rebase-merge/verbose")
 114static GIT_PATH_FUNC(rebase_path_head_name, "rebase-merge/head-name")
 115static GIT_PATH_FUNC(rebase_path_onto, "rebase-merge/onto")
 116static GIT_PATH_FUNC(rebase_path_autostash, "rebase-merge/autostash")
 117static GIT_PATH_FUNC(rebase_path_strategy, "rebase-merge/strategy")
 118static GIT_PATH_FUNC(rebase_path_strategy_opts, "rebase-merge/strategy_opts")
 119
 120static inline int is_rebase_i(const struct replay_opts *opts)
 121{
 122        return opts->action == REPLAY_INTERACTIVE_REBASE;
 123}
 124
 125static const char *get_dir(const struct replay_opts *opts)
 126{
 127        if (is_rebase_i(opts))
 128                return rebase_path();
 129        return git_path_seq_dir();
 130}
 131
 132static const char *get_todo_path(const struct replay_opts *opts)
 133{
 134        if (is_rebase_i(opts))
 135                return rebase_path_todo();
 136        return git_path_todo_file();
 137}
 138
 139/*
 140 * Returns 0 for non-conforming footer
 141 * Returns 1 for conforming footer
 142 * Returns 2 when sob exists within conforming footer
 143 * Returns 3 when sob exists within conforming footer as last entry
 144 */
 145static int has_conforming_footer(struct strbuf *sb, struct strbuf *sob,
 146        int ignore_footer)
 147{
 148        struct trailer_info info;
 149        int i;
 150        int found_sob = 0, found_sob_last = 0;
 151
 152        trailer_info_get(&info, sb->buf);
 153
 154        if (info.trailer_start == info.trailer_end)
 155                return 0;
 156
 157        for (i = 0; i < info.trailer_nr; i++)
 158                if (sob && !strncmp(info.trailers[i], sob->buf, sob->len)) {
 159                        found_sob = 1;
 160                        if (i == info.trailer_nr - 1)
 161                                found_sob_last = 1;
 162                }
 163
 164        trailer_info_release(&info);
 165
 166        if (found_sob_last)
 167                return 3;
 168        if (found_sob)
 169                return 2;
 170        return 1;
 171}
 172
 173static const char *gpg_sign_opt_quoted(struct replay_opts *opts)
 174{
 175        static struct strbuf buf = STRBUF_INIT;
 176
 177        strbuf_reset(&buf);
 178        if (opts->gpg_sign)
 179                sq_quotef(&buf, "-S%s", opts->gpg_sign);
 180        return buf.buf;
 181}
 182
 183int sequencer_remove_state(struct replay_opts *opts)
 184{
 185        struct strbuf dir = STRBUF_INIT;
 186        int i;
 187
 188        free(opts->gpg_sign);
 189        free(opts->strategy);
 190        for (i = 0; i < opts->xopts_nr; i++)
 191                free(opts->xopts[i]);
 192        free(opts->xopts);
 193
 194        strbuf_addf(&dir, "%s", get_dir(opts));
 195        remove_dir_recursively(&dir, 0);
 196        strbuf_release(&dir);
 197
 198        return 0;
 199}
 200
 201static const char *action_name(const struct replay_opts *opts)
 202{
 203        switch (opts->action) {
 204        case REPLAY_REVERT:
 205                return N_("revert");
 206        case REPLAY_PICK:
 207                return N_("cherry-pick");
 208        case REPLAY_INTERACTIVE_REBASE:
 209                return N_("rebase -i");
 210        }
 211        die(_("Unknown action: %d"), opts->action);
 212}
 213
 214struct commit_message {
 215        char *parent_label;
 216        char *label;
 217        char *subject;
 218        const char *message;
 219};
 220
 221static const char *short_commit_name(struct commit *commit)
 222{
 223        return find_unique_abbrev(commit->object.oid.hash, DEFAULT_ABBREV);
 224}
 225
 226static int get_message(struct commit *commit, struct commit_message *out)
 227{
 228        const char *abbrev, *subject;
 229        int subject_len;
 230
 231        out->message = logmsg_reencode(commit, NULL, get_commit_output_encoding());
 232        abbrev = short_commit_name(commit);
 233
 234        subject_len = find_commit_subject(out->message, &subject);
 235
 236        out->subject = xmemdupz(subject, subject_len);
 237        out->label = xstrfmt("%s... %s", abbrev, out->subject);
 238        out->parent_label = xstrfmt("parent of %s", out->label);
 239
 240        return 0;
 241}
 242
 243static void free_message(struct commit *commit, struct commit_message *msg)
 244{
 245        free(msg->parent_label);
 246        free(msg->label);
 247        free(msg->subject);
 248        unuse_commit_buffer(commit, msg->message);
 249}
 250
 251static void print_advice(int show_hint, struct replay_opts *opts)
 252{
 253        char *msg = getenv("GIT_CHERRY_PICK_HELP");
 254
 255        if (msg) {
 256                fprintf(stderr, "%s\n", msg);
 257                /*
 258                 * A conflict has occurred but the porcelain
 259                 * (typically rebase --interactive) wants to take care
 260                 * of the commit itself so remove CHERRY_PICK_HEAD
 261                 */
 262                unlink(git_path_cherry_pick_head());
 263                return;
 264        }
 265
 266        if (show_hint) {
 267                if (opts->no_commit)
 268                        advise(_("after resolving the conflicts, mark the corrected paths\n"
 269                                 "with 'git add <paths>' or 'git rm <paths>'"));
 270                else
 271                        advise(_("after resolving the conflicts, mark the corrected paths\n"
 272                                 "with 'git add <paths>' or 'git rm <paths>'\n"
 273                                 "and commit the result with 'git commit'"));
 274        }
 275}
 276
 277static int write_message(const void *buf, size_t len, const char *filename,
 278                         int append_eol)
 279{
 280        static struct lock_file msg_file;
 281
 282        int msg_fd = hold_lock_file_for_update(&msg_file, filename, 0);
 283        if (msg_fd < 0)
 284                return error_errno(_("could not lock '%s'"), filename);
 285        if (write_in_full(msg_fd, buf, len) < 0) {
 286                rollback_lock_file(&msg_file);
 287                return error_errno(_("could not write to '%s'"), filename);
 288        }
 289        if (append_eol && write(msg_fd, "\n", 1) < 0) {
 290                rollback_lock_file(&msg_file);
 291                return error_errno(_("could not write eol to '%s'"), filename);
 292        }
 293        if (commit_lock_file(&msg_file) < 0) {
 294                rollback_lock_file(&msg_file);
 295                return error(_("failed to finalize '%s'."), filename);
 296        }
 297
 298        return 0;
 299}
 300
 301/*
 302 * Reads a file that was presumably written by a shell script, i.e. with an
 303 * end-of-line marker that needs to be stripped.
 304 *
 305 * Note that only the last end-of-line marker is stripped, consistent with the
 306 * behavior of "$(cat path)" in a shell script.
 307 *
 308 * Returns 1 if the file was read, 0 if it could not be read or does not exist.
 309 */
 310static int read_oneliner(struct strbuf *buf,
 311        const char *path, int skip_if_empty)
 312{
 313        int orig_len = buf->len;
 314
 315        if (!file_exists(path))
 316                return 0;
 317
 318        if (strbuf_read_file(buf, path, 0) < 0) {
 319                warning_errno(_("could not read '%s'"), path);
 320                return 0;
 321        }
 322
 323        if (buf->len > orig_len && buf->buf[buf->len - 1] == '\n') {
 324                if (--buf->len > orig_len && buf->buf[buf->len - 1] == '\r')
 325                        --buf->len;
 326                buf->buf[buf->len] = '\0';
 327        }
 328
 329        if (skip_if_empty && buf->len == orig_len)
 330                return 0;
 331
 332        return 1;
 333}
 334
 335static struct tree *empty_tree(void)
 336{
 337        return lookup_tree(EMPTY_TREE_SHA1_BIN);
 338}
 339
 340static int error_dirty_index(struct replay_opts *opts)
 341{
 342        if (read_cache_unmerged())
 343                return error_resolve_conflict(_(action_name(opts)));
 344
 345        error(_("your local changes would be overwritten by %s."),
 346                _(action_name(opts)));
 347
 348        if (advice_commit_before_merge)
 349                advise(_("commit your changes or stash them to proceed."));
 350        return -1;
 351}
 352
 353static void update_abort_safety_file(void)
 354{
 355        struct object_id head;
 356
 357        /* Do nothing on a single-pick */
 358        if (!file_exists(git_path_seq_dir()))
 359                return;
 360
 361        if (!get_oid("HEAD", &head))
 362                write_file(git_path_abort_safety_file(), "%s", oid_to_hex(&head));
 363        else
 364                write_file(git_path_abort_safety_file(), "%s", "");
 365}
 366
 367static int fast_forward_to(const unsigned char *to, const unsigned char *from,
 368                        int unborn, struct replay_opts *opts)
 369{
 370        struct ref_transaction *transaction;
 371        struct strbuf sb = STRBUF_INIT;
 372        struct strbuf err = STRBUF_INIT;
 373
 374        read_cache();
 375        if (checkout_fast_forward(from, to, 1))
 376                return -1; /* the callee should have complained already */
 377
 378        strbuf_addf(&sb, _("%s: fast-forward"), _(action_name(opts)));
 379
 380        transaction = ref_transaction_begin(&err);
 381        if (!transaction ||
 382            ref_transaction_update(transaction, "HEAD",
 383                                   to, unborn ? null_sha1 : from,
 384                                   0, sb.buf, &err) ||
 385            ref_transaction_commit(transaction, &err)) {
 386                ref_transaction_free(transaction);
 387                error("%s", err.buf);
 388                strbuf_release(&sb);
 389                strbuf_release(&err);
 390                return -1;
 391        }
 392
 393        strbuf_release(&sb);
 394        strbuf_release(&err);
 395        ref_transaction_free(transaction);
 396        update_abort_safety_file();
 397        return 0;
 398}
 399
 400void append_conflicts_hint(struct strbuf *msgbuf)
 401{
 402        int i;
 403
 404        strbuf_addch(msgbuf, '\n');
 405        strbuf_commented_addf(msgbuf, "Conflicts:\n");
 406        for (i = 0; i < active_nr;) {
 407                const struct cache_entry *ce = active_cache[i++];
 408                if (ce_stage(ce)) {
 409                        strbuf_commented_addf(msgbuf, "\t%s\n", ce->name);
 410                        while (i < active_nr && !strcmp(ce->name,
 411                                                        active_cache[i]->name))
 412                                i++;
 413                }
 414        }
 415}
 416
 417static int do_recursive_merge(struct commit *base, struct commit *next,
 418                              const char *base_label, const char *next_label,
 419                              unsigned char *head, struct strbuf *msgbuf,
 420                              struct replay_opts *opts)
 421{
 422        struct merge_options o;
 423        struct tree *result, *next_tree, *base_tree, *head_tree;
 424        int clean;
 425        char **xopt;
 426        static struct lock_file index_lock;
 427
 428        hold_locked_index(&index_lock, LOCK_DIE_ON_ERROR);
 429
 430        read_cache();
 431
 432        init_merge_options(&o);
 433        o.ancestor = base ? base_label : "(empty tree)";
 434        o.branch1 = "HEAD";
 435        o.branch2 = next ? next_label : "(empty tree)";
 436
 437        head_tree = parse_tree_indirect(head);
 438        next_tree = next ? next->tree : empty_tree();
 439        base_tree = base ? base->tree : empty_tree();
 440
 441        for (xopt = opts->xopts; xopt != opts->xopts + opts->xopts_nr; xopt++)
 442                parse_merge_opt(&o, *xopt);
 443
 444        clean = merge_trees(&o,
 445                            head_tree,
 446                            next_tree, base_tree, &result);
 447        strbuf_release(&o.obuf);
 448        if (clean < 0)
 449                return clean;
 450
 451        if (active_cache_changed &&
 452            write_locked_index(&the_index, &index_lock, COMMIT_LOCK))
 453                /* TRANSLATORS: %s will be "revert", "cherry-pick" or
 454                 * "rebase -i".
 455                 */
 456                return error(_("%s: Unable to write new index file"),
 457                        _(action_name(opts)));
 458        rollback_lock_file(&index_lock);
 459
 460        if (opts->signoff)
 461                append_signoff(msgbuf, 0, 0);
 462
 463        if (!clean)
 464                append_conflicts_hint(msgbuf);
 465
 466        return !clean;
 467}
 468
 469static int is_index_unchanged(void)
 470{
 471        unsigned char head_sha1[20];
 472        struct commit *head_commit;
 473
 474        if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, head_sha1, NULL))
 475                return error(_("could not resolve HEAD commit\n"));
 476
 477        head_commit = lookup_commit(head_sha1);
 478
 479        /*
 480         * If head_commit is NULL, check_commit, called from
 481         * lookup_commit, would have indicated that head_commit is not
 482         * a commit object already.  parse_commit() will return failure
 483         * without further complaints in such a case.  Otherwise, if
 484         * the commit is invalid, parse_commit() will complain.  So
 485         * there is nothing for us to say here.  Just return failure.
 486         */
 487        if (parse_commit(head_commit))
 488                return -1;
 489
 490        if (!active_cache_tree)
 491                active_cache_tree = cache_tree();
 492
 493        if (!cache_tree_fully_valid(active_cache_tree))
 494                if (cache_tree_update(&the_index, 0))
 495                        return error(_("unable to update cache tree\n"));
 496
 497        return !hashcmp(active_cache_tree->sha1, head_commit->tree->object.oid.hash);
 498}
 499
 500static int write_author_script(const char *message)
 501{
 502        struct strbuf buf = STRBUF_INIT;
 503        const char *eol;
 504        int res;
 505
 506        for (;;)
 507                if (!*message || starts_with(message, "\n")) {
 508missing_author:
 509                        /* Missing 'author' line? */
 510                        unlink(rebase_path_author_script());
 511                        return 0;
 512                } else if (skip_prefix(message, "author ", &message))
 513                        break;
 514                else if ((eol = strchr(message, '\n')))
 515                        message = eol + 1;
 516                else
 517                        goto missing_author;
 518
 519        strbuf_addstr(&buf, "GIT_AUTHOR_NAME='");
 520        while (*message && *message != '\n' && *message != '\r')
 521                if (skip_prefix(message, " <", &message))
 522                        break;
 523                else if (*message != '\'')
 524                        strbuf_addch(&buf, *(message++));
 525                else
 526                        strbuf_addf(&buf, "'\\\\%c'", *(message++));
 527        strbuf_addstr(&buf, "'\nGIT_AUTHOR_EMAIL='");
 528        while (*message && *message != '\n' && *message != '\r')
 529                if (skip_prefix(message, "> ", &message))
 530                        break;
 531                else if (*message != '\'')
 532                        strbuf_addch(&buf, *(message++));
 533                else
 534                        strbuf_addf(&buf, "'\\\\%c'", *(message++));
 535        strbuf_addstr(&buf, "'\nGIT_AUTHOR_DATE='@");
 536        while (*message && *message != '\n' && *message != '\r')
 537                if (*message != '\'')
 538                        strbuf_addch(&buf, *(message++));
 539                else
 540                        strbuf_addf(&buf, "'\\\\%c'", *(message++));
 541        res = write_message(buf.buf, buf.len, rebase_path_author_script(), 1);
 542        strbuf_release(&buf);
 543        return res;
 544}
 545
 546/*
 547 * Read the author-script file into an environment block, ready for use in
 548 * run_command(), that can be free()d afterwards.
 549 */
 550static char **read_author_script(void)
 551{
 552        struct strbuf script = STRBUF_INIT;
 553        int i, count = 0;
 554        char *p, *p2, **env;
 555        size_t env_size;
 556
 557        if (strbuf_read_file(&script, rebase_path_author_script(), 256) <= 0)
 558                return NULL;
 559
 560        for (p = script.buf; *p; p++)
 561                if (skip_prefix(p, "'\\\\''", (const char **)&p2))
 562                        strbuf_splice(&script, p - script.buf, p2 - p, "'", 1);
 563                else if (*p == '\'')
 564                        strbuf_splice(&script, p-- - script.buf, 1, "", 0);
 565                else if (*p == '\n') {
 566                        *p = '\0';
 567                        count++;
 568                }
 569
 570        env_size = (count + 1) * sizeof(*env);
 571        strbuf_grow(&script, env_size);
 572        memmove(script.buf + env_size, script.buf, script.len);
 573        p = script.buf + env_size;
 574        env = (char **)strbuf_detach(&script, NULL);
 575
 576        for (i = 0; i < count; i++) {
 577                env[i] = p;
 578                p += strlen(p) + 1;
 579        }
 580        env[count] = NULL;
 581
 582        return env;
 583}
 584
 585static const char staged_changes_advice[] =
 586N_("you have staged changes in your working tree\n"
 587"If these changes are meant to be squashed into the previous commit, run:\n"
 588"\n"
 589"  git commit --amend %s\n"
 590"\n"
 591"If they are meant to go into a new commit, run:\n"
 592"\n"
 593"  git commit %s\n"
 594"\n"
 595"In both cases, once you're done, continue with:\n"
 596"\n"
 597"  git rebase --continue\n");
 598
 599/*
 600 * If we are cherry-pick, and if the merge did not result in
 601 * hand-editing, we will hit this commit and inherit the original
 602 * author date and name.
 603 *
 604 * If we are revert, or if our cherry-pick results in a hand merge,
 605 * we had better say that the current user is responsible for that.
 606 *
 607 * An exception is when run_git_commit() is called during an
 608 * interactive rebase: in that case, we will want to retain the
 609 * author metadata.
 610 */
 611static int run_git_commit(const char *defmsg, struct replay_opts *opts,
 612                          int allow_empty, int edit, int amend,
 613                          int cleanup_commit_message)
 614{
 615        char **env = NULL;
 616        struct argv_array array;
 617        int rc;
 618        const char *value;
 619
 620        if (is_rebase_i(opts)) {
 621                env = read_author_script();
 622                if (!env) {
 623                        const char *gpg_opt = gpg_sign_opt_quoted(opts);
 624
 625                        return error(_(staged_changes_advice),
 626                                     gpg_opt, gpg_opt);
 627                }
 628        }
 629
 630        argv_array_init(&array);
 631        argv_array_push(&array, "commit");
 632        argv_array_push(&array, "-n");
 633
 634        if (amend)
 635                argv_array_push(&array, "--amend");
 636        if (opts->gpg_sign)
 637                argv_array_pushf(&array, "-S%s", opts->gpg_sign);
 638        if (opts->signoff)
 639                argv_array_push(&array, "-s");
 640        if (defmsg)
 641                argv_array_pushl(&array, "-F", defmsg, NULL);
 642        if (cleanup_commit_message)
 643                argv_array_push(&array, "--cleanup=strip");
 644        if (edit)
 645                argv_array_push(&array, "-e");
 646        else if (!cleanup_commit_message &&
 647                 !opts->signoff && !opts->record_origin &&
 648                 git_config_get_value("commit.cleanup", &value))
 649                argv_array_push(&array, "--cleanup=verbatim");
 650
 651        if (allow_empty)
 652                argv_array_push(&array, "--allow-empty");
 653
 654        if (opts->allow_empty_message)
 655                argv_array_push(&array, "--allow-empty-message");
 656
 657        rc = run_command_v_opt_cd_env(array.argv, RUN_GIT_CMD, NULL,
 658                        (const char *const *)env);
 659        argv_array_clear(&array);
 660        free(env);
 661
 662        return rc;
 663}
 664
 665static int is_original_commit_empty(struct commit *commit)
 666{
 667        const unsigned char *ptree_sha1;
 668
 669        if (parse_commit(commit))
 670                return error(_("could not parse commit %s\n"),
 671                             oid_to_hex(&commit->object.oid));
 672        if (commit->parents) {
 673                struct commit *parent = commit->parents->item;
 674                if (parse_commit(parent))
 675                        return error(_("could not parse parent commit %s\n"),
 676                                oid_to_hex(&parent->object.oid));
 677                ptree_sha1 = parent->tree->object.oid.hash;
 678        } else {
 679                ptree_sha1 = EMPTY_TREE_SHA1_BIN; /* commit is root */
 680        }
 681
 682        return !hashcmp(ptree_sha1, commit->tree->object.oid.hash);
 683}
 684
 685/*
 686 * Do we run "git commit" with "--allow-empty"?
 687 */
 688static int allow_empty(struct replay_opts *opts, struct commit *commit)
 689{
 690        int index_unchanged, empty_commit;
 691
 692        /*
 693         * Three cases:
 694         *
 695         * (1) we do not allow empty at all and error out.
 696         *
 697         * (2) we allow ones that were initially empty, but
 698         * forbid the ones that become empty;
 699         *
 700         * (3) we allow both.
 701         */
 702        if (!opts->allow_empty)
 703                return 0; /* let "git commit" barf as necessary */
 704
 705        index_unchanged = is_index_unchanged();
 706        if (index_unchanged < 0)
 707                return index_unchanged;
 708        if (!index_unchanged)
 709                return 0; /* we do not have to say --allow-empty */
 710
 711        if (opts->keep_redundant_commits)
 712                return 1;
 713
 714        empty_commit = is_original_commit_empty(commit);
 715        if (empty_commit < 0)
 716                return empty_commit;
 717        if (!empty_commit)
 718                return 0;
 719        else
 720                return 1;
 721}
 722
 723/*
 724 * Note that ordering matters in this enum. Not only must it match the mapping
 725 * below, it is also divided into several sections that matter.  When adding
 726 * new commands, make sure you add it in the right section.
 727 */
 728enum todo_command {
 729        /* commands that handle commits */
 730        TODO_PICK = 0,
 731        TODO_REVERT,
 732        TODO_EDIT,
 733        TODO_REWORD,
 734        TODO_FIXUP,
 735        TODO_SQUASH,
 736        /* commands that do something else than handling a single commit */
 737        TODO_EXEC,
 738        /* commands that do nothing but are counted for reporting progress */
 739        TODO_NOOP,
 740        TODO_DROP,
 741        /* comments (not counted for reporting progress) */
 742        TODO_COMMENT
 743};
 744
 745static struct {
 746        char c;
 747        const char *str;
 748} todo_command_info[] = {
 749        { 'p', "pick" },
 750        { 0,   "revert" },
 751        { 'e', "edit" },
 752        { 'r', "reword" },
 753        { 'f', "fixup" },
 754        { 's', "squash" },
 755        { 'x', "exec" },
 756        { 0,   "noop" },
 757        { 'd', "drop" },
 758        { 0,   NULL }
 759};
 760
 761static const char *command_to_string(const enum todo_command command)
 762{
 763        if (command < TODO_COMMENT)
 764                return todo_command_info[command].str;
 765        die("Unknown command: %d", command);
 766}
 767
 768static int is_noop(const enum todo_command command)
 769{
 770        return TODO_NOOP <= command;
 771}
 772
 773static int is_fixup(enum todo_command command)
 774{
 775        return command == TODO_FIXUP || command == TODO_SQUASH;
 776}
 777
 778static int update_squash_messages(enum todo_command command,
 779                struct commit *commit, struct replay_opts *opts)
 780{
 781        struct strbuf buf = STRBUF_INIT;
 782        int count, res;
 783        const char *message, *body;
 784
 785        if (file_exists(rebase_path_squash_msg())) {
 786                struct strbuf header = STRBUF_INIT;
 787                char *eol, *p;
 788
 789                if (strbuf_read_file(&buf, rebase_path_squash_msg(), 2048) <= 0)
 790                        return error(_("could not read '%s'"),
 791                                rebase_path_squash_msg());
 792
 793                p = buf.buf + 1;
 794                eol = strchrnul(buf.buf, '\n');
 795                if (buf.buf[0] != comment_line_char ||
 796                    (p += strcspn(p, "0123456789\n")) == eol)
 797                        return error(_("unexpected 1st line of squash message:"
 798                                       "\n\n\t%.*s"),
 799                                     (int)(eol - buf.buf), buf.buf);
 800                count = strtol(p, NULL, 10);
 801
 802                if (count < 1)
 803                        return error(_("invalid 1st line of squash message:\n"
 804                                       "\n\t%.*s"),
 805                                     (int)(eol - buf.buf), buf.buf);
 806
 807                strbuf_addf(&header, "%c ", comment_line_char);
 808                strbuf_addf(&header,
 809                            _("This is a combination of %d commits."), ++count);
 810                strbuf_splice(&buf, 0, eol - buf.buf, header.buf, header.len);
 811                strbuf_release(&header);
 812        } else {
 813                unsigned char head[20];
 814                struct commit *head_commit;
 815                const char *head_message, *body;
 816
 817                if (get_sha1("HEAD", head))
 818                        return error(_("need a HEAD to fixup"));
 819                if (!(head_commit = lookup_commit_reference(head)))
 820                        return error(_("could not read HEAD"));
 821                if (!(head_message = get_commit_buffer(head_commit, NULL)))
 822                        return error(_("could not read HEAD's commit message"));
 823
 824                find_commit_subject(head_message, &body);
 825                if (write_message(body, strlen(body),
 826                                  rebase_path_fixup_msg(), 0)) {
 827                        unuse_commit_buffer(head_commit, head_message);
 828                        return error(_("cannot write '%s'"),
 829                                     rebase_path_fixup_msg());
 830                }
 831
 832                count = 2;
 833                strbuf_addf(&buf, "%c ", comment_line_char);
 834                strbuf_addf(&buf, _("This is a combination of %d commits."),
 835                            count);
 836                strbuf_addf(&buf, "\n%c ", comment_line_char);
 837                strbuf_addstr(&buf, _("This is the 1st commit message:"));
 838                strbuf_addstr(&buf, "\n\n");
 839                strbuf_addstr(&buf, body);
 840
 841                unuse_commit_buffer(head_commit, head_message);
 842        }
 843
 844        if (!(message = get_commit_buffer(commit, NULL)))
 845                return error(_("could not read commit message of %s"),
 846                             oid_to_hex(&commit->object.oid));
 847        find_commit_subject(message, &body);
 848
 849        if (command == TODO_SQUASH) {
 850                unlink(rebase_path_fixup_msg());
 851                strbuf_addf(&buf, "\n%c ", comment_line_char);
 852                strbuf_addf(&buf, _("This is the commit message #%d:"), count);
 853                strbuf_addstr(&buf, "\n\n");
 854                strbuf_addstr(&buf, body);
 855        } else if (command == TODO_FIXUP) {
 856                strbuf_addf(&buf, "\n%c ", comment_line_char);
 857                strbuf_addf(&buf, _("The commit message #%d will be skipped:"),
 858                            count);
 859                strbuf_addstr(&buf, "\n\n");
 860                strbuf_add_commented_lines(&buf, body, strlen(body));
 861        } else
 862                return error(_("unknown command: %d"), command);
 863        unuse_commit_buffer(commit, message);
 864
 865        res = write_message(buf.buf, buf.len, rebase_path_squash_msg(), 0);
 866        strbuf_release(&buf);
 867        return res;
 868}
 869
 870static void flush_rewritten_pending(void) {
 871        struct strbuf buf = STRBUF_INIT;
 872        unsigned char newsha1[20];
 873        FILE *out;
 874
 875        if (strbuf_read_file(&buf, rebase_path_rewritten_pending(), 82) > 0 &&
 876                        !get_sha1("HEAD", newsha1) &&
 877                        (out = fopen(rebase_path_rewritten_list(), "a"))) {
 878                char *bol = buf.buf, *eol;
 879
 880                while (*bol) {
 881                        eol = strchrnul(bol, '\n');
 882                        fprintf(out, "%.*s %s\n", (int)(eol - bol),
 883                                        bol, sha1_to_hex(newsha1));
 884                        if (!*eol)
 885                                break;
 886                        bol = eol + 1;
 887                }
 888                fclose(out);
 889                unlink(rebase_path_rewritten_pending());
 890        }
 891        strbuf_release(&buf);
 892}
 893
 894static void record_in_rewritten(struct object_id *oid,
 895                enum todo_command next_command) {
 896        FILE *out = fopen(rebase_path_rewritten_pending(), "a");
 897
 898        if (!out)
 899                return;
 900
 901        fprintf(out, "%s\n", oid_to_hex(oid));
 902        fclose(out);
 903
 904        if (!is_fixup(next_command))
 905                flush_rewritten_pending();
 906}
 907
 908static int do_pick_commit(enum todo_command command, struct commit *commit,
 909                struct replay_opts *opts, int final_fixup)
 910{
 911        int edit = opts->edit, cleanup_commit_message = 0;
 912        const char *msg_file = edit ? NULL : git_path_merge_msg();
 913        unsigned char head[20];
 914        struct commit *base, *next, *parent;
 915        const char *base_label, *next_label;
 916        struct commit_message msg = { NULL, NULL, NULL, NULL };
 917        struct strbuf msgbuf = STRBUF_INIT;
 918        int res, unborn = 0, amend = 0, allow = 0;
 919
 920        if (opts->no_commit) {
 921                /*
 922                 * We do not intend to commit immediately.  We just want to
 923                 * merge the differences in, so let's compute the tree
 924                 * that represents the "current" state for merge-recursive
 925                 * to work on.
 926                 */
 927                if (write_cache_as_tree(head, 0, NULL))
 928                        return error(_("your index file is unmerged."));
 929        } else {
 930                unborn = get_sha1("HEAD", head);
 931                if (unborn)
 932                        hashcpy(head, EMPTY_TREE_SHA1_BIN);
 933                if (index_differs_from(unborn ? EMPTY_TREE_SHA1_HEX : "HEAD", 0, 0))
 934                        return error_dirty_index(opts);
 935        }
 936        discard_cache();
 937
 938        if (!commit->parents)
 939                parent = NULL;
 940        else if (commit->parents->next) {
 941                /* Reverting or cherry-picking a merge commit */
 942                int cnt;
 943                struct commit_list *p;
 944
 945                if (!opts->mainline)
 946                        return error(_("commit %s is a merge but no -m option was given."),
 947                                oid_to_hex(&commit->object.oid));
 948
 949                for (cnt = 1, p = commit->parents;
 950                     cnt != opts->mainline && p;
 951                     cnt++)
 952                        p = p->next;
 953                if (cnt != opts->mainline || !p)
 954                        return error(_("commit %s does not have parent %d"),
 955                                oid_to_hex(&commit->object.oid), opts->mainline);
 956                parent = p->item;
 957        } else if (0 < opts->mainline)
 958                return error(_("mainline was specified but commit %s is not a merge."),
 959                        oid_to_hex(&commit->object.oid));
 960        else
 961                parent = commit->parents->item;
 962
 963        if (get_message(commit, &msg) != 0)
 964                return error(_("cannot get commit message for %s"),
 965                        oid_to_hex(&commit->object.oid));
 966
 967        if (opts->allow_ff && !is_fixup(command) &&
 968            ((parent && !hashcmp(parent->object.oid.hash, head)) ||
 969             (!parent && unborn))) {
 970                if (is_rebase_i(opts))
 971                        write_author_script(msg.message);
 972                res = fast_forward_to(commit->object.oid.hash, head, unborn,
 973                        opts);
 974                if (res || command != TODO_REWORD)
 975                        goto leave;
 976                edit = amend = 1;
 977                msg_file = NULL;
 978                goto fast_forward_edit;
 979        }
 980        if (parent && parse_commit(parent) < 0)
 981                /* TRANSLATORS: The first %s will be a "todo" command like
 982                   "revert" or "pick", the second %s a SHA1. */
 983                return error(_("%s: cannot parse parent commit %s"),
 984                        command_to_string(command),
 985                        oid_to_hex(&parent->object.oid));
 986
 987        /*
 988         * "commit" is an existing commit.  We would want to apply
 989         * the difference it introduces since its first parent "prev"
 990         * on top of the current HEAD if we are cherry-pick.  Or the
 991         * reverse of it if we are revert.
 992         */
 993
 994        if (command == TODO_REVERT) {
 995                base = commit;
 996                base_label = msg.label;
 997                next = parent;
 998                next_label = msg.parent_label;
 999                strbuf_addstr(&msgbuf, "Revert \"");
1000                strbuf_addstr(&msgbuf, msg.subject);
1001                strbuf_addstr(&msgbuf, "\"\n\nThis reverts commit ");
1002                strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
1003
1004                if (commit->parents && commit->parents->next) {
1005                        strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
1006                        strbuf_addstr(&msgbuf, oid_to_hex(&parent->object.oid));
1007                }
1008                strbuf_addstr(&msgbuf, ".\n");
1009        } else {
1010                const char *p;
1011
1012                base = parent;
1013                base_label = msg.parent_label;
1014                next = commit;
1015                next_label = msg.label;
1016
1017                /* Append the commit log message to msgbuf. */
1018                if (find_commit_subject(msg.message, &p))
1019                        strbuf_addstr(&msgbuf, p);
1020
1021                if (opts->record_origin) {
1022                        if (!has_conforming_footer(&msgbuf, NULL, 0))
1023                                strbuf_addch(&msgbuf, '\n');
1024                        strbuf_addstr(&msgbuf, cherry_picked_prefix);
1025                        strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
1026                        strbuf_addstr(&msgbuf, ")\n");
1027                }
1028        }
1029
1030        if (command == TODO_REWORD)
1031                edit = 1;
1032        else if (is_fixup(command)) {
1033                if (update_squash_messages(command, commit, opts))
1034                        return -1;
1035                amend = 1;
1036                if (!final_fixup)
1037                        msg_file = rebase_path_squash_msg();
1038                else if (file_exists(rebase_path_fixup_msg())) {
1039                        cleanup_commit_message = 1;
1040                        msg_file = rebase_path_fixup_msg();
1041                } else {
1042                        const char *dest = git_path("SQUASH_MSG");
1043                        unlink(dest);
1044                        if (copy_file(dest, rebase_path_squash_msg(), 0666))
1045                                return error(_("could not rename '%s' to '%s'"),
1046                                             rebase_path_squash_msg(), dest);
1047                        unlink(git_path("MERGE_MSG"));
1048                        msg_file = dest;
1049                        edit = 1;
1050                }
1051        }
1052
1053        if (is_rebase_i(opts) && write_author_script(msg.message) < 0)
1054                res = -1;
1055        else if (!opts->strategy || !strcmp(opts->strategy, "recursive") || command == TODO_REVERT) {
1056                res = do_recursive_merge(base, next, base_label, next_label,
1057                                         head, &msgbuf, opts);
1058                if (res < 0)
1059                        return res;
1060                res |= write_message(msgbuf.buf, msgbuf.len,
1061                                     git_path_merge_msg(), 0);
1062        } else {
1063                struct commit_list *common = NULL;
1064                struct commit_list *remotes = NULL;
1065
1066                res = write_message(msgbuf.buf, msgbuf.len,
1067                                    git_path_merge_msg(), 0);
1068
1069                commit_list_insert(base, &common);
1070                commit_list_insert(next, &remotes);
1071                res |= try_merge_command(opts->strategy,
1072                                         opts->xopts_nr, (const char **)opts->xopts,
1073                                        common, sha1_to_hex(head), remotes);
1074                free_commit_list(common);
1075                free_commit_list(remotes);
1076        }
1077        strbuf_release(&msgbuf);
1078
1079        /*
1080         * If the merge was clean or if it failed due to conflict, we write
1081         * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
1082         * However, if the merge did not even start, then we don't want to
1083         * write it at all.
1084         */
1085        if (command == TODO_PICK && !opts->no_commit && (res == 0 || res == 1) &&
1086            update_ref(NULL, "CHERRY_PICK_HEAD", commit->object.oid.hash, NULL,
1087                       REF_NODEREF, UPDATE_REFS_MSG_ON_ERR))
1088                res = -1;
1089        if (command == TODO_REVERT && ((opts->no_commit && res == 0) || res == 1) &&
1090            update_ref(NULL, "REVERT_HEAD", commit->object.oid.hash, NULL,
1091                       REF_NODEREF, UPDATE_REFS_MSG_ON_ERR))
1092                res = -1;
1093
1094        if (res) {
1095                error(command == TODO_REVERT
1096                      ? _("could not revert %s... %s")
1097                      : _("could not apply %s... %s"),
1098                      short_commit_name(commit), msg.subject);
1099                print_advice(res == 1, opts);
1100                rerere(opts->allow_rerere_auto);
1101                goto leave;
1102        }
1103
1104        allow = allow_empty(opts, commit);
1105        if (allow < 0) {
1106                res = allow;
1107                goto leave;
1108        }
1109        if (!opts->no_commit)
1110fast_forward_edit:
1111                res = run_git_commit(msg_file, opts, allow, edit, amend,
1112                                     cleanup_commit_message);
1113
1114        if (!res && final_fixup) {
1115                unlink(rebase_path_fixup_msg());
1116                unlink(rebase_path_squash_msg());
1117        }
1118
1119leave:
1120        free_message(commit, &msg);
1121        update_abort_safety_file();
1122
1123        return res;
1124}
1125
1126static int prepare_revs(struct replay_opts *opts)
1127{
1128        /*
1129         * picking (but not reverting) ranges (but not individual revisions)
1130         * should be done in reverse
1131         */
1132        if (opts->action == REPLAY_PICK && !opts->revs->no_walk)
1133                opts->revs->reverse ^= 1;
1134
1135        if (prepare_revision_walk(opts->revs))
1136                return error(_("revision walk setup failed"));
1137
1138        if (!opts->revs->commits)
1139                return error(_("empty commit set passed"));
1140        return 0;
1141}
1142
1143static int read_and_refresh_cache(struct replay_opts *opts)
1144{
1145        static struct lock_file index_lock;
1146        int index_fd = hold_locked_index(&index_lock, 0);
1147        if (read_index_preload(&the_index, NULL) < 0) {
1148                rollback_lock_file(&index_lock);
1149                return error(_("git %s: failed to read the index"),
1150                        _(action_name(opts)));
1151        }
1152        refresh_index(&the_index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
1153        if (the_index.cache_changed && index_fd >= 0) {
1154                if (write_locked_index(&the_index, &index_lock, COMMIT_LOCK)) {
1155                        rollback_lock_file(&index_lock);
1156                        return error(_("git %s: failed to refresh the index"),
1157                                _(action_name(opts)));
1158                }
1159        }
1160        rollback_lock_file(&index_lock);
1161        return 0;
1162}
1163
1164struct todo_item {
1165        enum todo_command command;
1166        struct commit *commit;
1167        const char *arg;
1168        int arg_len;
1169        size_t offset_in_buf;
1170};
1171
1172struct todo_list {
1173        struct strbuf buf;
1174        struct todo_item *items;
1175        int nr, alloc, current;
1176};
1177
1178#define TODO_LIST_INIT { STRBUF_INIT }
1179
1180static void todo_list_release(struct todo_list *todo_list)
1181{
1182        strbuf_release(&todo_list->buf);
1183        free(todo_list->items);
1184        todo_list->items = NULL;
1185        todo_list->nr = todo_list->alloc = 0;
1186}
1187
1188static struct todo_item *append_new_todo(struct todo_list *todo_list)
1189{
1190        ALLOC_GROW(todo_list->items, todo_list->nr + 1, todo_list->alloc);
1191        return todo_list->items + todo_list->nr++;
1192}
1193
1194static int parse_insn_line(struct todo_item *item, const char *bol, char *eol)
1195{
1196        unsigned char commit_sha1[20];
1197        char *end_of_object_name;
1198        int i, saved, status, padding;
1199
1200        /* left-trim */
1201        bol += strspn(bol, " \t");
1202
1203        if (bol == eol || *bol == '\r' || *bol == comment_line_char) {
1204                item->command = TODO_COMMENT;
1205                item->commit = NULL;
1206                item->arg = bol;
1207                item->arg_len = eol - bol;
1208                return 0;
1209        }
1210
1211        for (i = 0; i < TODO_COMMENT; i++)
1212                if (skip_prefix(bol, todo_command_info[i].str, &bol)) {
1213                        item->command = i;
1214                        break;
1215                } else if (bol[1] == ' ' && *bol == todo_command_info[i].c) {
1216                        bol++;
1217                        item->command = i;
1218                        break;
1219                }
1220        if (i >= TODO_COMMENT)
1221                return -1;
1222
1223        if (item->command == TODO_NOOP) {
1224                item->commit = NULL;
1225                item->arg = bol;
1226                item->arg_len = eol - bol;
1227                return 0;
1228        }
1229
1230        /* Eat up extra spaces/ tabs before object name */
1231        padding = strspn(bol, " \t");
1232        if (!padding)
1233                return -1;
1234        bol += padding;
1235
1236        if (item->command == TODO_EXEC) {
1237                item->arg = bol;
1238                item->arg_len = (int)(eol - bol);
1239                return 0;
1240        }
1241
1242        end_of_object_name = (char *) bol + strcspn(bol, " \t\n");
1243        saved = *end_of_object_name;
1244        *end_of_object_name = '\0';
1245        status = get_sha1(bol, commit_sha1);
1246        *end_of_object_name = saved;
1247
1248        item->arg = end_of_object_name + strspn(end_of_object_name, " \t");
1249        item->arg_len = (int)(eol - item->arg);
1250
1251        if (status < 0)
1252                return -1;
1253
1254        item->commit = lookup_commit_reference(commit_sha1);
1255        return !item->commit;
1256}
1257
1258static int parse_insn_buffer(char *buf, struct todo_list *todo_list)
1259{
1260        struct todo_item *item;
1261        char *p = buf, *next_p;
1262        int i, res = 0, fixup_okay = file_exists(rebase_path_done());
1263
1264        for (i = 1; *p; i++, p = next_p) {
1265                char *eol = strchrnul(p, '\n');
1266
1267                next_p = *eol ? eol + 1 /* skip LF */ : eol;
1268
1269                if (p != eol && eol[-1] == '\r')
1270                        eol--; /* strip Carriage Return */
1271
1272                item = append_new_todo(todo_list);
1273                item->offset_in_buf = p - todo_list->buf.buf;
1274                if (parse_insn_line(item, p, eol)) {
1275                        res = error(_("invalid line %d: %.*s"),
1276                                i, (int)(eol - p), p);
1277                        item->command = TODO_NOOP;
1278                }
1279
1280                if (fixup_okay)
1281                        ; /* do nothing */
1282                else if (is_fixup(item->command))
1283                        return error(_("cannot '%s' without a previous commit"),
1284                                command_to_string(item->command));
1285                else if (!is_noop(item->command))
1286                        fixup_okay = 1;
1287        }
1288
1289        return res;
1290}
1291
1292static int read_populate_todo(struct todo_list *todo_list,
1293                        struct replay_opts *opts)
1294{
1295        const char *todo_file = get_todo_path(opts);
1296        int fd, res;
1297
1298        strbuf_reset(&todo_list->buf);
1299        fd = open(todo_file, O_RDONLY);
1300        if (fd < 0)
1301                return error_errno(_("could not open '%s'"), todo_file);
1302        if (strbuf_read(&todo_list->buf, fd, 0) < 0) {
1303                close(fd);
1304                return error(_("could not read '%s'."), todo_file);
1305        }
1306        close(fd);
1307
1308        res = parse_insn_buffer(todo_list->buf.buf, todo_list);
1309        if (res)
1310                return error(_("unusable instruction sheet: '%s'"), todo_file);
1311
1312        if (!todo_list->nr &&
1313            (!is_rebase_i(opts) || !file_exists(rebase_path_done())))
1314                return error(_("no commits parsed."));
1315
1316        if (!is_rebase_i(opts)) {
1317                enum todo_command valid =
1318                        opts->action == REPLAY_PICK ? TODO_PICK : TODO_REVERT;
1319                int i;
1320
1321                for (i = 0; i < todo_list->nr; i++)
1322                        if (valid == todo_list->items[i].command)
1323                                continue;
1324                        else if (valid == TODO_PICK)
1325                                return error(_("cannot cherry-pick during a revert."));
1326                        else
1327                                return error(_("cannot revert during a cherry-pick."));
1328        }
1329
1330        return 0;
1331}
1332
1333static int git_config_string_dup(char **dest,
1334                                 const char *var, const char *value)
1335{
1336        if (!value)
1337                return config_error_nonbool(var);
1338        free(*dest);
1339        *dest = xstrdup(value);
1340        return 0;
1341}
1342
1343static int populate_opts_cb(const char *key, const char *value, void *data)
1344{
1345        struct replay_opts *opts = data;
1346        int error_flag = 1;
1347
1348        if (!value)
1349                error_flag = 0;
1350        else if (!strcmp(key, "options.no-commit"))
1351                opts->no_commit = git_config_bool_or_int(key, value, &error_flag);
1352        else if (!strcmp(key, "options.edit"))
1353                opts->edit = git_config_bool_or_int(key, value, &error_flag);
1354        else if (!strcmp(key, "options.signoff"))
1355                opts->signoff = git_config_bool_or_int(key, value, &error_flag);
1356        else if (!strcmp(key, "options.record-origin"))
1357                opts->record_origin = git_config_bool_or_int(key, value, &error_flag);
1358        else if (!strcmp(key, "options.allow-ff"))
1359                opts->allow_ff = git_config_bool_or_int(key, value, &error_flag);
1360        else if (!strcmp(key, "options.mainline"))
1361                opts->mainline = git_config_int(key, value);
1362        else if (!strcmp(key, "options.strategy"))
1363                git_config_string_dup(&opts->strategy, key, value);
1364        else if (!strcmp(key, "options.gpg-sign"))
1365                git_config_string_dup(&opts->gpg_sign, key, value);
1366        else if (!strcmp(key, "options.strategy-option")) {
1367                ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
1368                opts->xopts[opts->xopts_nr++] = xstrdup(value);
1369        } else
1370                return error(_("invalid key: %s"), key);
1371
1372        if (!error_flag)
1373                return error(_("invalid value for %s: %s"), key, value);
1374
1375        return 0;
1376}
1377
1378static void read_strategy_opts(struct replay_opts *opts, struct strbuf *buf)
1379{
1380        int i;
1381
1382        strbuf_reset(buf);
1383        if (!read_oneliner(buf, rebase_path_strategy(), 0))
1384                return;
1385        opts->strategy = strbuf_detach(buf, NULL);
1386        if (!read_oneliner(buf, rebase_path_strategy_opts(), 0))
1387                return;
1388
1389        opts->xopts_nr = split_cmdline(buf->buf, (const char ***)&opts->xopts);
1390        for (i = 0; i < opts->xopts_nr; i++) {
1391                const char *arg = opts->xopts[i];
1392
1393                skip_prefix(arg, "--", &arg);
1394                opts->xopts[i] = xstrdup(arg);
1395        }
1396}
1397
1398static int read_populate_opts(struct replay_opts *opts)
1399{
1400        if (is_rebase_i(opts)) {
1401                struct strbuf buf = STRBUF_INIT;
1402
1403                if (read_oneliner(&buf, rebase_path_gpg_sign_opt(), 1)) {
1404                        if (!starts_with(buf.buf, "-S"))
1405                                strbuf_reset(&buf);
1406                        else {
1407                                free(opts->gpg_sign);
1408                                opts->gpg_sign = xstrdup(buf.buf + 2);
1409                        }
1410                }
1411
1412                if (file_exists(rebase_path_verbose()))
1413                        opts->verbose = 1;
1414
1415                read_strategy_opts(opts, &buf);
1416                strbuf_release(&buf);
1417
1418                return 0;
1419        }
1420
1421        if (!file_exists(git_path_opts_file()))
1422                return 0;
1423        /*
1424         * The function git_parse_source(), called from git_config_from_file(),
1425         * may die() in case of a syntactically incorrect file. We do not care
1426         * about this case, though, because we wrote that file ourselves, so we
1427         * are pretty certain that it is syntactically correct.
1428         */
1429        if (git_config_from_file(populate_opts_cb, git_path_opts_file(), opts) < 0)
1430                return error(_("malformed options sheet: '%s'"),
1431                        git_path_opts_file());
1432        return 0;
1433}
1434
1435static int walk_revs_populate_todo(struct todo_list *todo_list,
1436                                struct replay_opts *opts)
1437{
1438        enum todo_command command = opts->action == REPLAY_PICK ?
1439                TODO_PICK : TODO_REVERT;
1440        const char *command_string = todo_command_info[command].str;
1441        struct commit *commit;
1442
1443        if (prepare_revs(opts))
1444                return -1;
1445
1446        while ((commit = get_revision(opts->revs))) {
1447                struct todo_item *item = append_new_todo(todo_list);
1448                const char *commit_buffer = get_commit_buffer(commit, NULL);
1449                const char *subject;
1450                int subject_len;
1451
1452                item->command = command;
1453                item->commit = commit;
1454                item->arg = NULL;
1455                item->arg_len = 0;
1456                item->offset_in_buf = todo_list->buf.len;
1457                subject_len = find_commit_subject(commit_buffer, &subject);
1458                strbuf_addf(&todo_list->buf, "%s %s %.*s\n", command_string,
1459                        short_commit_name(commit), subject_len, subject);
1460                unuse_commit_buffer(commit, commit_buffer);
1461        }
1462        return 0;
1463}
1464
1465static int create_seq_dir(void)
1466{
1467        if (file_exists(git_path_seq_dir())) {
1468                error(_("a cherry-pick or revert is already in progress"));
1469                advise(_("try \"git cherry-pick (--continue | --quit | --abort)\""));
1470                return -1;
1471        } else if (mkdir(git_path_seq_dir(), 0777) < 0)
1472                return error_errno(_("could not create sequencer directory '%s'"),
1473                                   git_path_seq_dir());
1474        return 0;
1475}
1476
1477static int save_head(const char *head)
1478{
1479        static struct lock_file head_lock;
1480        struct strbuf buf = STRBUF_INIT;
1481        int fd;
1482
1483        fd = hold_lock_file_for_update(&head_lock, git_path_head_file(), 0);
1484        if (fd < 0) {
1485                rollback_lock_file(&head_lock);
1486                return error_errno(_("could not lock HEAD"));
1487        }
1488        strbuf_addf(&buf, "%s\n", head);
1489        if (write_in_full(fd, buf.buf, buf.len) < 0) {
1490                rollback_lock_file(&head_lock);
1491                return error_errno(_("could not write to '%s'"),
1492                                   git_path_head_file());
1493        }
1494        if (commit_lock_file(&head_lock) < 0) {
1495                rollback_lock_file(&head_lock);
1496                return error(_("failed to finalize '%s'."), git_path_head_file());
1497        }
1498        return 0;
1499}
1500
1501static int rollback_is_safe(void)
1502{
1503        struct strbuf sb = STRBUF_INIT;
1504        struct object_id expected_head, actual_head;
1505
1506        if (strbuf_read_file(&sb, git_path_abort_safety_file(), 0) >= 0) {
1507                strbuf_trim(&sb);
1508                if (get_oid_hex(sb.buf, &expected_head)) {
1509                        strbuf_release(&sb);
1510                        die(_("could not parse %s"), git_path_abort_safety_file());
1511                }
1512                strbuf_release(&sb);
1513        }
1514        else if (errno == ENOENT)
1515                oidclr(&expected_head);
1516        else
1517                die_errno(_("could not read '%s'"), git_path_abort_safety_file());
1518
1519        if (get_oid("HEAD", &actual_head))
1520                oidclr(&actual_head);
1521
1522        return !oidcmp(&actual_head, &expected_head);
1523}
1524
1525static int reset_for_rollback(const unsigned char *sha1)
1526{
1527        const char *argv[4];    /* reset --merge <arg> + NULL */
1528
1529        argv[0] = "reset";
1530        argv[1] = "--merge";
1531        argv[2] = sha1_to_hex(sha1);
1532        argv[3] = NULL;
1533        return run_command_v_opt(argv, RUN_GIT_CMD);
1534}
1535
1536static int rollback_single_pick(void)
1537{
1538        unsigned char head_sha1[20];
1539
1540        if (!file_exists(git_path_cherry_pick_head()) &&
1541            !file_exists(git_path_revert_head()))
1542                return error(_("no cherry-pick or revert in progress"));
1543        if (read_ref_full("HEAD", 0, head_sha1, NULL))
1544                return error(_("cannot resolve HEAD"));
1545        if (is_null_sha1(head_sha1))
1546                return error(_("cannot abort from a branch yet to be born"));
1547        return reset_for_rollback(head_sha1);
1548}
1549
1550int sequencer_rollback(struct replay_opts *opts)
1551{
1552        FILE *f;
1553        unsigned char sha1[20];
1554        struct strbuf buf = STRBUF_INIT;
1555
1556        f = fopen(git_path_head_file(), "r");
1557        if (!f && errno == ENOENT) {
1558                /*
1559                 * There is no multiple-cherry-pick in progress.
1560                 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
1561                 * a single-cherry-pick in progress, abort that.
1562                 */
1563                return rollback_single_pick();
1564        }
1565        if (!f)
1566                return error_errno(_("cannot open '%s'"), git_path_head_file());
1567        if (strbuf_getline_lf(&buf, f)) {
1568                error(_("cannot read '%s': %s"), git_path_head_file(),
1569                      ferror(f) ?  strerror(errno) : _("unexpected end of file"));
1570                fclose(f);
1571                goto fail;
1572        }
1573        fclose(f);
1574        if (get_sha1_hex(buf.buf, sha1) || buf.buf[40] != '\0') {
1575                error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
1576                        git_path_head_file());
1577                goto fail;
1578        }
1579        if (is_null_sha1(sha1)) {
1580                error(_("cannot abort from a branch yet to be born"));
1581                goto fail;
1582        }
1583
1584        if (!rollback_is_safe()) {
1585                /* Do not error, just do not rollback */
1586                warning(_("You seem to have moved HEAD. "
1587                          "Not rewinding, check your HEAD!"));
1588        } else
1589        if (reset_for_rollback(sha1))
1590                goto fail;
1591        strbuf_release(&buf);
1592        return sequencer_remove_state(opts);
1593fail:
1594        strbuf_release(&buf);
1595        return -1;
1596}
1597
1598static int save_todo(struct todo_list *todo_list, struct replay_opts *opts)
1599{
1600        static struct lock_file todo_lock;
1601        const char *todo_path = get_todo_path(opts);
1602        int next = todo_list->current, offset, fd;
1603
1604        /*
1605         * rebase -i writes "git-rebase-todo" without the currently executing
1606         * command, appending it to "done" instead.
1607         */
1608        if (is_rebase_i(opts))
1609                next++;
1610
1611        fd = hold_lock_file_for_update(&todo_lock, todo_path, 0);
1612        if (fd < 0)
1613                return error_errno(_("could not lock '%s'"), todo_path);
1614        offset = next < todo_list->nr ?
1615                todo_list->items[next].offset_in_buf : todo_list->buf.len;
1616        if (write_in_full(fd, todo_list->buf.buf + offset,
1617                        todo_list->buf.len - offset) < 0)
1618                return error_errno(_("could not write to '%s'"), todo_path);
1619        if (commit_lock_file(&todo_lock) < 0)
1620                return error(_("failed to finalize '%s'."), todo_path);
1621
1622        if (is_rebase_i(opts)) {
1623                const char *done_path = rebase_path_done();
1624                int fd = open(done_path, O_CREAT | O_WRONLY | O_APPEND, 0666);
1625                int prev_offset = !next ? 0 :
1626                        todo_list->items[next - 1].offset_in_buf;
1627
1628                if (fd >= 0 && offset > prev_offset &&
1629                    write_in_full(fd, todo_list->buf.buf + prev_offset,
1630                                  offset - prev_offset) < 0) {
1631                        close(fd);
1632                        return error_errno(_("could not write to '%s'"),
1633                                           done_path);
1634                }
1635                if (fd >= 0)
1636                        close(fd);
1637        }
1638        return 0;
1639}
1640
1641static int save_opts(struct replay_opts *opts)
1642{
1643        const char *opts_file = git_path_opts_file();
1644        int res = 0;
1645
1646        if (opts->no_commit)
1647                res |= git_config_set_in_file_gently(opts_file, "options.no-commit", "true");
1648        if (opts->edit)
1649                res |= git_config_set_in_file_gently(opts_file, "options.edit", "true");
1650        if (opts->signoff)
1651                res |= git_config_set_in_file_gently(opts_file, "options.signoff", "true");
1652        if (opts->record_origin)
1653                res |= git_config_set_in_file_gently(opts_file, "options.record-origin", "true");
1654        if (opts->allow_ff)
1655                res |= git_config_set_in_file_gently(opts_file, "options.allow-ff", "true");
1656        if (opts->mainline) {
1657                struct strbuf buf = STRBUF_INIT;
1658                strbuf_addf(&buf, "%d", opts->mainline);
1659                res |= git_config_set_in_file_gently(opts_file, "options.mainline", buf.buf);
1660                strbuf_release(&buf);
1661        }
1662        if (opts->strategy)
1663                res |= git_config_set_in_file_gently(opts_file, "options.strategy", opts->strategy);
1664        if (opts->gpg_sign)
1665                res |= git_config_set_in_file_gently(opts_file, "options.gpg-sign", opts->gpg_sign);
1666        if (opts->xopts) {
1667                int i;
1668                for (i = 0; i < opts->xopts_nr; i++)
1669                        res |= git_config_set_multivar_in_file_gently(opts_file,
1670                                                        "options.strategy-option",
1671                                                        opts->xopts[i], "^$", 0);
1672        }
1673        return res;
1674}
1675
1676static int make_patch(struct commit *commit, struct replay_opts *opts)
1677{
1678        struct strbuf buf = STRBUF_INIT;
1679        struct rev_info log_tree_opt;
1680        const char *subject, *p;
1681        int res = 0;
1682
1683        p = short_commit_name(commit);
1684        if (write_message(p, strlen(p), rebase_path_stopped_sha(), 1) < 0)
1685                return -1;
1686
1687        strbuf_addf(&buf, "%s/patch", get_dir(opts));
1688        memset(&log_tree_opt, 0, sizeof(log_tree_opt));
1689        init_revisions(&log_tree_opt, NULL);
1690        log_tree_opt.abbrev = 0;
1691        log_tree_opt.diff = 1;
1692        log_tree_opt.diffopt.output_format = DIFF_FORMAT_PATCH;
1693        log_tree_opt.disable_stdin = 1;
1694        log_tree_opt.no_commit_id = 1;
1695        log_tree_opt.diffopt.file = fopen(buf.buf, "w");
1696        log_tree_opt.diffopt.use_color = GIT_COLOR_NEVER;
1697        if (!log_tree_opt.diffopt.file)
1698                res |= error_errno(_("could not open '%s'"), buf.buf);
1699        else {
1700                res |= log_tree_commit(&log_tree_opt, commit);
1701                fclose(log_tree_opt.diffopt.file);
1702        }
1703        strbuf_reset(&buf);
1704
1705        strbuf_addf(&buf, "%s/message", get_dir(opts));
1706        if (!file_exists(buf.buf)) {
1707                const char *commit_buffer = get_commit_buffer(commit, NULL);
1708                find_commit_subject(commit_buffer, &subject);
1709                res |= write_message(subject, strlen(subject), buf.buf, 1);
1710                unuse_commit_buffer(commit, commit_buffer);
1711        }
1712        strbuf_release(&buf);
1713
1714        return res;
1715}
1716
1717static int intend_to_amend(void)
1718{
1719        unsigned char head[20];
1720        char *p;
1721
1722        if (get_sha1("HEAD", head))
1723                return error(_("cannot read HEAD"));
1724
1725        p = sha1_to_hex(head);
1726        return write_message(p, strlen(p), rebase_path_amend(), 1);
1727}
1728
1729static int error_with_patch(struct commit *commit,
1730        const char *subject, int subject_len,
1731        struct replay_opts *opts, int exit_code, int to_amend)
1732{
1733        if (make_patch(commit, opts))
1734                return -1;
1735
1736        if (to_amend) {
1737                if (intend_to_amend())
1738                        return -1;
1739
1740                fprintf(stderr, "You can amend the commit now, with\n"
1741                        "\n"
1742                        "  git commit --amend %s\n"
1743                        "\n"
1744                        "Once you are satisfied with your changes, run\n"
1745                        "\n"
1746                        "  git rebase --continue\n", gpg_sign_opt_quoted(opts));
1747        } else if (exit_code)
1748                fprintf(stderr, "Could not apply %s... %.*s\n",
1749                        short_commit_name(commit), subject_len, subject);
1750
1751        return exit_code;
1752}
1753
1754static int error_failed_squash(struct commit *commit,
1755        struct replay_opts *opts, int subject_len, const char *subject)
1756{
1757        if (rename(rebase_path_squash_msg(), rebase_path_message()))
1758                return error(_("could not rename '%s' to '%s'"),
1759                        rebase_path_squash_msg(), rebase_path_message());
1760        unlink(rebase_path_fixup_msg());
1761        unlink(git_path("MERGE_MSG"));
1762        if (copy_file(git_path("MERGE_MSG"), rebase_path_message(), 0666))
1763                return error(_("could not copy '%s' to '%s'"),
1764                             rebase_path_message(), git_path("MERGE_MSG"));
1765        return error_with_patch(commit, subject, subject_len, opts, 1, 0);
1766}
1767
1768static int do_exec(const char *command_line)
1769{
1770        const char *child_argv[] = { NULL, NULL };
1771        int dirty, status;
1772
1773        fprintf(stderr, "Executing: %s\n", command_line);
1774        child_argv[0] = command_line;
1775        status = run_command_v_opt(child_argv, RUN_USING_SHELL);
1776
1777        /* force re-reading of the cache */
1778        if (discard_cache() < 0 || read_cache() < 0)
1779                return error(_("could not read index"));
1780
1781        dirty = require_clean_work_tree("rebase", NULL, 1, 1);
1782
1783        if (status) {
1784                warning(_("execution failed: %s\n%s"
1785                          "You can fix the problem, and then run\n"
1786                          "\n"
1787                          "  git rebase --continue\n"
1788                          "\n"),
1789                        command_line,
1790                        dirty ? N_("and made changes to the index and/or the "
1791                                "working tree\n") : "");
1792                if (status == 127)
1793                        /* command not found */
1794                        status = 1;
1795        } else if (dirty) {
1796                warning(_("execution succeeded: %s\nbut "
1797                          "left changes to the index and/or the working tree\n"
1798                          "Commit or stash your changes, and then run\n"
1799                          "\n"
1800                          "  git rebase --continue\n"
1801                          "\n"), command_line);
1802                status = 1;
1803        }
1804
1805        return status;
1806}
1807
1808static int is_final_fixup(struct todo_list *todo_list)
1809{
1810        int i = todo_list->current;
1811
1812        if (!is_fixup(todo_list->items[i].command))
1813                return 0;
1814
1815        while (++i < todo_list->nr)
1816                if (is_fixup(todo_list->items[i].command))
1817                        return 0;
1818                else if (!is_noop(todo_list->items[i].command))
1819                        break;
1820        return 1;
1821}
1822
1823static enum todo_command peek_command(struct todo_list *todo_list, int offset)
1824{
1825        int i;
1826
1827        for (i = todo_list->current + offset; i < todo_list->nr; i++)
1828                if (!is_noop(todo_list->items[i].command))
1829                        return todo_list->items[i].command;
1830
1831        return -1;
1832}
1833
1834static int apply_autostash(struct replay_opts *opts)
1835{
1836        struct strbuf stash_sha1 = STRBUF_INIT;
1837        struct child_process child = CHILD_PROCESS_INIT;
1838        int ret = 0;
1839
1840        if (!read_oneliner(&stash_sha1, rebase_path_autostash(), 1)) {
1841                strbuf_release(&stash_sha1);
1842                return 0;
1843        }
1844        strbuf_trim(&stash_sha1);
1845
1846        child.git_cmd = 1;
1847        argv_array_push(&child.args, "stash");
1848        argv_array_push(&child.args, "apply");
1849        argv_array_push(&child.args, stash_sha1.buf);
1850        if (!run_command(&child))
1851                printf(_("Applied autostash."));
1852        else {
1853                struct child_process store = CHILD_PROCESS_INIT;
1854
1855                store.git_cmd = 1;
1856                argv_array_push(&store.args, "stash");
1857                argv_array_push(&store.args, "store");
1858                argv_array_push(&store.args, "-m");
1859                argv_array_push(&store.args, "autostash");
1860                argv_array_push(&store.args, "-q");
1861                argv_array_push(&store.args, stash_sha1.buf);
1862                if (run_command(&store))
1863                        ret = error(_("cannot store %s"), stash_sha1.buf);
1864                else
1865                        printf(_("Applying autostash resulted in conflicts.\n"
1866                                "Your changes are safe in the stash.\n"
1867                                "You can run \"git stash pop\" or"
1868                                " \"git stash drop\" at any time.\n"));
1869        }
1870
1871        strbuf_release(&stash_sha1);
1872        return ret;
1873}
1874
1875static const char *reflog_message(struct replay_opts *opts,
1876        const char *sub_action, const char *fmt, ...)
1877{
1878        va_list ap;
1879        static struct strbuf buf = STRBUF_INIT;
1880
1881        va_start(ap, fmt);
1882        strbuf_reset(&buf);
1883        strbuf_addstr(&buf, action_name(opts));
1884        if (sub_action)
1885                strbuf_addf(&buf, " (%s)", sub_action);
1886        if (fmt) {
1887                strbuf_addstr(&buf, ": ");
1888                strbuf_vaddf(&buf, fmt, ap);
1889        }
1890        va_end(ap);
1891
1892        return buf.buf;
1893}
1894
1895static int pick_commits(struct todo_list *todo_list, struct replay_opts *opts)
1896{
1897        int res = 0;
1898
1899        setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
1900        if (opts->allow_ff)
1901                assert(!(opts->signoff || opts->no_commit ||
1902                                opts->record_origin || opts->edit));
1903        if (read_and_refresh_cache(opts))
1904                return -1;
1905
1906        while (todo_list->current < todo_list->nr) {
1907                struct todo_item *item = todo_list->items + todo_list->current;
1908                if (save_todo(todo_list, opts))
1909                        return -1;
1910                if (is_rebase_i(opts)) {
1911                        unlink(rebase_path_message());
1912                        unlink(rebase_path_author_script());
1913                        unlink(rebase_path_stopped_sha());
1914                        unlink(rebase_path_amend());
1915                }
1916                if (item->command <= TODO_SQUASH) {
1917                        if (is_rebase_i(opts))
1918                                setenv("GIT_REFLOG_ACTION", reflog_message(opts,
1919                                        command_to_string(item->command), NULL),
1920                                        1);
1921                        res = do_pick_commit(item->command, item->commit,
1922                                        opts, is_final_fixup(todo_list));
1923                        if (is_rebase_i(opts) && res < 0) {
1924                                /* Reschedule */
1925                                todo_list->current--;
1926                                if (save_todo(todo_list, opts))
1927                                        return -1;
1928                        }
1929                        if (item->command == TODO_EDIT) {
1930                                struct commit *commit = item->commit;
1931                                if (!res)
1932                                        warning(_("stopped at %s... %.*s"),
1933                                                short_commit_name(commit),
1934                                                item->arg_len, item->arg);
1935                                return error_with_patch(commit,
1936                                        item->arg, item->arg_len, opts, res,
1937                                        !res);
1938                        }
1939                        if (is_rebase_i(opts) && !res)
1940                                record_in_rewritten(&item->commit->object.oid,
1941                                        peek_command(todo_list, 1));
1942                        if (res && is_fixup(item->command)) {
1943                                if (res == 1)
1944                                        intend_to_amend();
1945                                return error_failed_squash(item->commit, opts,
1946                                        item->arg_len, item->arg);
1947                        } else if (res && is_rebase_i(opts))
1948                                return res | error_with_patch(item->commit,
1949                                        item->arg, item->arg_len, opts, res,
1950                                        item->command == TODO_REWORD);
1951                } else if (item->command == TODO_EXEC) {
1952                        char *end_of_arg = (char *)(item->arg + item->arg_len);
1953                        int saved = *end_of_arg;
1954
1955                        *end_of_arg = '\0';
1956                        res = do_exec(item->arg);
1957                        *end_of_arg = saved;
1958                } else if (!is_noop(item->command))
1959                        return error(_("unknown command %d"), item->command);
1960
1961                todo_list->current++;
1962                if (res)
1963                        return res;
1964        }
1965
1966        if (is_rebase_i(opts)) {
1967                struct strbuf head_ref = STRBUF_INIT, buf = STRBUF_INIT;
1968                struct stat st;
1969
1970                /* Stopped in the middle, as planned? */
1971                if (todo_list->current < todo_list->nr)
1972                        return 0;
1973
1974                if (read_oneliner(&head_ref, rebase_path_head_name(), 0) &&
1975                                starts_with(head_ref.buf, "refs/")) {
1976                        const char *msg;
1977                        unsigned char head[20], orig[20];
1978                        int res;
1979
1980                        if (get_sha1("HEAD", head)) {
1981                                res = error(_("cannot read HEAD"));
1982cleanup_head_ref:
1983                                strbuf_release(&head_ref);
1984                                strbuf_release(&buf);
1985                                return res;
1986                        }
1987                        if (!read_oneliner(&buf, rebase_path_orig_head(), 0) ||
1988                                        get_sha1_hex(buf.buf, orig)) {
1989                                res = error(_("could not read orig-head"));
1990                                goto cleanup_head_ref;
1991                        }
1992                        if (!read_oneliner(&buf, rebase_path_onto(), 0)) {
1993                                res = error(_("could not read 'onto'"));
1994                                goto cleanup_head_ref;
1995                        }
1996                        msg = reflog_message(opts, "finish", "%s onto %s",
1997                                head_ref.buf, buf.buf);
1998                        if (update_ref(msg, head_ref.buf, head, orig,
1999                                        REF_NODEREF, UPDATE_REFS_MSG_ON_ERR)) {
2000                                res = error(_("could not update %s"),
2001                                        head_ref.buf);
2002                                goto cleanup_head_ref;
2003                        }
2004                        msg = reflog_message(opts, "finish", "returning to %s",
2005                                head_ref.buf);
2006                        if (create_symref("HEAD", head_ref.buf, msg)) {
2007                                res = error(_("could not update HEAD to %s"),
2008                                        head_ref.buf);
2009                                goto cleanup_head_ref;
2010                        }
2011                        strbuf_reset(&buf);
2012                }
2013
2014                if (opts->verbose) {
2015                        struct rev_info log_tree_opt;
2016                        struct object_id orig, head;
2017
2018                        memset(&log_tree_opt, 0, sizeof(log_tree_opt));
2019                        init_revisions(&log_tree_opt, NULL);
2020                        log_tree_opt.diff = 1;
2021                        log_tree_opt.diffopt.output_format =
2022                                DIFF_FORMAT_DIFFSTAT;
2023                        log_tree_opt.disable_stdin = 1;
2024
2025                        if (read_oneliner(&buf, rebase_path_orig_head(), 0) &&
2026                            !get_sha1(buf.buf, orig.hash) &&
2027                            !get_sha1("HEAD", head.hash)) {
2028                                diff_tree_sha1(orig.hash, head.hash,
2029                                               "", &log_tree_opt.diffopt);
2030                                log_tree_diff_flush(&log_tree_opt);
2031                        }
2032                }
2033                flush_rewritten_pending();
2034                if (!stat(rebase_path_rewritten_list(), &st) &&
2035                                st.st_size > 0) {
2036                        struct child_process child = CHILD_PROCESS_INIT;
2037                        const char *post_rewrite_hook =
2038                                find_hook("post-rewrite");
2039
2040                        child.in = open(rebase_path_rewritten_list(), O_RDONLY);
2041                        child.git_cmd = 1;
2042                        argv_array_push(&child.args, "notes");
2043                        argv_array_push(&child.args, "copy");
2044                        argv_array_push(&child.args, "--for-rewrite=rebase");
2045                        /* we don't care if this copying failed */
2046                        run_command(&child);
2047
2048                        if (post_rewrite_hook) {
2049                                struct child_process hook = CHILD_PROCESS_INIT;
2050
2051                                hook.in = open(rebase_path_rewritten_list(),
2052                                        O_RDONLY);
2053                                hook.stdout_to_stderr = 1;
2054                                argv_array_push(&hook.args, post_rewrite_hook);
2055                                argv_array_push(&hook.args, "rebase");
2056                                /* we don't care if this hook failed */
2057                                run_command(&hook);
2058                        }
2059                }
2060                apply_autostash(opts);
2061
2062                strbuf_release(&buf);
2063                strbuf_release(&head_ref);
2064        }
2065
2066        /*
2067         * Sequence of picks finished successfully; cleanup by
2068         * removing the .git/sequencer directory
2069         */
2070        return sequencer_remove_state(opts);
2071}
2072
2073static int continue_single_pick(void)
2074{
2075        const char *argv[] = { "commit", NULL };
2076
2077        if (!file_exists(git_path_cherry_pick_head()) &&
2078            !file_exists(git_path_revert_head()))
2079                return error(_("no cherry-pick or revert in progress"));
2080        return run_command_v_opt(argv, RUN_GIT_CMD);
2081}
2082
2083static int commit_staged_changes(struct replay_opts *opts)
2084{
2085        int amend = 0;
2086
2087        if (has_unstaged_changes(1))
2088                return error(_("cannot rebase: You have unstaged changes."));
2089        if (!has_uncommitted_changes(0)) {
2090                const char *cherry_pick_head = git_path("CHERRY_PICK_HEAD");
2091
2092                if (file_exists(cherry_pick_head) && unlink(cherry_pick_head))
2093                        return error(_("could not remove CHERRY_PICK_HEAD"));
2094                return 0;
2095        }
2096
2097        if (file_exists(rebase_path_amend())) {
2098                struct strbuf rev = STRBUF_INIT;
2099                unsigned char head[20], to_amend[20];
2100
2101                if (get_sha1("HEAD", head))
2102                        return error(_("cannot amend non-existing commit"));
2103                if (!read_oneliner(&rev, rebase_path_amend(), 0))
2104                        return error(_("invalid file: '%s'"), rebase_path_amend());
2105                if (get_sha1_hex(rev.buf, to_amend))
2106                        return error(_("invalid contents: '%s'"),
2107                                rebase_path_amend());
2108                if (hashcmp(head, to_amend))
2109                        return error(_("\nYou have uncommitted changes in your "
2110                                       "working tree. Please, commit them\n"
2111                                       "first and then run 'git rebase "
2112                                       "--continue' again."));
2113
2114                strbuf_release(&rev);
2115                amend = 1;
2116        }
2117
2118        if (run_git_commit(rebase_path_message(), opts, 1, 1, amend, 0))
2119                return error(_("could not commit staged changes."));
2120        unlink(rebase_path_amend());
2121        return 0;
2122}
2123
2124int sequencer_continue(struct replay_opts *opts)
2125{
2126        struct todo_list todo_list = TODO_LIST_INIT;
2127        int res;
2128
2129        if (read_and_refresh_cache(opts))
2130                return -1;
2131
2132        if (is_rebase_i(opts)) {
2133                if (commit_staged_changes(opts))
2134                        return -1;
2135        } else if (!file_exists(get_todo_path(opts)))
2136                return continue_single_pick();
2137        if (read_populate_opts(opts))
2138                return -1;
2139        if ((res = read_populate_todo(&todo_list, opts)))
2140                goto release_todo_list;
2141
2142        if (!is_rebase_i(opts)) {
2143                /* Verify that the conflict has been resolved */
2144                if (file_exists(git_path_cherry_pick_head()) ||
2145                    file_exists(git_path_revert_head())) {
2146                        res = continue_single_pick();
2147                        if (res)
2148                                goto release_todo_list;
2149                }
2150                if (index_differs_from("HEAD", 0, 0)) {
2151                        res = error_dirty_index(opts);
2152                        goto release_todo_list;
2153                }
2154                todo_list.current++;
2155        } else if (file_exists(rebase_path_stopped_sha())) {
2156                struct strbuf buf = STRBUF_INIT;
2157                struct object_id oid;
2158
2159                if (read_oneliner(&buf, rebase_path_stopped_sha(), 1) &&
2160                    !get_sha1_committish(buf.buf, oid.hash))
2161                        record_in_rewritten(&oid, peek_command(&todo_list, 0));
2162                strbuf_release(&buf);
2163        }
2164
2165        res = pick_commits(&todo_list, opts);
2166release_todo_list:
2167        todo_list_release(&todo_list);
2168        return res;
2169}
2170
2171static int single_pick(struct commit *cmit, struct replay_opts *opts)
2172{
2173        setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
2174        return do_pick_commit(opts->action == REPLAY_PICK ?
2175                TODO_PICK : TODO_REVERT, cmit, opts, 0);
2176}
2177
2178int sequencer_pick_revisions(struct replay_opts *opts)
2179{
2180        struct todo_list todo_list = TODO_LIST_INIT;
2181        unsigned char sha1[20];
2182        int i, res;
2183
2184        assert(opts->revs);
2185        if (read_and_refresh_cache(opts))
2186                return -1;
2187
2188        for (i = 0; i < opts->revs->pending.nr; i++) {
2189                unsigned char sha1[20];
2190                const char *name = opts->revs->pending.objects[i].name;
2191
2192                /* This happens when using --stdin. */
2193                if (!strlen(name))
2194                        continue;
2195
2196                if (!get_sha1(name, sha1)) {
2197                        if (!lookup_commit_reference_gently(sha1, 1)) {
2198                                enum object_type type = sha1_object_info(sha1, NULL);
2199                                return error(_("%s: can't cherry-pick a %s"),
2200                                        name, typename(type));
2201                        }
2202                } else
2203                        return error(_("%s: bad revision"), name);
2204        }
2205
2206        /*
2207         * If we were called as "git cherry-pick <commit>", just
2208         * cherry-pick/revert it, set CHERRY_PICK_HEAD /
2209         * REVERT_HEAD, and don't touch the sequencer state.
2210         * This means it is possible to cherry-pick in the middle
2211         * of a cherry-pick sequence.
2212         */
2213        if (opts->revs->cmdline.nr == 1 &&
2214            opts->revs->cmdline.rev->whence == REV_CMD_REV &&
2215            opts->revs->no_walk &&
2216            !opts->revs->cmdline.rev->flags) {
2217                struct commit *cmit;
2218                if (prepare_revision_walk(opts->revs))
2219                        return error(_("revision walk setup failed"));
2220                cmit = get_revision(opts->revs);
2221                if (!cmit || get_revision(opts->revs))
2222                        return error("BUG: expected exactly one commit from walk");
2223                return single_pick(cmit, opts);
2224        }
2225
2226        /*
2227         * Start a new cherry-pick/ revert sequence; but
2228         * first, make sure that an existing one isn't in
2229         * progress
2230         */
2231
2232        if (walk_revs_populate_todo(&todo_list, opts) ||
2233                        create_seq_dir() < 0)
2234                return -1;
2235        if (get_sha1("HEAD", sha1) && (opts->action == REPLAY_REVERT))
2236                return error(_("can't revert as initial commit"));
2237        if (save_head(sha1_to_hex(sha1)))
2238                return -1;
2239        if (save_opts(opts))
2240                return -1;
2241        update_abort_safety_file();
2242        res = pick_commits(&todo_list, opts);
2243        todo_list_release(&todo_list);
2244        return res;
2245}
2246
2247void append_signoff(struct strbuf *msgbuf, int ignore_footer, unsigned flag)
2248{
2249        unsigned no_dup_sob = flag & APPEND_SIGNOFF_DEDUP;
2250        struct strbuf sob = STRBUF_INIT;
2251        int has_footer;
2252
2253        strbuf_addstr(&sob, sign_off_header);
2254        strbuf_addstr(&sob, fmt_name(getenv("GIT_COMMITTER_NAME"),
2255                                getenv("GIT_COMMITTER_EMAIL")));
2256        strbuf_addch(&sob, '\n');
2257
2258        /*
2259         * If the whole message buffer is equal to the sob, pretend that we
2260         * found a conforming footer with a matching sob
2261         */
2262        if (msgbuf->len - ignore_footer == sob.len &&
2263            !strncmp(msgbuf->buf, sob.buf, sob.len))
2264                has_footer = 3;
2265        else
2266                has_footer = has_conforming_footer(msgbuf, &sob, ignore_footer);
2267
2268        if (!has_footer) {
2269                const char *append_newlines = NULL;
2270                size_t len = msgbuf->len - ignore_footer;
2271
2272                if (!len) {
2273                        /*
2274                         * The buffer is completely empty.  Leave foom for
2275                         * the title and body to be filled in by the user.
2276                         */
2277                        append_newlines = "\n\n";
2278                } else if (msgbuf->buf[len - 1] != '\n') {
2279                        /*
2280                         * Incomplete line.  Complete the line and add a
2281                         * blank one so that there is an empty line between
2282                         * the message body and the sob.
2283                         */
2284                        append_newlines = "\n\n";
2285                } else if (len == 1) {
2286                        /*
2287                         * Buffer contains a single newline.  Add another
2288                         * so that we leave room for the title and body.
2289                         */
2290                        append_newlines = "\n";
2291                } else if (msgbuf->buf[len - 2] != '\n') {
2292                        /*
2293                         * Buffer ends with a single newline.  Add another
2294                         * so that there is an empty line between the message
2295                         * body and the sob.
2296                         */
2297                        append_newlines = "\n";
2298                } /* else, the buffer already ends with two newlines. */
2299
2300                if (append_newlines)
2301                        strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
2302                                append_newlines, strlen(append_newlines));
2303        }
2304
2305        if (has_footer != 3 && (!no_dup_sob || has_footer != 2))
2306                strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
2307                                sob.buf, sob.len);
2308
2309        strbuf_release(&sob);
2310}