sequencer.con commit sequencer: avoid unnecessary indirection (5adf9bd)
   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
  19#define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
  20
  21const char sign_off_header[] = "Signed-off-by: ";
  22static const char cherry_picked_prefix[] = "(cherry picked from commit ";
  23
  24GIT_PATH_FUNC(git_path_seq_dir, "sequencer")
  25
  26static GIT_PATH_FUNC(git_path_todo_file, "sequencer/todo")
  27static GIT_PATH_FUNC(git_path_opts_file, "sequencer/opts")
  28static GIT_PATH_FUNC(git_path_head_file, "sequencer/head")
  29
  30static int is_rfc2822_line(const char *buf, int len)
  31{
  32        int i;
  33
  34        for (i = 0; i < len; i++) {
  35                int ch = buf[i];
  36                if (ch == ':')
  37                        return 1;
  38                if (!isalnum(ch) && ch != '-')
  39                        break;
  40        }
  41
  42        return 0;
  43}
  44
  45static int is_cherry_picked_from_line(const char *buf, int len)
  46{
  47        /*
  48         * We only care that it looks roughly like (cherry picked from ...)
  49         */
  50        return len > strlen(cherry_picked_prefix) + 1 &&
  51                starts_with(buf, cherry_picked_prefix) && buf[len - 1] == ')';
  52}
  53
  54/*
  55 * Returns 0 for non-conforming footer
  56 * Returns 1 for conforming footer
  57 * Returns 2 when sob exists within conforming footer
  58 * Returns 3 when sob exists within conforming footer as last entry
  59 */
  60static int has_conforming_footer(struct strbuf *sb, struct strbuf *sob,
  61        int ignore_footer)
  62{
  63        char prev;
  64        int i, k;
  65        int len = sb->len - ignore_footer;
  66        const char *buf = sb->buf;
  67        int found_sob = 0;
  68
  69        /* footer must end with newline */
  70        if (!len || buf[len - 1] != '\n')
  71                return 0;
  72
  73        prev = '\0';
  74        for (i = len - 1; i > 0; i--) {
  75                char ch = buf[i];
  76                if (prev == '\n' && ch == '\n') /* paragraph break */
  77                        break;
  78                prev = ch;
  79        }
  80
  81        /* require at least one blank line */
  82        if (prev != '\n' || buf[i] != '\n')
  83                return 0;
  84
  85        /* advance to start of last paragraph */
  86        while (i < len - 1 && buf[i] == '\n')
  87                i++;
  88
  89        for (; i < len; i = k) {
  90                int found_rfc2822;
  91
  92                for (k = i; k < len && buf[k] != '\n'; k++)
  93                        ; /* do nothing */
  94                k++;
  95
  96                found_rfc2822 = is_rfc2822_line(buf + i, k - i - 1);
  97                if (found_rfc2822 && sob &&
  98                    !strncmp(buf + i, sob->buf, sob->len))
  99                        found_sob = k;
 100
 101                if (!(found_rfc2822 ||
 102                      is_cherry_picked_from_line(buf + i, k - i - 1)))
 103                        return 0;
 104        }
 105        if (found_sob == i)
 106                return 3;
 107        if (found_sob)
 108                return 2;
 109        return 1;
 110}
 111
 112static void remove_sequencer_state(void)
 113{
 114        struct strbuf seq_dir = STRBUF_INIT;
 115
 116        strbuf_addstr(&seq_dir, git_path_seq_dir());
 117        remove_dir_recursively(&seq_dir, 0);
 118        strbuf_release(&seq_dir);
 119}
 120
 121static const char *action_name(const struct replay_opts *opts)
 122{
 123        return opts->action == REPLAY_REVERT ? "revert" : "cherry-pick";
 124}
 125
 126struct commit_message {
 127        char *parent_label;
 128        char *label;
 129        char *subject;
 130        const char *message;
 131};
 132
 133static int get_message(struct commit *commit, struct commit_message *out)
 134{
 135        const char *abbrev, *subject;
 136        int subject_len;
 137
 138        out->message = logmsg_reencode(commit, NULL, get_commit_output_encoding());
 139        abbrev = find_unique_abbrev(commit->object.oid.hash, DEFAULT_ABBREV);
 140
 141        subject_len = find_commit_subject(out->message, &subject);
 142
 143        out->subject = xmemdupz(subject, subject_len);
 144        out->label = xstrfmt("%s... %s", abbrev, out->subject);
 145        out->parent_label = xstrfmt("parent of %s", out->label);
 146
 147        return 0;
 148}
 149
 150static void free_message(struct commit *commit, struct commit_message *msg)
 151{
 152        free(msg->parent_label);
 153        free(msg->label);
 154        free(msg->subject);
 155        unuse_commit_buffer(commit, msg->message);
 156}
 157
 158static void print_advice(int show_hint, struct replay_opts *opts)
 159{
 160        char *msg = getenv("GIT_CHERRY_PICK_HELP");
 161
 162        if (msg) {
 163                fprintf(stderr, "%s\n", msg);
 164                /*
 165                 * A conflict has occurred but the porcelain
 166                 * (typically rebase --interactive) wants to take care
 167                 * of the commit itself so remove CHERRY_PICK_HEAD
 168                 */
 169                unlink(git_path_cherry_pick_head());
 170                return;
 171        }
 172
 173        if (show_hint) {
 174                if (opts->no_commit)
 175                        advise(_("after resolving the conflicts, mark the corrected paths\n"
 176                                 "with 'git add <paths>' or 'git rm <paths>'"));
 177                else
 178                        advise(_("after resolving the conflicts, mark the corrected paths\n"
 179                                 "with 'git add <paths>' or 'git rm <paths>'\n"
 180                                 "and commit the result with 'git commit'"));
 181        }
 182}
 183
 184static int write_message(struct strbuf *msgbuf, const char *filename)
 185{
 186        static struct lock_file msg_file;
 187
 188        int msg_fd = hold_lock_file_for_update(&msg_file, filename, 0);
 189        if (msg_fd < 0)
 190                return error_errno(_("Could not lock '%s'"), filename);
 191        if (write_in_full(msg_fd, msgbuf->buf, msgbuf->len) < 0)
 192                return error_errno(_("Could not write to %s"), filename);
 193        strbuf_release(msgbuf);
 194        if (commit_lock_file(&msg_file) < 0)
 195                return error(_("Error wrapping up %s."), filename);
 196
 197        return 0;
 198}
 199
 200static struct tree *empty_tree(void)
 201{
 202        return lookup_tree(EMPTY_TREE_SHA1_BIN);
 203}
 204
 205static int error_dirty_index(struct replay_opts *opts)
 206{
 207        if (read_cache_unmerged())
 208                return error_resolve_conflict(action_name(opts));
 209
 210        /* Different translation strings for cherry-pick and revert */
 211        if (opts->action == REPLAY_PICK)
 212                error(_("Your local changes would be overwritten by cherry-pick."));
 213        else
 214                error(_("Your local changes would be overwritten by revert."));
 215
 216        if (advice_commit_before_merge)
 217                advise(_("Commit your changes or stash them to proceed."));
 218        return -1;
 219}
 220
 221static int fast_forward_to(const unsigned char *to, const unsigned char *from,
 222                        int unborn, struct replay_opts *opts)
 223{
 224        struct ref_transaction *transaction;
 225        struct strbuf sb = STRBUF_INIT;
 226        struct strbuf err = STRBUF_INIT;
 227
 228        read_cache();
 229        if (checkout_fast_forward(from, to, 1))
 230                return -1; /* the callee should have complained already */
 231
 232        strbuf_addf(&sb, _("%s: fast-forward"), action_name(opts));
 233
 234        transaction = ref_transaction_begin(&err);
 235        if (!transaction ||
 236            ref_transaction_update(transaction, "HEAD",
 237                                   to, unborn ? null_sha1 : from,
 238                                   0, sb.buf, &err) ||
 239            ref_transaction_commit(transaction, &err)) {
 240                ref_transaction_free(transaction);
 241                error("%s", err.buf);
 242                strbuf_release(&sb);
 243                strbuf_release(&err);
 244                return -1;
 245        }
 246
 247        strbuf_release(&sb);
 248        strbuf_release(&err);
 249        ref_transaction_free(transaction);
 250        return 0;
 251}
 252
 253void append_conflicts_hint(struct strbuf *msgbuf)
 254{
 255        int i;
 256
 257        strbuf_addch(msgbuf, '\n');
 258        strbuf_commented_addf(msgbuf, "Conflicts:\n");
 259        for (i = 0; i < active_nr;) {
 260                const struct cache_entry *ce = active_cache[i++];
 261                if (ce_stage(ce)) {
 262                        strbuf_commented_addf(msgbuf, "\t%s\n", ce->name);
 263                        while (i < active_nr && !strcmp(ce->name,
 264                                                        active_cache[i]->name))
 265                                i++;
 266                }
 267        }
 268}
 269
 270static int do_recursive_merge(struct commit *base, struct commit *next,
 271                              const char *base_label, const char *next_label,
 272                              unsigned char *head, struct strbuf *msgbuf,
 273                              struct replay_opts *opts)
 274{
 275        struct merge_options o;
 276        struct tree *result, *next_tree, *base_tree, *head_tree;
 277        int clean;
 278        const char **xopt;
 279        static struct lock_file index_lock;
 280
 281        hold_locked_index(&index_lock, 1);
 282
 283        read_cache();
 284
 285        init_merge_options(&o);
 286        o.ancestor = base ? base_label : "(empty tree)";
 287        o.branch1 = "HEAD";
 288        o.branch2 = next ? next_label : "(empty tree)";
 289
 290        head_tree = parse_tree_indirect(head);
 291        next_tree = next ? next->tree : empty_tree();
 292        base_tree = base ? base->tree : empty_tree();
 293
 294        for (xopt = opts->xopts; xopt != opts->xopts + opts->xopts_nr; xopt++)
 295                parse_merge_opt(&o, *xopt);
 296
 297        clean = merge_trees(&o,
 298                            head_tree,
 299                            next_tree, base_tree, &result);
 300        strbuf_release(&o.obuf);
 301        if (clean < 0)
 302                return clean;
 303
 304        if (active_cache_changed &&
 305            write_locked_index(&the_index, &index_lock, COMMIT_LOCK))
 306                /* TRANSLATORS: %s will be "revert" or "cherry-pick" */
 307                return error(_("%s: Unable to write new index file"),
 308                        action_name(opts));
 309        rollback_lock_file(&index_lock);
 310
 311        if (opts->signoff)
 312                append_signoff(msgbuf, 0, 0);
 313
 314        if (!clean)
 315                append_conflicts_hint(msgbuf);
 316
 317        return !clean;
 318}
 319
 320static int is_index_unchanged(void)
 321{
 322        unsigned char head_sha1[20];
 323        struct commit *head_commit;
 324
 325        if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, head_sha1, NULL))
 326                return error(_("Could not resolve HEAD commit\n"));
 327
 328        head_commit = lookup_commit(head_sha1);
 329
 330        /*
 331         * If head_commit is NULL, check_commit, called from
 332         * lookup_commit, would have indicated that head_commit is not
 333         * a commit object already.  parse_commit() will return failure
 334         * without further complaints in such a case.  Otherwise, if
 335         * the commit is invalid, parse_commit() will complain.  So
 336         * there is nothing for us to say here.  Just return failure.
 337         */
 338        if (parse_commit(head_commit))
 339                return -1;
 340
 341        if (!active_cache_tree)
 342                active_cache_tree = cache_tree();
 343
 344        if (!cache_tree_fully_valid(active_cache_tree))
 345                if (cache_tree_update(&the_index, 0))
 346                        return error(_("Unable to update cache tree\n"));
 347
 348        return !hashcmp(active_cache_tree->sha1, head_commit->tree->object.oid.hash);
 349}
 350
 351/*
 352 * If we are cherry-pick, and if the merge did not result in
 353 * hand-editing, we will hit this commit and inherit the original
 354 * author date and name.
 355 * If we are revert, or if our cherry-pick results in a hand merge,
 356 * we had better say that the current user is responsible for that.
 357 */
 358static int run_git_commit(const char *defmsg, struct replay_opts *opts,
 359                          int allow_empty)
 360{
 361        struct argv_array array;
 362        int rc;
 363        const char *value;
 364
 365        argv_array_init(&array);
 366        argv_array_push(&array, "commit");
 367        argv_array_push(&array, "-n");
 368
 369        if (opts->gpg_sign)
 370                argv_array_pushf(&array, "-S%s", opts->gpg_sign);
 371        if (opts->signoff)
 372                argv_array_push(&array, "-s");
 373        if (!opts->edit) {
 374                argv_array_push(&array, "-F");
 375                argv_array_push(&array, defmsg);
 376                if (!opts->signoff &&
 377                    !opts->record_origin &&
 378                    git_config_get_value("commit.cleanup", &value))
 379                        argv_array_push(&array, "--cleanup=verbatim");
 380        }
 381
 382        if (allow_empty)
 383                argv_array_push(&array, "--allow-empty");
 384
 385        if (opts->allow_empty_message)
 386                argv_array_push(&array, "--allow-empty-message");
 387
 388        rc = run_command_v_opt(array.argv, RUN_GIT_CMD);
 389        argv_array_clear(&array);
 390        return rc;
 391}
 392
 393static int is_original_commit_empty(struct commit *commit)
 394{
 395        const unsigned char *ptree_sha1;
 396
 397        if (parse_commit(commit))
 398                return error(_("Could not parse commit %s\n"),
 399                             oid_to_hex(&commit->object.oid));
 400        if (commit->parents) {
 401                struct commit *parent = commit->parents->item;
 402                if (parse_commit(parent))
 403                        return error(_("Could not parse parent commit %s\n"),
 404                                oid_to_hex(&parent->object.oid));
 405                ptree_sha1 = parent->tree->object.oid.hash;
 406        } else {
 407                ptree_sha1 = EMPTY_TREE_SHA1_BIN; /* commit is root */
 408        }
 409
 410        return !hashcmp(ptree_sha1, commit->tree->object.oid.hash);
 411}
 412
 413/*
 414 * Do we run "git commit" with "--allow-empty"?
 415 */
 416static int allow_empty(struct replay_opts *opts, struct commit *commit)
 417{
 418        int index_unchanged, empty_commit;
 419
 420        /*
 421         * Three cases:
 422         *
 423         * (1) we do not allow empty at all and error out.
 424         *
 425         * (2) we allow ones that were initially empty, but
 426         * forbid the ones that become empty;
 427         *
 428         * (3) we allow both.
 429         */
 430        if (!opts->allow_empty)
 431                return 0; /* let "git commit" barf as necessary */
 432
 433        index_unchanged = is_index_unchanged();
 434        if (index_unchanged < 0)
 435                return index_unchanged;
 436        if (!index_unchanged)
 437                return 0; /* we do not have to say --allow-empty */
 438
 439        if (opts->keep_redundant_commits)
 440                return 1;
 441
 442        empty_commit = is_original_commit_empty(commit);
 443        if (empty_commit < 0)
 444                return empty_commit;
 445        if (!empty_commit)
 446                return 0;
 447        else
 448                return 1;
 449}
 450
 451static int do_pick_commit(struct commit *commit, struct replay_opts *opts)
 452{
 453        unsigned char head[20];
 454        struct commit *base, *next, *parent;
 455        const char *base_label, *next_label;
 456        struct commit_message msg = { NULL, NULL, NULL, NULL };
 457        struct strbuf msgbuf = STRBUF_INIT;
 458        int res, unborn = 0, allow;
 459
 460        if (opts->no_commit) {
 461                /*
 462                 * We do not intend to commit immediately.  We just want to
 463                 * merge the differences in, so let's compute the tree
 464                 * that represents the "current" state for merge-recursive
 465                 * to work on.
 466                 */
 467                if (write_cache_as_tree(head, 0, NULL))
 468                        return error(_("Your index file is unmerged."));
 469        } else {
 470                unborn = get_sha1("HEAD", head);
 471                if (unborn)
 472                        hashcpy(head, EMPTY_TREE_SHA1_BIN);
 473                if (index_differs_from(unborn ? EMPTY_TREE_SHA1_HEX : "HEAD", 0))
 474                        return error_dirty_index(opts);
 475        }
 476        discard_cache();
 477
 478        if (!commit->parents) {
 479                parent = NULL;
 480        }
 481        else if (commit->parents->next) {
 482                /* Reverting or cherry-picking a merge commit */
 483                int cnt;
 484                struct commit_list *p;
 485
 486                if (!opts->mainline)
 487                        return error(_("Commit %s is a merge but no -m option was given."),
 488                                oid_to_hex(&commit->object.oid));
 489
 490                for (cnt = 1, p = commit->parents;
 491                     cnt != opts->mainline && p;
 492                     cnt++)
 493                        p = p->next;
 494                if (cnt != opts->mainline || !p)
 495                        return error(_("Commit %s does not have parent %d"),
 496                                oid_to_hex(&commit->object.oid), opts->mainline);
 497                parent = p->item;
 498        } else if (0 < opts->mainline)
 499                return error(_("Mainline was specified but commit %s is not a merge."),
 500                        oid_to_hex(&commit->object.oid));
 501        else
 502                parent = commit->parents->item;
 503
 504        if (opts->allow_ff &&
 505            ((parent && !hashcmp(parent->object.oid.hash, head)) ||
 506             (!parent && unborn)))
 507                return fast_forward_to(commit->object.oid.hash, head, unborn, opts);
 508
 509        if (parent && parse_commit(parent) < 0)
 510                /* TRANSLATORS: The first %s will be "revert" or
 511                   "cherry-pick", the second %s a SHA1 */
 512                return error(_("%s: cannot parse parent commit %s"),
 513                        action_name(opts), oid_to_hex(&parent->object.oid));
 514
 515        if (get_message(commit, &msg) != 0)
 516                return error(_("Cannot get commit message for %s"),
 517                        oid_to_hex(&commit->object.oid));
 518
 519        /*
 520         * "commit" is an existing commit.  We would want to apply
 521         * the difference it introduces since its first parent "prev"
 522         * on top of the current HEAD if we are cherry-pick.  Or the
 523         * reverse of it if we are revert.
 524         */
 525
 526        if (opts->action == REPLAY_REVERT) {
 527                base = commit;
 528                base_label = msg.label;
 529                next = parent;
 530                next_label = msg.parent_label;
 531                strbuf_addstr(&msgbuf, "Revert \"");
 532                strbuf_addstr(&msgbuf, msg.subject);
 533                strbuf_addstr(&msgbuf, "\"\n\nThis reverts commit ");
 534                strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
 535
 536                if (commit->parents && commit->parents->next) {
 537                        strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
 538                        strbuf_addstr(&msgbuf, oid_to_hex(&parent->object.oid));
 539                }
 540                strbuf_addstr(&msgbuf, ".\n");
 541        } else {
 542                const char *p;
 543
 544                base = parent;
 545                base_label = msg.parent_label;
 546                next = commit;
 547                next_label = msg.label;
 548
 549                /*
 550                 * Append the commit log message to msgbuf; it starts
 551                 * after the tree, parent, author, committer
 552                 * information followed by "\n\n".
 553                 */
 554                p = strstr(msg.message, "\n\n");
 555                if (p)
 556                        strbuf_addstr(&msgbuf, skip_blank_lines(p + 2));
 557
 558                if (opts->record_origin) {
 559                        if (!has_conforming_footer(&msgbuf, NULL, 0))
 560                                strbuf_addch(&msgbuf, '\n');
 561                        strbuf_addstr(&msgbuf, cherry_picked_prefix);
 562                        strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
 563                        strbuf_addstr(&msgbuf, ")\n");
 564                }
 565        }
 566
 567        if (!opts->strategy || !strcmp(opts->strategy, "recursive") || opts->action == REPLAY_REVERT) {
 568                res = do_recursive_merge(base, next, base_label, next_label,
 569                                         head, &msgbuf, opts);
 570                if (res < 0)
 571                        return res;
 572                res |= write_message(&msgbuf, git_path_merge_msg());
 573        } else {
 574                struct commit_list *common = NULL;
 575                struct commit_list *remotes = NULL;
 576
 577                res = write_message(&msgbuf, git_path_merge_msg());
 578
 579                commit_list_insert(base, &common);
 580                commit_list_insert(next, &remotes);
 581                res |= try_merge_command(opts->strategy, opts->xopts_nr, opts->xopts,
 582                                        common, sha1_to_hex(head), remotes);
 583                free_commit_list(common);
 584                free_commit_list(remotes);
 585        }
 586
 587        /*
 588         * If the merge was clean or if it failed due to conflict, we write
 589         * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
 590         * However, if the merge did not even start, then we don't want to
 591         * write it at all.
 592         */
 593        if (opts->action == REPLAY_PICK && !opts->no_commit && (res == 0 || res == 1) &&
 594            update_ref(NULL, "CHERRY_PICK_HEAD", commit->object.oid.hash, NULL,
 595                       REF_NODEREF, UPDATE_REFS_MSG_ON_ERR))
 596                res = -1;
 597        if (opts->action == REPLAY_REVERT && ((opts->no_commit && res == 0) || res == 1) &&
 598            update_ref(NULL, "REVERT_HEAD", commit->object.oid.hash, NULL,
 599                       REF_NODEREF, UPDATE_REFS_MSG_ON_ERR))
 600                res = -1;
 601
 602        if (res) {
 603                error(opts->action == REPLAY_REVERT
 604                      ? _("could not revert %s... %s")
 605                      : _("could not apply %s... %s"),
 606                      find_unique_abbrev(commit->object.oid.hash, DEFAULT_ABBREV),
 607                      msg.subject);
 608                print_advice(res == 1, opts);
 609                rerere(opts->allow_rerere_auto);
 610                goto leave;
 611        }
 612
 613        allow = allow_empty(opts, commit);
 614        if (allow < 0) {
 615                res = allow;
 616                goto leave;
 617        }
 618        if (!opts->no_commit)
 619                res = run_git_commit(git_path_merge_msg(), opts, allow);
 620
 621leave:
 622        free_message(commit, &msg);
 623
 624        return res;
 625}
 626
 627static int prepare_revs(struct replay_opts *opts)
 628{
 629        /*
 630         * picking (but not reverting) ranges (but not individual revisions)
 631         * should be done in reverse
 632         */
 633        if (opts->action == REPLAY_PICK && !opts->revs->no_walk)
 634                opts->revs->reverse ^= 1;
 635
 636        if (prepare_revision_walk(opts->revs))
 637                return error(_("revision walk setup failed"));
 638
 639        if (!opts->revs->commits)
 640                return error(_("empty commit set passed"));
 641        return 0;
 642}
 643
 644static int read_and_refresh_cache(struct replay_opts *opts)
 645{
 646        static struct lock_file index_lock;
 647        int index_fd = hold_locked_index(&index_lock, 0);
 648        if (read_index_preload(&the_index, NULL) < 0) {
 649                rollback_lock_file(&index_lock);
 650                return error(_("git %s: failed to read the index"),
 651                        action_name(opts));
 652        }
 653        refresh_index(&the_index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
 654        if (the_index.cache_changed && index_fd >= 0) {
 655                if (write_locked_index(&the_index, &index_lock, COMMIT_LOCK)) {
 656                        rollback_lock_file(&index_lock);
 657                        return error(_("git %s: failed to refresh the index"),
 658                                action_name(opts));
 659                }
 660        }
 661        rollback_lock_file(&index_lock);
 662        return 0;
 663}
 664
 665static int format_todo(struct strbuf *buf, struct commit_list *todo_list,
 666                struct replay_opts *opts)
 667{
 668        struct commit_list *cur = NULL;
 669        const char *sha1_abbrev = NULL;
 670        const char *action_str = opts->action == REPLAY_REVERT ? "revert" : "pick";
 671        const char *subject;
 672        int subject_len;
 673
 674        for (cur = todo_list; cur; cur = cur->next) {
 675                const char *commit_buffer = get_commit_buffer(cur->item, NULL);
 676                sha1_abbrev = find_unique_abbrev(cur->item->object.oid.hash, DEFAULT_ABBREV);
 677                subject_len = find_commit_subject(commit_buffer, &subject);
 678                strbuf_addf(buf, "%s %s %.*s\n", action_str, sha1_abbrev,
 679                        subject_len, subject);
 680                unuse_commit_buffer(cur->item, commit_buffer);
 681        }
 682        return 0;
 683}
 684
 685static struct commit *parse_insn_line(char *bol, char *eol, struct replay_opts *opts)
 686{
 687        unsigned char commit_sha1[20];
 688        enum replay_action action;
 689        char *end_of_object_name;
 690        int saved, status, padding;
 691
 692        if (starts_with(bol, "pick")) {
 693                action = REPLAY_PICK;
 694                bol += strlen("pick");
 695        } else if (starts_with(bol, "revert")) {
 696                action = REPLAY_REVERT;
 697                bol += strlen("revert");
 698        } else
 699                return NULL;
 700
 701        /* Eat up extra spaces/ tabs before object name */
 702        padding = strspn(bol, " \t");
 703        if (!padding)
 704                return NULL;
 705        bol += padding;
 706
 707        end_of_object_name = bol + strcspn(bol, " \t\n");
 708        saved = *end_of_object_name;
 709        *end_of_object_name = '\0';
 710        status = get_sha1(bol, commit_sha1);
 711        *end_of_object_name = saved;
 712
 713        /*
 714         * Verify that the action matches up with the one in
 715         * opts; we don't support arbitrary instructions
 716         */
 717        if (action != opts->action) {
 718                if (action == REPLAY_REVERT)
 719                      error((opts->action == REPLAY_REVERT)
 720                            ? _("Cannot revert during another revert.")
 721                            : _("Cannot revert during a cherry-pick."));
 722                else
 723                      error((opts->action == REPLAY_REVERT)
 724                            ? _("Cannot cherry-pick during a revert.")
 725                            : _("Cannot cherry-pick during another cherry-pick."));
 726                return NULL;
 727        }
 728
 729        if (status < 0)
 730                return NULL;
 731
 732        return lookup_commit_reference(commit_sha1);
 733}
 734
 735static int parse_insn_buffer(char *buf, struct commit_list **todo_list,
 736                        struct replay_opts *opts)
 737{
 738        struct commit_list **next = todo_list;
 739        struct commit *commit;
 740        char *p = buf;
 741        int i;
 742
 743        for (i = 1; *p; i++) {
 744                char *eol = strchrnul(p, '\n');
 745                commit = parse_insn_line(p, eol, opts);
 746                if (!commit)
 747                        return error(_("Could not parse line %d."), i);
 748                next = commit_list_append(commit, next);
 749                p = *eol ? eol + 1 : eol;
 750        }
 751        if (!*todo_list)
 752                return error(_("No commits parsed."));
 753        return 0;
 754}
 755
 756static int read_populate_todo(struct commit_list **todo_list,
 757                        struct replay_opts *opts)
 758{
 759        struct strbuf buf = STRBUF_INIT;
 760        int fd, res;
 761
 762        fd = open(git_path_todo_file(), O_RDONLY);
 763        if (fd < 0)
 764                return error_errno(_("Could not open %s"),
 765                                   git_path_todo_file());
 766        if (strbuf_read(&buf, fd, 0) < 0) {
 767                close(fd);
 768                strbuf_release(&buf);
 769                return error(_("Could not read %s."), git_path_todo_file());
 770        }
 771        close(fd);
 772
 773        res = parse_insn_buffer(buf.buf, todo_list, opts);
 774        strbuf_release(&buf);
 775        if (res)
 776                return error(_("Unusable instruction sheet: %s"),
 777                        git_path_todo_file());
 778        return 0;
 779}
 780
 781static int populate_opts_cb(const char *key, const char *value, void *data)
 782{
 783        struct replay_opts *opts = data;
 784        int error_flag = 1;
 785
 786        if (!value)
 787                error_flag = 0;
 788        else if (!strcmp(key, "options.no-commit"))
 789                opts->no_commit = git_config_bool_or_int(key, value, &error_flag);
 790        else if (!strcmp(key, "options.edit"))
 791                opts->edit = git_config_bool_or_int(key, value, &error_flag);
 792        else if (!strcmp(key, "options.signoff"))
 793                opts->signoff = git_config_bool_or_int(key, value, &error_flag);
 794        else if (!strcmp(key, "options.record-origin"))
 795                opts->record_origin = git_config_bool_or_int(key, value, &error_flag);
 796        else if (!strcmp(key, "options.allow-ff"))
 797                opts->allow_ff = git_config_bool_or_int(key, value, &error_flag);
 798        else if (!strcmp(key, "options.mainline"))
 799                opts->mainline = git_config_int(key, value);
 800        else if (!strcmp(key, "options.strategy"))
 801                git_config_string(&opts->strategy, key, value);
 802        else if (!strcmp(key, "options.gpg-sign"))
 803                git_config_string(&opts->gpg_sign, key, value);
 804        else if (!strcmp(key, "options.strategy-option")) {
 805                ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
 806                opts->xopts[opts->xopts_nr++] = xstrdup(value);
 807        } else
 808                return error(_("Invalid key: %s"), key);
 809
 810        if (!error_flag)
 811                return error(_("Invalid value for %s: %s"), key, value);
 812
 813        return 0;
 814}
 815
 816static int read_populate_opts(struct replay_opts *opts)
 817{
 818        if (!file_exists(git_path_opts_file()))
 819                return 0;
 820        /*
 821         * The function git_parse_source(), called from git_config_from_file(),
 822         * may die() in case of a syntactically incorrect file. We do not care
 823         * about this case, though, because we wrote that file ourselves, so we
 824         * are pretty certain that it is syntactically correct.
 825         */
 826        if (git_config_from_file(populate_opts_cb, git_path_opts_file(), opts) < 0)
 827                return error(_("Malformed options sheet: %s"),
 828                        git_path_opts_file());
 829        return 0;
 830}
 831
 832static int walk_revs_populate_todo(struct commit_list **todo_list,
 833                                struct replay_opts *opts)
 834{
 835        struct commit *commit;
 836        struct commit_list **next;
 837
 838        if (prepare_revs(opts))
 839                return -1;
 840
 841        next = todo_list;
 842        while ((commit = get_revision(opts->revs)))
 843                next = commit_list_append(commit, next);
 844        return 0;
 845}
 846
 847static int create_seq_dir(void)
 848{
 849        if (file_exists(git_path_seq_dir())) {
 850                error(_("a cherry-pick or revert is already in progress"));
 851                advise(_("try \"git cherry-pick (--continue | --quit | --abort)\""));
 852                return -1;
 853        }
 854        else if (mkdir(git_path_seq_dir(), 0777) < 0)
 855                return error_errno(_("Could not create sequencer directory %s"),
 856                                   git_path_seq_dir());
 857        return 0;
 858}
 859
 860static int save_head(const char *head)
 861{
 862        static struct lock_file head_lock;
 863        struct strbuf buf = STRBUF_INIT;
 864        int fd;
 865
 866        fd = hold_lock_file_for_update(&head_lock, git_path_head_file(), 0);
 867        if (fd < 0) {
 868                rollback_lock_file(&head_lock);
 869                return error_errno(_("Could not lock HEAD"));
 870        }
 871        strbuf_addf(&buf, "%s\n", head);
 872        if (write_in_full(fd, buf.buf, buf.len) < 0) {
 873                rollback_lock_file(&head_lock);
 874                return error_errno(_("Could not write to %s"),
 875                                   git_path_head_file());
 876        }
 877        if (commit_lock_file(&head_lock) < 0) {
 878                rollback_lock_file(&head_lock);
 879                return error(_("Error wrapping up %s."), git_path_head_file());
 880        }
 881        return 0;
 882}
 883
 884static int reset_for_rollback(const unsigned char *sha1)
 885{
 886        const char *argv[4];    /* reset --merge <arg> + NULL */
 887        argv[0] = "reset";
 888        argv[1] = "--merge";
 889        argv[2] = sha1_to_hex(sha1);
 890        argv[3] = NULL;
 891        return run_command_v_opt(argv, RUN_GIT_CMD);
 892}
 893
 894static int rollback_single_pick(void)
 895{
 896        unsigned char head_sha1[20];
 897
 898        if (!file_exists(git_path_cherry_pick_head()) &&
 899            !file_exists(git_path_revert_head()))
 900                return error(_("no cherry-pick or revert in progress"));
 901        if (read_ref_full("HEAD", 0, head_sha1, NULL))
 902                return error(_("cannot resolve HEAD"));
 903        if (is_null_sha1(head_sha1))
 904                return error(_("cannot abort from a branch yet to be born"));
 905        return reset_for_rollback(head_sha1);
 906}
 907
 908static int sequencer_rollback(struct replay_opts *opts)
 909{
 910        FILE *f;
 911        unsigned char sha1[20];
 912        struct strbuf buf = STRBUF_INIT;
 913
 914        f = fopen(git_path_head_file(), "r");
 915        if (!f && errno == ENOENT) {
 916                /*
 917                 * There is no multiple-cherry-pick in progress.
 918                 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
 919                 * a single-cherry-pick in progress, abort that.
 920                 */
 921                return rollback_single_pick();
 922        }
 923        if (!f)
 924                return error_errno(_("cannot open %s"), git_path_head_file());
 925        if (strbuf_getline_lf(&buf, f)) {
 926                error(_("cannot read %s: %s"), git_path_head_file(),
 927                      ferror(f) ?  strerror(errno) : _("unexpected end of file"));
 928                fclose(f);
 929                goto fail;
 930        }
 931        fclose(f);
 932        if (get_sha1_hex(buf.buf, sha1) || buf.buf[40] != '\0') {
 933                error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
 934                        git_path_head_file());
 935                goto fail;
 936        }
 937        if (is_null_sha1(sha1)) {
 938                error(_("cannot abort from a branch yet to be born"));
 939                goto fail;
 940        }
 941        if (reset_for_rollback(sha1))
 942                goto fail;
 943        remove_sequencer_state();
 944        strbuf_release(&buf);
 945        return 0;
 946fail:
 947        strbuf_release(&buf);
 948        return -1;
 949}
 950
 951static int save_todo(struct commit_list *todo_list, struct replay_opts *opts)
 952{
 953        static struct lock_file todo_lock;
 954        struct strbuf buf = STRBUF_INIT;
 955        int fd;
 956
 957        fd = hold_lock_file_for_update(&todo_lock, git_path_todo_file(), 0);
 958        if (fd < 0)
 959                return error_errno(_("Could not lock '%s'"),
 960                                   git_path_todo_file());
 961        if (format_todo(&buf, todo_list, opts) < 0) {
 962                strbuf_release(&buf);
 963                return error(_("Could not format %s."), git_path_todo_file());
 964        }
 965        if (write_in_full(fd, buf.buf, buf.len) < 0) {
 966                strbuf_release(&buf);
 967                return error_errno(_("Could not write to %s"),
 968                                   git_path_todo_file());
 969        }
 970        if (commit_lock_file(&todo_lock) < 0) {
 971                strbuf_release(&buf);
 972                return error(_("Error wrapping up %s."), git_path_todo_file());
 973        }
 974        strbuf_release(&buf);
 975        return 0;
 976}
 977
 978static int save_opts(struct replay_opts *opts)
 979{
 980        const char *opts_file = git_path_opts_file();
 981        int res = 0;
 982
 983        if (opts->no_commit)
 984                res |= git_config_set_in_file_gently(opts_file, "options.no-commit", "true");
 985        if (opts->edit)
 986                res |= git_config_set_in_file_gently(opts_file, "options.edit", "true");
 987        if (opts->signoff)
 988                res |= git_config_set_in_file_gently(opts_file, "options.signoff", "true");
 989        if (opts->record_origin)
 990                res |= git_config_set_in_file_gently(opts_file, "options.record-origin", "true");
 991        if (opts->allow_ff)
 992                res |= git_config_set_in_file_gently(opts_file, "options.allow-ff", "true");
 993        if (opts->mainline) {
 994                struct strbuf buf = STRBUF_INIT;
 995                strbuf_addf(&buf, "%d", opts->mainline);
 996                res |= git_config_set_in_file_gently(opts_file, "options.mainline", buf.buf);
 997                strbuf_release(&buf);
 998        }
 999        if (opts->strategy)
1000                res |= git_config_set_in_file_gently(opts_file, "options.strategy", opts->strategy);
1001        if (opts->gpg_sign)
1002                res |= git_config_set_in_file_gently(opts_file, "options.gpg-sign", opts->gpg_sign);
1003        if (opts->xopts) {
1004                int i;
1005                for (i = 0; i < opts->xopts_nr; i++)
1006                        res |= git_config_set_multivar_in_file_gently(opts_file,
1007                                                        "options.strategy-option",
1008                                                        opts->xopts[i], "^$", 0);
1009        }
1010        return res;
1011}
1012
1013static int pick_commits(struct commit_list *todo_list, struct replay_opts *opts)
1014{
1015        struct commit_list *cur;
1016        int res;
1017
1018        setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
1019        if (opts->allow_ff)
1020                assert(!(opts->signoff || opts->no_commit ||
1021                                opts->record_origin || opts->edit));
1022        if (read_and_refresh_cache(opts))
1023                return -1;
1024
1025        for (cur = todo_list; cur; cur = cur->next) {
1026                if (save_todo(cur, opts))
1027                        return -1;
1028                res = do_pick_commit(cur->item, opts);
1029                if (res)
1030                        return res;
1031        }
1032
1033        /*
1034         * Sequence of picks finished successfully; cleanup by
1035         * removing the .git/sequencer directory
1036         */
1037        remove_sequencer_state();
1038        return 0;
1039}
1040
1041static int continue_single_pick(void)
1042{
1043        const char *argv[] = { "commit", NULL };
1044
1045        if (!file_exists(git_path_cherry_pick_head()) &&
1046            !file_exists(git_path_revert_head()))
1047                return error(_("no cherry-pick or revert in progress"));
1048        return run_command_v_opt(argv, RUN_GIT_CMD);
1049}
1050
1051static int sequencer_continue(struct replay_opts *opts)
1052{
1053        struct commit_list *todo_list = NULL;
1054
1055        if (!file_exists(git_path_todo_file()))
1056                return continue_single_pick();
1057        if (read_populate_opts(opts) ||
1058                        read_populate_todo(&todo_list, opts))
1059                return -1;
1060
1061        /* Verify that the conflict has been resolved */
1062        if (file_exists(git_path_cherry_pick_head()) ||
1063            file_exists(git_path_revert_head())) {
1064                int ret = continue_single_pick();
1065                if (ret)
1066                        return ret;
1067        }
1068        if (index_differs_from("HEAD", 0))
1069                return error_dirty_index(opts);
1070        todo_list = todo_list->next;
1071        return pick_commits(todo_list, opts);
1072}
1073
1074static int single_pick(struct commit *cmit, struct replay_opts *opts)
1075{
1076        setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
1077        return do_pick_commit(cmit, opts);
1078}
1079
1080int sequencer_pick_revisions(struct replay_opts *opts)
1081{
1082        struct commit_list *todo_list = NULL;
1083        unsigned char sha1[20];
1084        int i;
1085
1086        if (opts->subcommand == REPLAY_NONE)
1087                assert(opts->revs);
1088
1089        if (read_and_refresh_cache(opts))
1090                return -1;
1091
1092        /*
1093         * Decide what to do depending on the arguments; a fresh
1094         * cherry-pick should be handled differently from an existing
1095         * one that is being continued
1096         */
1097        if (opts->subcommand == REPLAY_REMOVE_STATE) {
1098                remove_sequencer_state();
1099                return 0;
1100        }
1101        if (opts->subcommand == REPLAY_ROLLBACK)
1102                return sequencer_rollback(opts);
1103        if (opts->subcommand == REPLAY_CONTINUE)
1104                return sequencer_continue(opts);
1105
1106        for (i = 0; i < opts->revs->pending.nr; i++) {
1107                unsigned char sha1[20];
1108                const char *name = opts->revs->pending.objects[i].name;
1109
1110                /* This happens when using --stdin. */
1111                if (!strlen(name))
1112                        continue;
1113
1114                if (!get_sha1(name, sha1)) {
1115                        if (!lookup_commit_reference_gently(sha1, 1)) {
1116                                enum object_type type = sha1_object_info(sha1, NULL);
1117                                return error(_("%s: can't cherry-pick a %s"),
1118                                        name, typename(type));
1119                        }
1120                } else
1121                        return error(_("%s: bad revision"), name);
1122        }
1123
1124        /*
1125         * If we were called as "git cherry-pick <commit>", just
1126         * cherry-pick/revert it, set CHERRY_PICK_HEAD /
1127         * REVERT_HEAD, and don't touch the sequencer state.
1128         * This means it is possible to cherry-pick in the middle
1129         * of a cherry-pick sequence.
1130         */
1131        if (opts->revs->cmdline.nr == 1 &&
1132            opts->revs->cmdline.rev->whence == REV_CMD_REV &&
1133            opts->revs->no_walk &&
1134            !opts->revs->cmdline.rev->flags) {
1135                struct commit *cmit;
1136                if (prepare_revision_walk(opts->revs))
1137                        return error(_("revision walk setup failed"));
1138                cmit = get_revision(opts->revs);
1139                if (!cmit || get_revision(opts->revs))
1140                        return error("BUG: expected exactly one commit from walk");
1141                return single_pick(cmit, opts);
1142        }
1143
1144        /*
1145         * Start a new cherry-pick/ revert sequence; but
1146         * first, make sure that an existing one isn't in
1147         * progress
1148         */
1149
1150        if (walk_revs_populate_todo(&todo_list, opts) ||
1151                        create_seq_dir() < 0)
1152                return -1;
1153        if (get_sha1("HEAD", sha1) && (opts->action == REPLAY_REVERT))
1154                return error(_("Can't revert as initial commit"));
1155        if (save_head(sha1_to_hex(sha1)))
1156                return -1;
1157        if (save_opts(opts))
1158                return -1;
1159        return pick_commits(todo_list, opts);
1160}
1161
1162void append_signoff(struct strbuf *msgbuf, int ignore_footer, unsigned flag)
1163{
1164        unsigned no_dup_sob = flag & APPEND_SIGNOFF_DEDUP;
1165        struct strbuf sob = STRBUF_INIT;
1166        int has_footer;
1167
1168        strbuf_addstr(&sob, sign_off_header);
1169        strbuf_addstr(&sob, fmt_name(getenv("GIT_COMMITTER_NAME"),
1170                                getenv("GIT_COMMITTER_EMAIL")));
1171        strbuf_addch(&sob, '\n');
1172
1173        /*
1174         * If the whole message buffer is equal to the sob, pretend that we
1175         * found a conforming footer with a matching sob
1176         */
1177        if (msgbuf->len - ignore_footer == sob.len &&
1178            !strncmp(msgbuf->buf, sob.buf, sob.len))
1179                has_footer = 3;
1180        else
1181                has_footer = has_conforming_footer(msgbuf, &sob, ignore_footer);
1182
1183        if (!has_footer) {
1184                const char *append_newlines = NULL;
1185                size_t len = msgbuf->len - ignore_footer;
1186
1187                if (!len) {
1188                        /*
1189                         * The buffer is completely empty.  Leave foom for
1190                         * the title and body to be filled in by the user.
1191                         */
1192                        append_newlines = "\n\n";
1193                } else if (msgbuf->buf[len - 1] != '\n') {
1194                        /*
1195                         * Incomplete line.  Complete the line and add a
1196                         * blank one so that there is an empty line between
1197                         * the message body and the sob.
1198                         */
1199                        append_newlines = "\n\n";
1200                } else if (len == 1) {
1201                        /*
1202                         * Buffer contains a single newline.  Add another
1203                         * so that we leave room for the title and body.
1204                         */
1205                        append_newlines = "\n";
1206                } else if (msgbuf->buf[len - 2] != '\n') {
1207                        /*
1208                         * Buffer ends with a single newline.  Add another
1209                         * so that there is an empty line between the message
1210                         * body and the sob.
1211                         */
1212                        append_newlines = "\n";
1213                } /* else, the buffer already ends with two newlines. */
1214
1215                if (append_newlines)
1216                        strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
1217                                append_newlines, strlen(append_newlines));
1218        }
1219
1220        if (has_footer != 3 && (!no_dup_sob || has_footer != 2))
1221                strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
1222                                sob.buf, sob.len);
1223
1224        strbuf_release(&sob);
1225}