ddc4d144d7d58d46101a9e84e52c9a4b1b07e6c2
   1#include "cache.h"
   2#include "lockfile.h"
   3#include "sequencer.h"
   4#include "dir.h"
   5#include "object.h"
   6#include "commit.h"
   7#include "tag.h"
   8#include "run-command.h"
   9#include "exec_cmd.h"
  10#include "utf8.h"
  11#include "cache-tree.h"
  12#include "diff.h"
  13#include "revision.h"
  14#include "rerere.h"
  15#include "merge-recursive.h"
  16#include "refs.h"
  17#include "argv-array.h"
  18#include "quote.h"
  19#include "trailer.h"
  20#include "log-tree.h"
  21#include "wt-status.h"
  22
  23#define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
  24
  25const char sign_off_header[] = "Signed-off-by: ";
  26static const char cherry_picked_prefix[] = "(cherry picked from commit ";
  27
  28GIT_PATH_FUNC(git_path_seq_dir, "sequencer")
  29
  30static GIT_PATH_FUNC(git_path_todo_file, "sequencer/todo")
  31static GIT_PATH_FUNC(git_path_opts_file, "sequencer/opts")
  32static GIT_PATH_FUNC(git_path_head_file, "sequencer/head")
  33static GIT_PATH_FUNC(git_path_abort_safety_file, "sequencer/abort-safety")
  34
  35static GIT_PATH_FUNC(rebase_path, "rebase-merge")
  36/*
  37 * The file containing rebase commands, comments, and empty lines.
  38 * This file is created by "git rebase -i" then edited by the user. As
  39 * the lines are processed, they are removed from the front of this
  40 * file and written to the tail of 'done'.
  41 */
  42static GIT_PATH_FUNC(rebase_path_todo, "rebase-merge/git-rebase-todo")
  43/*
  44 * A script to set the GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL, and
  45 * GIT_AUTHOR_DATE that will be used for the commit that is currently
  46 * being rebased.
  47 */
  48static GIT_PATH_FUNC(rebase_path_author_script, "rebase-merge/author-script")
  49/*
  50 * When an "edit" rebase command is being processed, the SHA1 of the
  51 * commit to be edited is recorded in this file.  When "git rebase
  52 * --continue" is executed, if there are any staged changes then they
  53 * will be amended to the HEAD commit, but only provided the HEAD
  54 * commit is still the commit to be edited.  When any other rebase
  55 * command is processed, this file is deleted.
  56 */
  57static GIT_PATH_FUNC(rebase_path_amend, "rebase-merge/amend")
  58/*
  59 * When we stop at a given patch via the "edit" command, this file contains
  60 * the abbreviated commit name of the corresponding patch.
  61 */
  62static GIT_PATH_FUNC(rebase_path_stopped_sha, "rebase-merge/stopped-sha")
  63/*
  64 * The following files are written by git-rebase just after parsing the
  65 * command-line (and are only consumed, not modified, by the sequencer).
  66 */
  67static GIT_PATH_FUNC(rebase_path_gpg_sign_opt, "rebase-merge/gpg_sign_opt")
  68static GIT_PATH_FUNC(rebase_path_orig_head, "rebase-merge/orig-head")
  69static GIT_PATH_FUNC(rebase_path_verbose, "rebase-merge/verbose")
  70
  71static inline int is_rebase_i(const struct replay_opts *opts)
  72{
  73        return opts->action == REPLAY_INTERACTIVE_REBASE;
  74}
  75
  76static const char *get_dir(const struct replay_opts *opts)
  77{
  78        if (is_rebase_i(opts))
  79                return rebase_path();
  80        return git_path_seq_dir();
  81}
  82
  83static const char *get_todo_path(const struct replay_opts *opts)
  84{
  85        if (is_rebase_i(opts))
  86                return rebase_path_todo();
  87        return git_path_todo_file();
  88}
  89
  90/*
  91 * Returns 0 for non-conforming footer
  92 * Returns 1 for conforming footer
  93 * Returns 2 when sob exists within conforming footer
  94 * Returns 3 when sob exists within conforming footer as last entry
  95 */
  96static int has_conforming_footer(struct strbuf *sb, struct strbuf *sob,
  97        int ignore_footer)
  98{
  99        struct trailer_info info;
 100        int i;
 101        int found_sob = 0, found_sob_last = 0;
 102
 103        trailer_info_get(&info, sb->buf);
 104
 105        if (info.trailer_start == info.trailer_end)
 106                return 0;
 107
 108        for (i = 0; i < info.trailer_nr; i++)
 109                if (sob && !strncmp(info.trailers[i], sob->buf, sob->len)) {
 110                        found_sob = 1;
 111                        if (i == info.trailer_nr - 1)
 112                                found_sob_last = 1;
 113                }
 114
 115        trailer_info_release(&info);
 116
 117        if (found_sob_last)
 118                return 3;
 119        if (found_sob)
 120                return 2;
 121        return 1;
 122}
 123
 124static const char *gpg_sign_opt_quoted(struct replay_opts *opts)
 125{
 126        static struct strbuf buf = STRBUF_INIT;
 127
 128        strbuf_reset(&buf);
 129        if (opts->gpg_sign)
 130                sq_quotef(&buf, "-S%s", opts->gpg_sign);
 131        return buf.buf;
 132}
 133
 134int sequencer_remove_state(struct replay_opts *opts)
 135{
 136        struct strbuf dir = STRBUF_INIT;
 137        int i;
 138
 139        free(opts->gpg_sign);
 140        free(opts->strategy);
 141        for (i = 0; i < opts->xopts_nr; i++)
 142                free(opts->xopts[i]);
 143        free(opts->xopts);
 144
 145        strbuf_addf(&dir, "%s", get_dir(opts));
 146        remove_dir_recursively(&dir, 0);
 147        strbuf_release(&dir);
 148
 149        return 0;
 150}
 151
 152static const char *action_name(const struct replay_opts *opts)
 153{
 154        switch (opts->action) {
 155        case REPLAY_REVERT:
 156                return N_("revert");
 157        case REPLAY_PICK:
 158                return N_("cherry-pick");
 159        case REPLAY_INTERACTIVE_REBASE:
 160                return N_("rebase -i");
 161        }
 162        die(_("Unknown action: %d"), opts->action);
 163}
 164
 165struct commit_message {
 166        char *parent_label;
 167        char *label;
 168        char *subject;
 169        const char *message;
 170};
 171
 172static const char *short_commit_name(struct commit *commit)
 173{
 174        return find_unique_abbrev(commit->object.oid.hash, DEFAULT_ABBREV);
 175}
 176
 177static int get_message(struct commit *commit, struct commit_message *out)
 178{
 179        const char *abbrev, *subject;
 180        int subject_len;
 181
 182        out->message = logmsg_reencode(commit, NULL, get_commit_output_encoding());
 183        abbrev = short_commit_name(commit);
 184
 185        subject_len = find_commit_subject(out->message, &subject);
 186
 187        out->subject = xmemdupz(subject, subject_len);
 188        out->label = xstrfmt("%s... %s", abbrev, out->subject);
 189        out->parent_label = xstrfmt("parent of %s", out->label);
 190
 191        return 0;
 192}
 193
 194static void free_message(struct commit *commit, struct commit_message *msg)
 195{
 196        free(msg->parent_label);
 197        free(msg->label);
 198        free(msg->subject);
 199        unuse_commit_buffer(commit, msg->message);
 200}
 201
 202static void print_advice(int show_hint, struct replay_opts *opts)
 203{
 204        char *msg = getenv("GIT_CHERRY_PICK_HELP");
 205
 206        if (msg) {
 207                fprintf(stderr, "%s\n", msg);
 208                /*
 209                 * A conflict has occurred but the porcelain
 210                 * (typically rebase --interactive) wants to take care
 211                 * of the commit itself so remove CHERRY_PICK_HEAD
 212                 */
 213                unlink(git_path_cherry_pick_head());
 214                return;
 215        }
 216
 217        if (show_hint) {
 218                if (opts->no_commit)
 219                        advise(_("after resolving the conflicts, mark the corrected paths\n"
 220                                 "with 'git add <paths>' or 'git rm <paths>'"));
 221                else
 222                        advise(_("after resolving the conflicts, mark the corrected paths\n"
 223                                 "with 'git add <paths>' or 'git rm <paths>'\n"
 224                                 "and commit the result with 'git commit'"));
 225        }
 226}
 227
 228static int write_message(const void *buf, size_t len, const char *filename,
 229                         int append_eol)
 230{
 231        static struct lock_file msg_file;
 232
 233        int msg_fd = hold_lock_file_for_update(&msg_file, filename, 0);
 234        if (msg_fd < 0)
 235                return error_errno(_("could not lock '%s'"), filename);
 236        if (write_in_full(msg_fd, buf, len) < 0) {
 237                rollback_lock_file(&msg_file);
 238                return error_errno(_("could not write to '%s'"), filename);
 239        }
 240        if (append_eol && write(msg_fd, "\n", 1) < 0) {
 241                rollback_lock_file(&msg_file);
 242                return error_errno(_("could not write eol to '%s'"), filename);
 243        }
 244        if (commit_lock_file(&msg_file) < 0) {
 245                rollback_lock_file(&msg_file);
 246                return error(_("failed to finalize '%s'."), filename);
 247        }
 248
 249        return 0;
 250}
 251
 252/*
 253 * Reads a file that was presumably written by a shell script, i.e. with an
 254 * end-of-line marker that needs to be stripped.
 255 *
 256 * Note that only the last end-of-line marker is stripped, consistent with the
 257 * behavior of "$(cat path)" in a shell script.
 258 *
 259 * Returns 1 if the file was read, 0 if it could not be read or does not exist.
 260 */
 261static int read_oneliner(struct strbuf *buf,
 262        const char *path, int skip_if_empty)
 263{
 264        int orig_len = buf->len;
 265
 266        if (!file_exists(path))
 267                return 0;
 268
 269        if (strbuf_read_file(buf, path, 0) < 0) {
 270                warning_errno(_("could not read '%s'"), path);
 271                return 0;
 272        }
 273
 274        if (buf->len > orig_len && buf->buf[buf->len - 1] == '\n') {
 275                if (--buf->len > orig_len && buf->buf[buf->len - 1] == '\r')
 276                        --buf->len;
 277                buf->buf[buf->len] = '\0';
 278        }
 279
 280        if (skip_if_empty && buf->len == orig_len)
 281                return 0;
 282
 283        return 1;
 284}
 285
 286static struct tree *empty_tree(void)
 287{
 288        return lookup_tree(EMPTY_TREE_SHA1_BIN);
 289}
 290
 291static int error_dirty_index(struct replay_opts *opts)
 292{
 293        if (read_cache_unmerged())
 294                return error_resolve_conflict(_(action_name(opts)));
 295
 296        error(_("your local changes would be overwritten by %s."),
 297                _(action_name(opts)));
 298
 299        if (advice_commit_before_merge)
 300                advise(_("commit your changes or stash them to proceed."));
 301        return -1;
 302}
 303
 304static void update_abort_safety_file(void)
 305{
 306        struct object_id head;
 307
 308        /* Do nothing on a single-pick */
 309        if (!file_exists(git_path_seq_dir()))
 310                return;
 311
 312        if (!get_oid("HEAD", &head))
 313                write_file(git_path_abort_safety_file(), "%s", oid_to_hex(&head));
 314        else
 315                write_file(git_path_abort_safety_file(), "%s", "");
 316}
 317
 318static int fast_forward_to(const unsigned char *to, const unsigned char *from,
 319                        int unborn, struct replay_opts *opts)
 320{
 321        struct ref_transaction *transaction;
 322        struct strbuf sb = STRBUF_INIT;
 323        struct strbuf err = STRBUF_INIT;
 324
 325        read_cache();
 326        if (checkout_fast_forward(from, to, 1))
 327                return -1; /* the callee should have complained already */
 328
 329        strbuf_addf(&sb, _("%s: fast-forward"), _(action_name(opts)));
 330
 331        transaction = ref_transaction_begin(&err);
 332        if (!transaction ||
 333            ref_transaction_update(transaction, "HEAD",
 334                                   to, unborn ? null_sha1 : from,
 335                                   0, sb.buf, &err) ||
 336            ref_transaction_commit(transaction, &err)) {
 337                ref_transaction_free(transaction);
 338                error("%s", err.buf);
 339                strbuf_release(&sb);
 340                strbuf_release(&err);
 341                return -1;
 342        }
 343
 344        strbuf_release(&sb);
 345        strbuf_release(&err);
 346        ref_transaction_free(transaction);
 347        update_abort_safety_file();
 348        return 0;
 349}
 350
 351void append_conflicts_hint(struct strbuf *msgbuf)
 352{
 353        int i;
 354
 355        strbuf_addch(msgbuf, '\n');
 356        strbuf_commented_addf(msgbuf, "Conflicts:\n");
 357        for (i = 0; i < active_nr;) {
 358                const struct cache_entry *ce = active_cache[i++];
 359                if (ce_stage(ce)) {
 360                        strbuf_commented_addf(msgbuf, "\t%s\n", ce->name);
 361                        while (i < active_nr && !strcmp(ce->name,
 362                                                        active_cache[i]->name))
 363                                i++;
 364                }
 365        }
 366}
 367
 368static int do_recursive_merge(struct commit *base, struct commit *next,
 369                              const char *base_label, const char *next_label,
 370                              unsigned char *head, struct strbuf *msgbuf,
 371                              struct replay_opts *opts)
 372{
 373        struct merge_options o;
 374        struct tree *result, *next_tree, *base_tree, *head_tree;
 375        int clean;
 376        char **xopt;
 377        static struct lock_file index_lock;
 378
 379        hold_locked_index(&index_lock, LOCK_DIE_ON_ERROR);
 380
 381        read_cache();
 382
 383        init_merge_options(&o);
 384        o.ancestor = base ? base_label : "(empty tree)";
 385        o.branch1 = "HEAD";
 386        o.branch2 = next ? next_label : "(empty tree)";
 387
 388        head_tree = parse_tree_indirect(head);
 389        next_tree = next ? next->tree : empty_tree();
 390        base_tree = base ? base->tree : empty_tree();
 391
 392        for (xopt = opts->xopts; xopt != opts->xopts + opts->xopts_nr; xopt++)
 393                parse_merge_opt(&o, *xopt);
 394
 395        clean = merge_trees(&o,
 396                            head_tree,
 397                            next_tree, base_tree, &result);
 398        strbuf_release(&o.obuf);
 399        if (clean < 0)
 400                return clean;
 401
 402        if (active_cache_changed &&
 403            write_locked_index(&the_index, &index_lock, COMMIT_LOCK))
 404                /* TRANSLATORS: %s will be "revert", "cherry-pick" or
 405                 * "rebase -i".
 406                 */
 407                return error(_("%s: Unable to write new index file"),
 408                        _(action_name(opts)));
 409        rollback_lock_file(&index_lock);
 410
 411        if (opts->signoff)
 412                append_signoff(msgbuf, 0, 0);
 413
 414        if (!clean)
 415                append_conflicts_hint(msgbuf);
 416
 417        return !clean;
 418}
 419
 420static int is_index_unchanged(void)
 421{
 422        unsigned char head_sha1[20];
 423        struct commit *head_commit;
 424
 425        if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, head_sha1, NULL))
 426                return error(_("could not resolve HEAD commit\n"));
 427
 428        head_commit = lookup_commit(head_sha1);
 429
 430        /*
 431         * If head_commit is NULL, check_commit, called from
 432         * lookup_commit, would have indicated that head_commit is not
 433         * a commit object already.  parse_commit() will return failure
 434         * without further complaints in such a case.  Otherwise, if
 435         * the commit is invalid, parse_commit() will complain.  So
 436         * there is nothing for us to say here.  Just return failure.
 437         */
 438        if (parse_commit(head_commit))
 439                return -1;
 440
 441        if (!active_cache_tree)
 442                active_cache_tree = cache_tree();
 443
 444        if (!cache_tree_fully_valid(active_cache_tree))
 445                if (cache_tree_update(&the_index, 0))
 446                        return error(_("unable to update cache tree\n"));
 447
 448        return !hashcmp(active_cache_tree->sha1, head_commit->tree->object.oid.hash);
 449}
 450
 451/*
 452 * Read the author-script file into an environment block, ready for use in
 453 * run_command(), that can be free()d afterwards.
 454 */
 455static char **read_author_script(void)
 456{
 457        struct strbuf script = STRBUF_INIT;
 458        int i, count = 0;
 459        char *p, *p2, **env;
 460        size_t env_size;
 461
 462        if (strbuf_read_file(&script, rebase_path_author_script(), 256) <= 0)
 463                return NULL;
 464
 465        for (p = script.buf; *p; p++)
 466                if (skip_prefix(p, "'\\\\''", (const char **)&p2))
 467                        strbuf_splice(&script, p - script.buf, p2 - p, "'", 1);
 468                else if (*p == '\'')
 469                        strbuf_splice(&script, p-- - script.buf, 1, "", 0);
 470                else if (*p == '\n') {
 471                        *p = '\0';
 472                        count++;
 473                }
 474
 475        env_size = (count + 1) * sizeof(*env);
 476        strbuf_grow(&script, env_size);
 477        memmove(script.buf + env_size, script.buf, script.len);
 478        p = script.buf + env_size;
 479        env = (char **)strbuf_detach(&script, NULL);
 480
 481        for (i = 0; i < count; i++) {
 482                env[i] = p;
 483                p += strlen(p) + 1;
 484        }
 485        env[count] = NULL;
 486
 487        return env;
 488}
 489
 490static const char staged_changes_advice[] =
 491N_("you have staged changes in your working tree\n"
 492"If these changes are meant to be squashed into the previous commit, run:\n"
 493"\n"
 494"  git commit --amend %s\n"
 495"\n"
 496"If they are meant to go into a new commit, run:\n"
 497"\n"
 498"  git commit %s\n"
 499"\n"
 500"In both cases, once you're done, continue with:\n"
 501"\n"
 502"  git rebase --continue\n");
 503
 504/*
 505 * If we are cherry-pick, and if the merge did not result in
 506 * hand-editing, we will hit this commit and inherit the original
 507 * author date and name.
 508 *
 509 * If we are revert, or if our cherry-pick results in a hand merge,
 510 * we had better say that the current user is responsible for that.
 511 *
 512 * An exception is when run_git_commit() is called during an
 513 * interactive rebase: in that case, we will want to retain the
 514 * author metadata.
 515 */
 516static int run_git_commit(const char *defmsg, struct replay_opts *opts,
 517                          int allow_empty, int edit, int amend,
 518                          int cleanup_commit_message)
 519{
 520        char **env = NULL;
 521        struct argv_array array;
 522        int rc;
 523        const char *value;
 524
 525        if (is_rebase_i(opts)) {
 526                env = read_author_script();
 527                if (!env) {
 528                        const char *gpg_opt = gpg_sign_opt_quoted(opts);
 529
 530                        return error(_(staged_changes_advice),
 531                                     gpg_opt, gpg_opt);
 532                }
 533        }
 534
 535        argv_array_init(&array);
 536        argv_array_push(&array, "commit");
 537        argv_array_push(&array, "-n");
 538
 539        if (amend)
 540                argv_array_push(&array, "--amend");
 541        if (opts->gpg_sign)
 542                argv_array_pushf(&array, "-S%s", opts->gpg_sign);
 543        if (opts->signoff)
 544                argv_array_push(&array, "-s");
 545        if (defmsg)
 546                argv_array_pushl(&array, "-F", defmsg, NULL);
 547        if (cleanup_commit_message)
 548                argv_array_push(&array, "--cleanup=strip");
 549        if (edit)
 550                argv_array_push(&array, "-e");
 551        else if (!cleanup_commit_message &&
 552                 !opts->signoff && !opts->record_origin &&
 553                 git_config_get_value("commit.cleanup", &value))
 554                argv_array_push(&array, "--cleanup=verbatim");
 555
 556        if (allow_empty)
 557                argv_array_push(&array, "--allow-empty");
 558
 559        if (opts->allow_empty_message)
 560                argv_array_push(&array, "--allow-empty-message");
 561
 562        rc = run_command_v_opt_cd_env(array.argv, RUN_GIT_CMD, NULL,
 563                        (const char *const *)env);
 564        argv_array_clear(&array);
 565        free(env);
 566
 567        return rc;
 568}
 569
 570static int is_original_commit_empty(struct commit *commit)
 571{
 572        const unsigned char *ptree_sha1;
 573
 574        if (parse_commit(commit))
 575                return error(_("could not parse commit %s\n"),
 576                             oid_to_hex(&commit->object.oid));
 577        if (commit->parents) {
 578                struct commit *parent = commit->parents->item;
 579                if (parse_commit(parent))
 580                        return error(_("could not parse parent commit %s\n"),
 581                                oid_to_hex(&parent->object.oid));
 582                ptree_sha1 = parent->tree->object.oid.hash;
 583        } else {
 584                ptree_sha1 = EMPTY_TREE_SHA1_BIN; /* commit is root */
 585        }
 586
 587        return !hashcmp(ptree_sha1, commit->tree->object.oid.hash);
 588}
 589
 590/*
 591 * Do we run "git commit" with "--allow-empty"?
 592 */
 593static int allow_empty(struct replay_opts *opts, struct commit *commit)
 594{
 595        int index_unchanged, empty_commit;
 596
 597        /*
 598         * Three cases:
 599         *
 600         * (1) we do not allow empty at all and error out.
 601         *
 602         * (2) we allow ones that were initially empty, but
 603         * forbid the ones that become empty;
 604         *
 605         * (3) we allow both.
 606         */
 607        if (!opts->allow_empty)
 608                return 0; /* let "git commit" barf as necessary */
 609
 610        index_unchanged = is_index_unchanged();
 611        if (index_unchanged < 0)
 612                return index_unchanged;
 613        if (!index_unchanged)
 614                return 0; /* we do not have to say --allow-empty */
 615
 616        if (opts->keep_redundant_commits)
 617                return 1;
 618
 619        empty_commit = is_original_commit_empty(commit);
 620        if (empty_commit < 0)
 621                return empty_commit;
 622        if (!empty_commit)
 623                return 0;
 624        else
 625                return 1;
 626}
 627
 628/*
 629 * Note that ordering matters in this enum. Not only must it match the mapping
 630 * below, it is also divided into several sections that matter.  When adding
 631 * new commands, make sure you add it in the right section.
 632 */
 633enum todo_command {
 634        /* commands that handle commits */
 635        TODO_PICK = 0,
 636        TODO_REVERT,
 637        TODO_EDIT,
 638        /* commands that do something else than handling a single commit */
 639        TODO_EXEC,
 640        /* commands that do nothing but are counted for reporting progress */
 641        TODO_NOOP
 642};
 643
 644static const char *todo_command_strings[] = {
 645        "pick",
 646        "revert",
 647        "edit",
 648        "exec",
 649        "noop"
 650};
 651
 652static const char *command_to_string(const enum todo_command command)
 653{
 654        if ((size_t)command < ARRAY_SIZE(todo_command_strings))
 655                return todo_command_strings[command];
 656        die("Unknown command: %d", command);
 657}
 658
 659static int is_noop(const enum todo_command command)
 660{
 661        return TODO_NOOP <= (size_t)command;
 662}
 663
 664static int do_pick_commit(enum todo_command command, struct commit *commit,
 665                struct replay_opts *opts)
 666{
 667        unsigned char head[20];
 668        struct commit *base, *next, *parent;
 669        const char *base_label, *next_label;
 670        struct commit_message msg = { NULL, NULL, NULL, NULL };
 671        struct strbuf msgbuf = STRBUF_INIT;
 672        int res, unborn = 0, allow;
 673
 674        if (opts->no_commit) {
 675                /*
 676                 * We do not intend to commit immediately.  We just want to
 677                 * merge the differences in, so let's compute the tree
 678                 * that represents the "current" state for merge-recursive
 679                 * to work on.
 680                 */
 681                if (write_cache_as_tree(head, 0, NULL))
 682                        return error(_("your index file is unmerged."));
 683        } else {
 684                unborn = get_sha1("HEAD", head);
 685                if (unborn)
 686                        hashcpy(head, EMPTY_TREE_SHA1_BIN);
 687                if (index_differs_from(unborn ? EMPTY_TREE_SHA1_HEX : "HEAD", 0, 0))
 688                        return error_dirty_index(opts);
 689        }
 690        discard_cache();
 691
 692        if (!commit->parents)
 693                parent = NULL;
 694        else if (commit->parents->next) {
 695                /* Reverting or cherry-picking a merge commit */
 696                int cnt;
 697                struct commit_list *p;
 698
 699                if (!opts->mainline)
 700                        return error(_("commit %s is a merge but no -m option was given."),
 701                                oid_to_hex(&commit->object.oid));
 702
 703                for (cnt = 1, p = commit->parents;
 704                     cnt != opts->mainline && p;
 705                     cnt++)
 706                        p = p->next;
 707                if (cnt != opts->mainline || !p)
 708                        return error(_("commit %s does not have parent %d"),
 709                                oid_to_hex(&commit->object.oid), opts->mainline);
 710                parent = p->item;
 711        } else if (0 < opts->mainline)
 712                return error(_("mainline was specified but commit %s is not a merge."),
 713                        oid_to_hex(&commit->object.oid));
 714        else
 715                parent = commit->parents->item;
 716
 717        if (opts->allow_ff &&
 718            ((parent && !hashcmp(parent->object.oid.hash, head)) ||
 719             (!parent && unborn)))
 720                return fast_forward_to(commit->object.oid.hash, head, unborn, opts);
 721
 722        if (parent && parse_commit(parent) < 0)
 723                /* TRANSLATORS: The first %s will be a "todo" command like
 724                   "revert" or "pick", the second %s a SHA1. */
 725                return error(_("%s: cannot parse parent commit %s"),
 726                        command_to_string(command),
 727                        oid_to_hex(&parent->object.oid));
 728
 729        if (get_message(commit, &msg) != 0)
 730                return error(_("cannot get commit message for %s"),
 731                        oid_to_hex(&commit->object.oid));
 732
 733        /*
 734         * "commit" is an existing commit.  We would want to apply
 735         * the difference it introduces since its first parent "prev"
 736         * on top of the current HEAD if we are cherry-pick.  Or the
 737         * reverse of it if we are revert.
 738         */
 739
 740        if (command == TODO_REVERT) {
 741                base = commit;
 742                base_label = msg.label;
 743                next = parent;
 744                next_label = msg.parent_label;
 745                strbuf_addstr(&msgbuf, "Revert \"");
 746                strbuf_addstr(&msgbuf, msg.subject);
 747                strbuf_addstr(&msgbuf, "\"\n\nThis reverts commit ");
 748                strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
 749
 750                if (commit->parents && commit->parents->next) {
 751                        strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
 752                        strbuf_addstr(&msgbuf, oid_to_hex(&parent->object.oid));
 753                }
 754                strbuf_addstr(&msgbuf, ".\n");
 755        } else {
 756                const char *p;
 757
 758                base = parent;
 759                base_label = msg.parent_label;
 760                next = commit;
 761                next_label = msg.label;
 762
 763                /* Append the commit log message to msgbuf. */
 764                if (find_commit_subject(msg.message, &p))
 765                        strbuf_addstr(&msgbuf, p);
 766
 767                if (opts->record_origin) {
 768                        if (!has_conforming_footer(&msgbuf, NULL, 0))
 769                                strbuf_addch(&msgbuf, '\n');
 770                        strbuf_addstr(&msgbuf, cherry_picked_prefix);
 771                        strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
 772                        strbuf_addstr(&msgbuf, ")\n");
 773                }
 774        }
 775
 776        if (!opts->strategy || !strcmp(opts->strategy, "recursive") || command == TODO_REVERT) {
 777                res = do_recursive_merge(base, next, base_label, next_label,
 778                                         head, &msgbuf, opts);
 779                if (res < 0)
 780                        return res;
 781                res |= write_message(msgbuf.buf, msgbuf.len,
 782                                     git_path_merge_msg(), 0);
 783        } else {
 784                struct commit_list *common = NULL;
 785                struct commit_list *remotes = NULL;
 786
 787                res = write_message(msgbuf.buf, msgbuf.len,
 788                                    git_path_merge_msg(), 0);
 789
 790                commit_list_insert(base, &common);
 791                commit_list_insert(next, &remotes);
 792                res |= try_merge_command(opts->strategy,
 793                                         opts->xopts_nr, (const char **)opts->xopts,
 794                                        common, sha1_to_hex(head), remotes);
 795                free_commit_list(common);
 796                free_commit_list(remotes);
 797        }
 798        strbuf_release(&msgbuf);
 799
 800        /*
 801         * If the merge was clean or if it failed due to conflict, we write
 802         * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
 803         * However, if the merge did not even start, then we don't want to
 804         * write it at all.
 805         */
 806        if (command == TODO_PICK && !opts->no_commit && (res == 0 || res == 1) &&
 807            update_ref(NULL, "CHERRY_PICK_HEAD", commit->object.oid.hash, NULL,
 808                       REF_NODEREF, UPDATE_REFS_MSG_ON_ERR))
 809                res = -1;
 810        if (command == TODO_REVERT && ((opts->no_commit && res == 0) || res == 1) &&
 811            update_ref(NULL, "REVERT_HEAD", commit->object.oid.hash, NULL,
 812                       REF_NODEREF, UPDATE_REFS_MSG_ON_ERR))
 813                res = -1;
 814
 815        if (res) {
 816                error(command == TODO_REVERT
 817                      ? _("could not revert %s... %s")
 818                      : _("could not apply %s... %s"),
 819                      short_commit_name(commit), msg.subject);
 820                print_advice(res == 1, opts);
 821                rerere(opts->allow_rerere_auto);
 822                goto leave;
 823        }
 824
 825        allow = allow_empty(opts, commit);
 826        if (allow < 0) {
 827                res = allow;
 828                goto leave;
 829        }
 830        if (!opts->no_commit)
 831                res = run_git_commit(opts->edit ? NULL : git_path_merge_msg(),
 832                                     opts, allow, opts->edit, 0, 0);
 833
 834leave:
 835        free_message(commit, &msg);
 836        update_abort_safety_file();
 837
 838        return res;
 839}
 840
 841static int prepare_revs(struct replay_opts *opts)
 842{
 843        /*
 844         * picking (but not reverting) ranges (but not individual revisions)
 845         * should be done in reverse
 846         */
 847        if (opts->action == REPLAY_PICK && !opts->revs->no_walk)
 848                opts->revs->reverse ^= 1;
 849
 850        if (prepare_revision_walk(opts->revs))
 851                return error(_("revision walk setup failed"));
 852
 853        if (!opts->revs->commits)
 854                return error(_("empty commit set passed"));
 855        return 0;
 856}
 857
 858static int read_and_refresh_cache(struct replay_opts *opts)
 859{
 860        static struct lock_file index_lock;
 861        int index_fd = hold_locked_index(&index_lock, 0);
 862        if (read_index_preload(&the_index, NULL) < 0) {
 863                rollback_lock_file(&index_lock);
 864                return error(_("git %s: failed to read the index"),
 865                        _(action_name(opts)));
 866        }
 867        refresh_index(&the_index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
 868        if (the_index.cache_changed && index_fd >= 0) {
 869                if (write_locked_index(&the_index, &index_lock, COMMIT_LOCK)) {
 870                        rollback_lock_file(&index_lock);
 871                        return error(_("git %s: failed to refresh the index"),
 872                                _(action_name(opts)));
 873                }
 874        }
 875        rollback_lock_file(&index_lock);
 876        return 0;
 877}
 878
 879struct todo_item {
 880        enum todo_command command;
 881        struct commit *commit;
 882        const char *arg;
 883        int arg_len;
 884        size_t offset_in_buf;
 885};
 886
 887struct todo_list {
 888        struct strbuf buf;
 889        struct todo_item *items;
 890        int nr, alloc, current;
 891};
 892
 893#define TODO_LIST_INIT { STRBUF_INIT }
 894
 895static void todo_list_release(struct todo_list *todo_list)
 896{
 897        strbuf_release(&todo_list->buf);
 898        free(todo_list->items);
 899        todo_list->items = NULL;
 900        todo_list->nr = todo_list->alloc = 0;
 901}
 902
 903static struct todo_item *append_new_todo(struct todo_list *todo_list)
 904{
 905        ALLOC_GROW(todo_list->items, todo_list->nr + 1, todo_list->alloc);
 906        return todo_list->items + todo_list->nr++;
 907}
 908
 909static int parse_insn_line(struct todo_item *item, const char *bol, char *eol)
 910{
 911        unsigned char commit_sha1[20];
 912        char *end_of_object_name;
 913        int i, saved, status, padding;
 914
 915        /* left-trim */
 916        bol += strspn(bol, " \t");
 917
 918        if (bol == eol || *bol == '\r' || *bol == comment_line_char) {
 919                item->command = TODO_NOOP;
 920                item->commit = NULL;
 921                item->arg = bol;
 922                item->arg_len = eol - bol;
 923                return 0;
 924        }
 925
 926        for (i = 0; i < ARRAY_SIZE(todo_command_strings); i++)
 927                if (skip_prefix(bol, todo_command_strings[i], &bol)) {
 928                        item->command = i;
 929                        break;
 930                }
 931        if (i >= ARRAY_SIZE(todo_command_strings))
 932                return -1;
 933
 934        if (item->command == TODO_NOOP) {
 935                item->commit = NULL;
 936                item->arg = bol;
 937                item->arg_len = eol - bol;
 938                return 0;
 939        }
 940
 941        /* Eat up extra spaces/ tabs before object name */
 942        padding = strspn(bol, " \t");
 943        if (!padding)
 944                return -1;
 945        bol += padding;
 946
 947        if (item->command == TODO_EXEC) {
 948                item->arg = bol;
 949                item->arg_len = (int)(eol - bol);
 950                return 0;
 951        }
 952
 953        end_of_object_name = (char *) bol + strcspn(bol, " \t\n");
 954        saved = *end_of_object_name;
 955        *end_of_object_name = '\0';
 956        status = get_sha1(bol, commit_sha1);
 957        *end_of_object_name = saved;
 958
 959        item->arg = end_of_object_name + strspn(end_of_object_name, " \t");
 960        item->arg_len = (int)(eol - item->arg);
 961
 962        if (status < 0)
 963                return -1;
 964
 965        item->commit = lookup_commit_reference(commit_sha1);
 966        return !item->commit;
 967}
 968
 969static int parse_insn_buffer(char *buf, struct todo_list *todo_list)
 970{
 971        struct todo_item *item;
 972        char *p = buf, *next_p;
 973        int i, res = 0;
 974
 975        for (i = 1; *p; i++, p = next_p) {
 976                char *eol = strchrnul(p, '\n');
 977
 978                next_p = *eol ? eol + 1 /* skip LF */ : eol;
 979
 980                if (p != eol && eol[-1] == '\r')
 981                        eol--; /* strip Carriage Return */
 982
 983                item = append_new_todo(todo_list);
 984                item->offset_in_buf = p - todo_list->buf.buf;
 985                if (parse_insn_line(item, p, eol)) {
 986                        res = error(_("invalid line %d: %.*s"),
 987                                i, (int)(eol - p), p);
 988                        item->command = -1;
 989                }
 990        }
 991        if (!todo_list->nr)
 992                return error(_("no commits parsed."));
 993        return res;
 994}
 995
 996static int read_populate_todo(struct todo_list *todo_list,
 997                        struct replay_opts *opts)
 998{
 999        const char *todo_file = get_todo_path(opts);
1000        int fd, res;
1001
1002        strbuf_reset(&todo_list->buf);
1003        fd = open(todo_file, O_RDONLY);
1004        if (fd < 0)
1005                return error_errno(_("could not open '%s'"), todo_file);
1006        if (strbuf_read(&todo_list->buf, fd, 0) < 0) {
1007                close(fd);
1008                return error(_("could not read '%s'."), todo_file);
1009        }
1010        close(fd);
1011
1012        res = parse_insn_buffer(todo_list->buf.buf, todo_list);
1013        if (res)
1014                return error(_("unusable instruction sheet: '%s'"), todo_file);
1015
1016        if (!is_rebase_i(opts)) {
1017                enum todo_command valid =
1018                        opts->action == REPLAY_PICK ? TODO_PICK : TODO_REVERT;
1019                int i;
1020
1021                for (i = 0; i < todo_list->nr; i++)
1022                        if (valid == todo_list->items[i].command)
1023                                continue;
1024                        else if (valid == TODO_PICK)
1025                                return error(_("cannot cherry-pick during a revert."));
1026                        else
1027                                return error(_("cannot revert during a cherry-pick."));
1028        }
1029
1030        return 0;
1031}
1032
1033static int git_config_string_dup(char **dest,
1034                                 const char *var, const char *value)
1035{
1036        if (!value)
1037                return config_error_nonbool(var);
1038        free(*dest);
1039        *dest = xstrdup(value);
1040        return 0;
1041}
1042
1043static int populate_opts_cb(const char *key, const char *value, void *data)
1044{
1045        struct replay_opts *opts = data;
1046        int error_flag = 1;
1047
1048        if (!value)
1049                error_flag = 0;
1050        else if (!strcmp(key, "options.no-commit"))
1051                opts->no_commit = git_config_bool_or_int(key, value, &error_flag);
1052        else if (!strcmp(key, "options.edit"))
1053                opts->edit = git_config_bool_or_int(key, value, &error_flag);
1054        else if (!strcmp(key, "options.signoff"))
1055                opts->signoff = git_config_bool_or_int(key, value, &error_flag);
1056        else if (!strcmp(key, "options.record-origin"))
1057                opts->record_origin = git_config_bool_or_int(key, value, &error_flag);
1058        else if (!strcmp(key, "options.allow-ff"))
1059                opts->allow_ff = git_config_bool_or_int(key, value, &error_flag);
1060        else if (!strcmp(key, "options.mainline"))
1061                opts->mainline = git_config_int(key, value);
1062        else if (!strcmp(key, "options.strategy"))
1063                git_config_string_dup(&opts->strategy, key, value);
1064        else if (!strcmp(key, "options.gpg-sign"))
1065                git_config_string_dup(&opts->gpg_sign, key, value);
1066        else if (!strcmp(key, "options.strategy-option")) {
1067                ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
1068                opts->xopts[opts->xopts_nr++] = xstrdup(value);
1069        } else
1070                return error(_("invalid key: %s"), key);
1071
1072        if (!error_flag)
1073                return error(_("invalid value for %s: %s"), key, value);
1074
1075        return 0;
1076}
1077
1078static int read_populate_opts(struct replay_opts *opts)
1079{
1080        if (is_rebase_i(opts)) {
1081                struct strbuf buf = STRBUF_INIT;
1082
1083                if (read_oneliner(&buf, rebase_path_gpg_sign_opt(), 1)) {
1084                        if (!starts_with(buf.buf, "-S"))
1085                                strbuf_reset(&buf);
1086                        else {
1087                                free(opts->gpg_sign);
1088                                opts->gpg_sign = xstrdup(buf.buf + 2);
1089                        }
1090                }
1091                strbuf_release(&buf);
1092
1093                if (file_exists(rebase_path_verbose()))
1094                        opts->verbose = 1;
1095
1096                return 0;
1097        }
1098
1099        if (!file_exists(git_path_opts_file()))
1100                return 0;
1101        /*
1102         * The function git_parse_source(), called from git_config_from_file(),
1103         * may die() in case of a syntactically incorrect file. We do not care
1104         * about this case, though, because we wrote that file ourselves, so we
1105         * are pretty certain that it is syntactically correct.
1106         */
1107        if (git_config_from_file(populate_opts_cb, git_path_opts_file(), opts) < 0)
1108                return error(_("malformed options sheet: '%s'"),
1109                        git_path_opts_file());
1110        return 0;
1111}
1112
1113static int walk_revs_populate_todo(struct todo_list *todo_list,
1114                                struct replay_opts *opts)
1115{
1116        enum todo_command command = opts->action == REPLAY_PICK ?
1117                TODO_PICK : TODO_REVERT;
1118        const char *command_string = todo_command_strings[command];
1119        struct commit *commit;
1120
1121        if (prepare_revs(opts))
1122                return -1;
1123
1124        while ((commit = get_revision(opts->revs))) {
1125                struct todo_item *item = append_new_todo(todo_list);
1126                const char *commit_buffer = get_commit_buffer(commit, NULL);
1127                const char *subject;
1128                int subject_len;
1129
1130                item->command = command;
1131                item->commit = commit;
1132                item->arg = NULL;
1133                item->arg_len = 0;
1134                item->offset_in_buf = todo_list->buf.len;
1135                subject_len = find_commit_subject(commit_buffer, &subject);
1136                strbuf_addf(&todo_list->buf, "%s %s %.*s\n", command_string,
1137                        short_commit_name(commit), subject_len, subject);
1138                unuse_commit_buffer(commit, commit_buffer);
1139        }
1140        return 0;
1141}
1142
1143static int create_seq_dir(void)
1144{
1145        if (file_exists(git_path_seq_dir())) {
1146                error(_("a cherry-pick or revert is already in progress"));
1147                advise(_("try \"git cherry-pick (--continue | --quit | --abort)\""));
1148                return -1;
1149        } else if (mkdir(git_path_seq_dir(), 0777) < 0)
1150                return error_errno(_("could not create sequencer directory '%s'"),
1151                                   git_path_seq_dir());
1152        return 0;
1153}
1154
1155static int save_head(const char *head)
1156{
1157        static struct lock_file head_lock;
1158        struct strbuf buf = STRBUF_INIT;
1159        int fd;
1160
1161        fd = hold_lock_file_for_update(&head_lock, git_path_head_file(), 0);
1162        if (fd < 0) {
1163                rollback_lock_file(&head_lock);
1164                return error_errno(_("could not lock HEAD"));
1165        }
1166        strbuf_addf(&buf, "%s\n", head);
1167        if (write_in_full(fd, buf.buf, buf.len) < 0) {
1168                rollback_lock_file(&head_lock);
1169                return error_errno(_("could not write to '%s'"),
1170                                   git_path_head_file());
1171        }
1172        if (commit_lock_file(&head_lock) < 0) {
1173                rollback_lock_file(&head_lock);
1174                return error(_("failed to finalize '%s'."), git_path_head_file());
1175        }
1176        return 0;
1177}
1178
1179static int rollback_is_safe(void)
1180{
1181        struct strbuf sb = STRBUF_INIT;
1182        struct object_id expected_head, actual_head;
1183
1184        if (strbuf_read_file(&sb, git_path_abort_safety_file(), 0) >= 0) {
1185                strbuf_trim(&sb);
1186                if (get_oid_hex(sb.buf, &expected_head)) {
1187                        strbuf_release(&sb);
1188                        die(_("could not parse %s"), git_path_abort_safety_file());
1189                }
1190                strbuf_release(&sb);
1191        }
1192        else if (errno == ENOENT)
1193                oidclr(&expected_head);
1194        else
1195                die_errno(_("could not read '%s'"), git_path_abort_safety_file());
1196
1197        if (get_oid("HEAD", &actual_head))
1198                oidclr(&actual_head);
1199
1200        return !oidcmp(&actual_head, &expected_head);
1201}
1202
1203static int reset_for_rollback(const unsigned char *sha1)
1204{
1205        const char *argv[4];    /* reset --merge <arg> + NULL */
1206
1207        argv[0] = "reset";
1208        argv[1] = "--merge";
1209        argv[2] = sha1_to_hex(sha1);
1210        argv[3] = NULL;
1211        return run_command_v_opt(argv, RUN_GIT_CMD);
1212}
1213
1214static int rollback_single_pick(void)
1215{
1216        unsigned char head_sha1[20];
1217
1218        if (!file_exists(git_path_cherry_pick_head()) &&
1219            !file_exists(git_path_revert_head()))
1220                return error(_("no cherry-pick or revert in progress"));
1221        if (read_ref_full("HEAD", 0, head_sha1, NULL))
1222                return error(_("cannot resolve HEAD"));
1223        if (is_null_sha1(head_sha1))
1224                return error(_("cannot abort from a branch yet to be born"));
1225        return reset_for_rollback(head_sha1);
1226}
1227
1228int sequencer_rollback(struct replay_opts *opts)
1229{
1230        FILE *f;
1231        unsigned char sha1[20];
1232        struct strbuf buf = STRBUF_INIT;
1233
1234        f = fopen(git_path_head_file(), "r");
1235        if (!f && errno == ENOENT) {
1236                /*
1237                 * There is no multiple-cherry-pick in progress.
1238                 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
1239                 * a single-cherry-pick in progress, abort that.
1240                 */
1241                return rollback_single_pick();
1242        }
1243        if (!f)
1244                return error_errno(_("cannot open '%s'"), git_path_head_file());
1245        if (strbuf_getline_lf(&buf, f)) {
1246                error(_("cannot read '%s': %s"), git_path_head_file(),
1247                      ferror(f) ?  strerror(errno) : _("unexpected end of file"));
1248                fclose(f);
1249                goto fail;
1250        }
1251        fclose(f);
1252        if (get_sha1_hex(buf.buf, sha1) || buf.buf[40] != '\0') {
1253                error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
1254                        git_path_head_file());
1255                goto fail;
1256        }
1257        if (is_null_sha1(sha1)) {
1258                error(_("cannot abort from a branch yet to be born"));
1259                goto fail;
1260        }
1261
1262        if (!rollback_is_safe()) {
1263                /* Do not error, just do not rollback */
1264                warning(_("You seem to have moved HEAD. "
1265                          "Not rewinding, check your HEAD!"));
1266        } else
1267        if (reset_for_rollback(sha1))
1268                goto fail;
1269        strbuf_release(&buf);
1270        return sequencer_remove_state(opts);
1271fail:
1272        strbuf_release(&buf);
1273        return -1;
1274}
1275
1276static int save_todo(struct todo_list *todo_list, struct replay_opts *opts)
1277{
1278        static struct lock_file todo_lock;
1279        const char *todo_path = get_todo_path(opts);
1280        int next = todo_list->current, offset, fd;
1281
1282        /*
1283         * rebase -i writes "git-rebase-todo" without the currently executing
1284         * command, appending it to "done" instead.
1285         */
1286        if (is_rebase_i(opts))
1287                next++;
1288
1289        fd = hold_lock_file_for_update(&todo_lock, todo_path, 0);
1290        if (fd < 0)
1291                return error_errno(_("could not lock '%s'"), todo_path);
1292        offset = next < todo_list->nr ?
1293                todo_list->items[next].offset_in_buf : todo_list->buf.len;
1294        if (write_in_full(fd, todo_list->buf.buf + offset,
1295                        todo_list->buf.len - offset) < 0)
1296                return error_errno(_("could not write to '%s'"), todo_path);
1297        if (commit_lock_file(&todo_lock) < 0)
1298                return error(_("failed to finalize '%s'."), todo_path);
1299        return 0;
1300}
1301
1302static int save_opts(struct replay_opts *opts)
1303{
1304        const char *opts_file = git_path_opts_file();
1305        int res = 0;
1306
1307        if (opts->no_commit)
1308                res |= git_config_set_in_file_gently(opts_file, "options.no-commit", "true");
1309        if (opts->edit)
1310                res |= git_config_set_in_file_gently(opts_file, "options.edit", "true");
1311        if (opts->signoff)
1312                res |= git_config_set_in_file_gently(opts_file, "options.signoff", "true");
1313        if (opts->record_origin)
1314                res |= git_config_set_in_file_gently(opts_file, "options.record-origin", "true");
1315        if (opts->allow_ff)
1316                res |= git_config_set_in_file_gently(opts_file, "options.allow-ff", "true");
1317        if (opts->mainline) {
1318                struct strbuf buf = STRBUF_INIT;
1319                strbuf_addf(&buf, "%d", opts->mainline);
1320                res |= git_config_set_in_file_gently(opts_file, "options.mainline", buf.buf);
1321                strbuf_release(&buf);
1322        }
1323        if (opts->strategy)
1324                res |= git_config_set_in_file_gently(opts_file, "options.strategy", opts->strategy);
1325        if (opts->gpg_sign)
1326                res |= git_config_set_in_file_gently(opts_file, "options.gpg-sign", opts->gpg_sign);
1327        if (opts->xopts) {
1328                int i;
1329                for (i = 0; i < opts->xopts_nr; i++)
1330                        res |= git_config_set_multivar_in_file_gently(opts_file,
1331                                                        "options.strategy-option",
1332                                                        opts->xopts[i], "^$", 0);
1333        }
1334        return res;
1335}
1336
1337static int make_patch(struct commit *commit, struct replay_opts *opts)
1338{
1339        struct strbuf buf = STRBUF_INIT;
1340        struct rev_info log_tree_opt;
1341        const char *subject, *p;
1342        int res = 0;
1343
1344        p = short_commit_name(commit);
1345        if (write_message(p, strlen(p), rebase_path_stopped_sha(), 1) < 0)
1346                return -1;
1347
1348        strbuf_addf(&buf, "%s/patch", get_dir(opts));
1349        memset(&log_tree_opt, 0, sizeof(log_tree_opt));
1350        init_revisions(&log_tree_opt, NULL);
1351        log_tree_opt.abbrev = 0;
1352        log_tree_opt.diff = 1;
1353        log_tree_opt.diffopt.output_format = DIFF_FORMAT_PATCH;
1354        log_tree_opt.disable_stdin = 1;
1355        log_tree_opt.no_commit_id = 1;
1356        log_tree_opt.diffopt.file = fopen(buf.buf, "w");
1357        log_tree_opt.diffopt.use_color = GIT_COLOR_NEVER;
1358        if (!log_tree_opt.diffopt.file)
1359                res |= error_errno(_("could not open '%s'"), buf.buf);
1360        else {
1361                res |= log_tree_commit(&log_tree_opt, commit);
1362                fclose(log_tree_opt.diffopt.file);
1363        }
1364        strbuf_reset(&buf);
1365
1366        strbuf_addf(&buf, "%s/message", get_dir(opts));
1367        if (!file_exists(buf.buf)) {
1368                const char *commit_buffer = get_commit_buffer(commit, NULL);
1369                find_commit_subject(commit_buffer, &subject);
1370                res |= write_message(subject, strlen(subject), buf.buf, 1);
1371                unuse_commit_buffer(commit, commit_buffer);
1372        }
1373        strbuf_release(&buf);
1374
1375        return res;
1376}
1377
1378static int intend_to_amend(void)
1379{
1380        unsigned char head[20];
1381        char *p;
1382
1383        if (get_sha1("HEAD", head))
1384                return error(_("cannot read HEAD"));
1385
1386        p = sha1_to_hex(head);
1387        return write_message(p, strlen(p), rebase_path_amend(), 1);
1388}
1389
1390static int error_with_patch(struct commit *commit,
1391        const char *subject, int subject_len,
1392        struct replay_opts *opts, int exit_code, int to_amend)
1393{
1394        if (make_patch(commit, opts))
1395                return -1;
1396
1397        if (to_amend) {
1398                if (intend_to_amend())
1399                        return -1;
1400
1401                fprintf(stderr, "You can amend the commit now, with\n"
1402                        "\n"
1403                        "  git commit --amend %s\n"
1404                        "\n"
1405                        "Once you are satisfied with your changes, run\n"
1406                        "\n"
1407                        "  git rebase --continue\n", gpg_sign_opt_quoted(opts));
1408        } else if (exit_code)
1409                fprintf(stderr, "Could not apply %s... %.*s\n",
1410                        short_commit_name(commit), subject_len, subject);
1411
1412        return exit_code;
1413}
1414
1415static int do_exec(const char *command_line)
1416{
1417        const char *child_argv[] = { NULL, NULL };
1418        int dirty, status;
1419
1420        fprintf(stderr, "Executing: %s\n", command_line);
1421        child_argv[0] = command_line;
1422        status = run_command_v_opt(child_argv, RUN_USING_SHELL);
1423
1424        /* force re-reading of the cache */
1425        if (discard_cache() < 0 || read_cache() < 0)
1426                return error(_("could not read index"));
1427
1428        dirty = require_clean_work_tree("rebase", NULL, 1, 1);
1429
1430        if (status) {
1431                warning(_("execution failed: %s\n%s"
1432                          "You can fix the problem, and then run\n"
1433                          "\n"
1434                          "  git rebase --continue\n"
1435                          "\n"),
1436                        command_line,
1437                        dirty ? N_("and made changes to the index and/or the "
1438                                "working tree\n") : "");
1439                if (status == 127)
1440                        /* command not found */
1441                        status = 1;
1442        } else if (dirty) {
1443                warning(_("execution succeeded: %s\nbut "
1444                          "left changes to the index and/or the working tree\n"
1445                          "Commit or stash your changes, and then run\n"
1446                          "\n"
1447                          "  git rebase --continue\n"
1448                          "\n"), command_line);
1449                status = 1;
1450        }
1451
1452        return status;
1453}
1454
1455static int pick_commits(struct todo_list *todo_list, struct replay_opts *opts)
1456{
1457        int res = 0;
1458
1459        setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
1460        if (opts->allow_ff)
1461                assert(!(opts->signoff || opts->no_commit ||
1462                                opts->record_origin || opts->edit));
1463        if (read_and_refresh_cache(opts))
1464                return -1;
1465
1466        while (todo_list->current < todo_list->nr) {
1467                struct todo_item *item = todo_list->items + todo_list->current;
1468                if (save_todo(todo_list, opts))
1469                        return -1;
1470                if (item->command <= TODO_EDIT) {
1471                        res = do_pick_commit(item->command, item->commit,
1472                                        opts);
1473                        if (item->command == TODO_EDIT) {
1474                                struct commit *commit = item->commit;
1475                                if (!res)
1476                                        warning(_("stopped at %s... %.*s"),
1477                                                short_commit_name(commit),
1478                                                item->arg_len, item->arg);
1479                                return error_with_patch(commit,
1480                                        item->arg, item->arg_len, opts, res,
1481                                        !res);
1482                        }
1483                } else if (item->command == TODO_EXEC) {
1484                        char *end_of_arg = (char *)(item->arg + item->arg_len);
1485                        int saved = *end_of_arg;
1486
1487                        *end_of_arg = '\0';
1488                        res = do_exec(item->arg);
1489                        *end_of_arg = saved;
1490                } else if (!is_noop(item->command))
1491                        return error(_("unknown command %d"), item->command);
1492
1493                todo_list->current++;
1494                if (res)
1495                        return res;
1496        }
1497
1498        if (is_rebase_i(opts)) {
1499                struct strbuf buf = STRBUF_INIT;
1500
1501                /* Stopped in the middle, as planned? */
1502                if (todo_list->current < todo_list->nr)
1503                        return 0;
1504
1505                if (opts->verbose) {
1506                        struct rev_info log_tree_opt;
1507                        struct object_id orig, head;
1508
1509                        memset(&log_tree_opt, 0, sizeof(log_tree_opt));
1510                        init_revisions(&log_tree_opt, NULL);
1511                        log_tree_opt.diff = 1;
1512                        log_tree_opt.diffopt.output_format =
1513                                DIFF_FORMAT_DIFFSTAT;
1514                        log_tree_opt.disable_stdin = 1;
1515
1516                        if (read_oneliner(&buf, rebase_path_orig_head(), 0) &&
1517                            !get_sha1(buf.buf, orig.hash) &&
1518                            !get_sha1("HEAD", head.hash)) {
1519                                diff_tree_sha1(orig.hash, head.hash,
1520                                               "", &log_tree_opt.diffopt);
1521                                log_tree_diff_flush(&log_tree_opt);
1522                        }
1523                }
1524                strbuf_release(&buf);
1525        }
1526
1527        /*
1528         * Sequence of picks finished successfully; cleanup by
1529         * removing the .git/sequencer directory
1530         */
1531        return sequencer_remove_state(opts);
1532}
1533
1534static int continue_single_pick(void)
1535{
1536        const char *argv[] = { "commit", NULL };
1537
1538        if (!file_exists(git_path_cherry_pick_head()) &&
1539            !file_exists(git_path_revert_head()))
1540                return error(_("no cherry-pick or revert in progress"));
1541        return run_command_v_opt(argv, RUN_GIT_CMD);
1542}
1543
1544int sequencer_continue(struct replay_opts *opts)
1545{
1546        struct todo_list todo_list = TODO_LIST_INIT;
1547        int res;
1548
1549        if (read_and_refresh_cache(opts))
1550                return -1;
1551
1552        if (!file_exists(get_todo_path(opts)))
1553                return continue_single_pick();
1554        if (read_populate_opts(opts))
1555                return -1;
1556        if ((res = read_populate_todo(&todo_list, opts)))
1557                goto release_todo_list;
1558
1559        /* Verify that the conflict has been resolved */
1560        if (file_exists(git_path_cherry_pick_head()) ||
1561            file_exists(git_path_revert_head())) {
1562                res = continue_single_pick();
1563                if (res)
1564                        goto release_todo_list;
1565        }
1566        if (index_differs_from("HEAD", 0, 0)) {
1567                res = error_dirty_index(opts);
1568                goto release_todo_list;
1569        }
1570        todo_list.current++;
1571        res = pick_commits(&todo_list, opts);
1572release_todo_list:
1573        todo_list_release(&todo_list);
1574        return res;
1575}
1576
1577static int single_pick(struct commit *cmit, struct replay_opts *opts)
1578{
1579        setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
1580        return do_pick_commit(opts->action == REPLAY_PICK ?
1581                TODO_PICK : TODO_REVERT, cmit, opts);
1582}
1583
1584int sequencer_pick_revisions(struct replay_opts *opts)
1585{
1586        struct todo_list todo_list = TODO_LIST_INIT;
1587        unsigned char sha1[20];
1588        int i, res;
1589
1590        assert(opts->revs);
1591        if (read_and_refresh_cache(opts))
1592                return -1;
1593
1594        for (i = 0; i < opts->revs->pending.nr; i++) {
1595                unsigned char sha1[20];
1596                const char *name = opts->revs->pending.objects[i].name;
1597
1598                /* This happens when using --stdin. */
1599                if (!strlen(name))
1600                        continue;
1601
1602                if (!get_sha1(name, sha1)) {
1603                        if (!lookup_commit_reference_gently(sha1, 1)) {
1604                                enum object_type type = sha1_object_info(sha1, NULL);
1605                                return error(_("%s: can't cherry-pick a %s"),
1606                                        name, typename(type));
1607                        }
1608                } else
1609                        return error(_("%s: bad revision"), name);
1610        }
1611
1612        /*
1613         * If we were called as "git cherry-pick <commit>", just
1614         * cherry-pick/revert it, set CHERRY_PICK_HEAD /
1615         * REVERT_HEAD, and don't touch the sequencer state.
1616         * This means it is possible to cherry-pick in the middle
1617         * of a cherry-pick sequence.
1618         */
1619        if (opts->revs->cmdline.nr == 1 &&
1620            opts->revs->cmdline.rev->whence == REV_CMD_REV &&
1621            opts->revs->no_walk &&
1622            !opts->revs->cmdline.rev->flags) {
1623                struct commit *cmit;
1624                if (prepare_revision_walk(opts->revs))
1625                        return error(_("revision walk setup failed"));
1626                cmit = get_revision(opts->revs);
1627                if (!cmit || get_revision(opts->revs))
1628                        return error("BUG: expected exactly one commit from walk");
1629                return single_pick(cmit, opts);
1630        }
1631
1632        /*
1633         * Start a new cherry-pick/ revert sequence; but
1634         * first, make sure that an existing one isn't in
1635         * progress
1636         */
1637
1638        if (walk_revs_populate_todo(&todo_list, opts) ||
1639                        create_seq_dir() < 0)
1640                return -1;
1641        if (get_sha1("HEAD", sha1) && (opts->action == REPLAY_REVERT))
1642                return error(_("can't revert as initial commit"));
1643        if (save_head(sha1_to_hex(sha1)))
1644                return -1;
1645        if (save_opts(opts))
1646                return -1;
1647        update_abort_safety_file();
1648        res = pick_commits(&todo_list, opts);
1649        todo_list_release(&todo_list);
1650        return res;
1651}
1652
1653void append_signoff(struct strbuf *msgbuf, int ignore_footer, unsigned flag)
1654{
1655        unsigned no_dup_sob = flag & APPEND_SIGNOFF_DEDUP;
1656        struct strbuf sob = STRBUF_INIT;
1657        int has_footer;
1658
1659        strbuf_addstr(&sob, sign_off_header);
1660        strbuf_addstr(&sob, fmt_name(getenv("GIT_COMMITTER_NAME"),
1661                                getenv("GIT_COMMITTER_EMAIL")));
1662        strbuf_addch(&sob, '\n');
1663
1664        /*
1665         * If the whole message buffer is equal to the sob, pretend that we
1666         * found a conforming footer with a matching sob
1667         */
1668        if (msgbuf->len - ignore_footer == sob.len &&
1669            !strncmp(msgbuf->buf, sob.buf, sob.len))
1670                has_footer = 3;
1671        else
1672                has_footer = has_conforming_footer(msgbuf, &sob, ignore_footer);
1673
1674        if (!has_footer) {
1675                const char *append_newlines = NULL;
1676                size_t len = msgbuf->len - ignore_footer;
1677
1678                if (!len) {
1679                        /*
1680                         * The buffer is completely empty.  Leave foom for
1681                         * the title and body to be filled in by the user.
1682                         */
1683                        append_newlines = "\n\n";
1684                } else if (msgbuf->buf[len - 1] != '\n') {
1685                        /*
1686                         * Incomplete line.  Complete the line and add a
1687                         * blank one so that there is an empty line between
1688                         * the message body and the sob.
1689                         */
1690                        append_newlines = "\n\n";
1691                } else if (len == 1) {
1692                        /*
1693                         * Buffer contains a single newline.  Add another
1694                         * so that we leave room for the title and body.
1695                         */
1696                        append_newlines = "\n";
1697                } else if (msgbuf->buf[len - 2] != '\n') {
1698                        /*
1699                         * Buffer ends with a single newline.  Add another
1700                         * so that there is an empty line between the message
1701                         * body and the sob.
1702                         */
1703                        append_newlines = "\n";
1704                } /* else, the buffer already ends with two newlines. */
1705
1706                if (append_newlines)
1707                        strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
1708                                append_newlines, strlen(append_newlines));
1709        }
1710
1711        if (has_footer != 3 && (!no_dup_sob || has_footer != 2))
1712                strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
1713                                sob.buf, sob.len);
1714
1715        strbuf_release(&sob);
1716}