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