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