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