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