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