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