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