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