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