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