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