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