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