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