sequencer.con commit fast-import doc: cat-blob and ls responses need to be consumed quickly (d57e490)
   1#include "cache.h"
   2#include "sequencer.h"
   3#include "dir.h"
   4#include "object.h"
   5#include "commit.h"
   6#include "tag.h"
   7#include "run-command.h"
   8#include "exec_cmd.h"
   9#include "utf8.h"
  10#include "cache-tree.h"
  11#include "diff.h"
  12#include "revision.h"
  13#include "rerere.h"
  14#include "merge-recursive.h"
  15#include "refs.h"
  16
  17#define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
  18
  19void remove_sequencer_state(void)
  20{
  21        struct strbuf seq_dir = STRBUF_INIT;
  22
  23        strbuf_addf(&seq_dir, "%s", git_path(SEQ_DIR));
  24        remove_dir_recursively(&seq_dir, 0);
  25        strbuf_release(&seq_dir);
  26}
  27
  28static const char *action_name(const struct replay_opts *opts)
  29{
  30        return opts->action == REPLAY_REVERT ? "revert" : "cherry-pick";
  31}
  32
  33static char *get_encoding(const char *message);
  34
  35struct commit_message {
  36        char *parent_label;
  37        const char *label;
  38        const char *subject;
  39        char *reencoded_message;
  40        const char *message;
  41};
  42
  43static int get_message(struct commit *commit, struct commit_message *out)
  44{
  45        const char *encoding;
  46        const char *abbrev, *subject;
  47        int abbrev_len, subject_len;
  48        char *q;
  49
  50        if (!commit->buffer)
  51                return -1;
  52        encoding = get_encoding(commit->buffer);
  53        if (!encoding)
  54                encoding = "UTF-8";
  55        if (!git_commit_encoding)
  56                git_commit_encoding = "UTF-8";
  57
  58        out->reencoded_message = NULL;
  59        out->message = commit->buffer;
  60        if (strcmp(encoding, git_commit_encoding))
  61                out->reencoded_message = reencode_string(commit->buffer,
  62                                        git_commit_encoding, encoding);
  63        if (out->reencoded_message)
  64                out->message = out->reencoded_message;
  65
  66        abbrev = find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV);
  67        abbrev_len = strlen(abbrev);
  68
  69        subject_len = find_commit_subject(out->message, &subject);
  70
  71        out->parent_label = xmalloc(strlen("parent of ") + abbrev_len +
  72                              strlen("... ") + subject_len + 1);
  73        q = out->parent_label;
  74        q = mempcpy(q, "parent of ", strlen("parent of "));
  75        out->label = q;
  76        q = mempcpy(q, abbrev, abbrev_len);
  77        q = mempcpy(q, "... ", strlen("... "));
  78        out->subject = q;
  79        q = mempcpy(q, subject, subject_len);
  80        *q = '\0';
  81        return 0;
  82}
  83
  84static void free_message(struct commit_message *msg)
  85{
  86        free(msg->parent_label);
  87        free(msg->reencoded_message);
  88}
  89
  90static char *get_encoding(const char *message)
  91{
  92        const char *p = message, *eol;
  93
  94        while (*p && *p != '\n') {
  95                for (eol = p + 1; *eol && *eol != '\n'; eol++)
  96                        ; /* do nothing */
  97                if (!prefixcmp(p, "encoding ")) {
  98                        char *result = xmalloc(eol - 8 - p);
  99                        strlcpy(result, p + 9, eol - 8 - p);
 100                        return result;
 101                }
 102                p = eol;
 103                if (*p == '\n')
 104                        p++;
 105        }
 106        return NULL;
 107}
 108
 109static void write_cherry_pick_head(struct commit *commit, const char *pseudoref)
 110{
 111        const char *filename;
 112        int fd;
 113        struct strbuf buf = STRBUF_INIT;
 114
 115        strbuf_addf(&buf, "%s\n", sha1_to_hex(commit->object.sha1));
 116
 117        filename = git_path("%s", pseudoref);
 118        fd = open(filename, O_WRONLY | O_CREAT, 0666);
 119        if (fd < 0)
 120                die_errno(_("Could not open '%s' for writing"), filename);
 121        if (write_in_full(fd, buf.buf, buf.len) != buf.len || close(fd))
 122                die_errno(_("Could not write to '%s'"), filename);
 123        strbuf_release(&buf);
 124}
 125
 126static void print_advice(int show_hint, struct replay_opts *opts)
 127{
 128        char *msg = getenv("GIT_CHERRY_PICK_HELP");
 129
 130        if (msg) {
 131                fprintf(stderr, "%s\n", msg);
 132                /*
 133                 * A conflict has occured but the porcelain
 134                 * (typically rebase --interactive) wants to take care
 135                 * of the commit itself so remove CHERRY_PICK_HEAD
 136                 */
 137                unlink(git_path("CHERRY_PICK_HEAD"));
 138                return;
 139        }
 140
 141        if (show_hint) {
 142                if (opts->no_commit)
 143                        advise(_("after resolving the conflicts, mark the corrected paths\n"
 144                                 "with 'git add <paths>' or 'git rm <paths>'"));
 145                else
 146                        advise(_("after resolving the conflicts, mark the corrected paths\n"
 147                                 "with 'git add <paths>' or 'git rm <paths>'\n"
 148                                 "and commit the result with 'git commit'"));
 149        }
 150}
 151
 152static void write_message(struct strbuf *msgbuf, const char *filename)
 153{
 154        static struct lock_file msg_file;
 155
 156        int msg_fd = hold_lock_file_for_update(&msg_file, filename,
 157                                               LOCK_DIE_ON_ERROR);
 158        if (write_in_full(msg_fd, msgbuf->buf, msgbuf->len) < 0)
 159                die_errno(_("Could not write to %s"), filename);
 160        strbuf_release(msgbuf);
 161        if (commit_lock_file(&msg_file) < 0)
 162                die(_("Error wrapping up %s"), filename);
 163}
 164
 165static struct tree *empty_tree(void)
 166{
 167        return lookup_tree((const unsigned char *)EMPTY_TREE_SHA1_BIN);
 168}
 169
 170static int error_dirty_index(struct replay_opts *opts)
 171{
 172        if (read_cache_unmerged())
 173                return error_resolve_conflict(action_name(opts));
 174
 175        /* Different translation strings for cherry-pick and revert */
 176        if (opts->action == REPLAY_PICK)
 177                error(_("Your local changes would be overwritten by cherry-pick."));
 178        else
 179                error(_("Your local changes would be overwritten by revert."));
 180
 181        if (advice_commit_before_merge)
 182                advise(_("Commit your changes or stash them to proceed."));
 183        return -1;
 184}
 185
 186static int fast_forward_to(const unsigned char *to, const unsigned char *from)
 187{
 188        struct ref_lock *ref_lock;
 189
 190        read_cache();
 191        if (checkout_fast_forward(from, to))
 192                exit(1); /* the callee should have complained already */
 193        ref_lock = lock_any_ref_for_update("HEAD", from, 0);
 194        return write_ref_sha1(ref_lock, to, "cherry-pick");
 195}
 196
 197static int do_recursive_merge(struct commit *base, struct commit *next,
 198                              const char *base_label, const char *next_label,
 199                              unsigned char *head, struct strbuf *msgbuf,
 200                              struct replay_opts *opts)
 201{
 202        struct merge_options o;
 203        struct tree *result, *next_tree, *base_tree, *head_tree;
 204        int clean, index_fd;
 205        const char **xopt;
 206        static struct lock_file index_lock;
 207
 208        index_fd = hold_locked_index(&index_lock, 1);
 209
 210        read_cache();
 211
 212        init_merge_options(&o);
 213        o.ancestor = base ? base_label : "(empty tree)";
 214        o.branch1 = "HEAD";
 215        o.branch2 = next ? next_label : "(empty tree)";
 216
 217        head_tree = parse_tree_indirect(head);
 218        next_tree = next ? next->tree : empty_tree();
 219        base_tree = base ? base->tree : empty_tree();
 220
 221        for (xopt = opts->xopts; xopt != opts->xopts + opts->xopts_nr; xopt++)
 222                parse_merge_opt(&o, *xopt);
 223
 224        clean = merge_trees(&o,
 225                            head_tree,
 226                            next_tree, base_tree, &result);
 227
 228        if (active_cache_changed &&
 229            (write_cache(index_fd, active_cache, active_nr) ||
 230             commit_locked_index(&index_lock)))
 231                /* TRANSLATORS: %s will be "revert" or "cherry-pick" */
 232                die(_("%s: Unable to write new index file"), action_name(opts));
 233        rollback_lock_file(&index_lock);
 234
 235        if (!clean) {
 236                int i;
 237                strbuf_addstr(msgbuf, "\nConflicts:\n\n");
 238                for (i = 0; i < active_nr;) {
 239                        struct cache_entry *ce = active_cache[i++];
 240                        if (ce_stage(ce)) {
 241                                strbuf_addch(msgbuf, '\t');
 242                                strbuf_addstr(msgbuf, ce->name);
 243                                strbuf_addch(msgbuf, '\n');
 244                                while (i < active_nr && !strcmp(ce->name,
 245                                                active_cache[i]->name))
 246                                        i++;
 247                        }
 248                }
 249        }
 250
 251        return !clean;
 252}
 253
 254/*
 255 * If we are cherry-pick, and if the merge did not result in
 256 * hand-editing, we will hit this commit and inherit the original
 257 * author date and name.
 258 * If we are revert, or if our cherry-pick results in a hand merge,
 259 * we had better say that the current user is responsible for that.
 260 */
 261static int run_git_commit(const char *defmsg, struct replay_opts *opts)
 262{
 263        /* 6 is max possible length of our args array including NULL */
 264        const char *args[6];
 265        int i = 0;
 266
 267        args[i++] = "commit";
 268        args[i++] = "-n";
 269        if (opts->signoff)
 270                args[i++] = "-s";
 271        if (!opts->edit) {
 272                args[i++] = "-F";
 273                args[i++] = defmsg;
 274        }
 275        args[i] = NULL;
 276
 277        return run_command_v_opt(args, RUN_GIT_CMD);
 278}
 279
 280static int do_pick_commit(struct commit *commit, struct replay_opts *opts)
 281{
 282        unsigned char head[20];
 283        struct commit *base, *next, *parent;
 284        const char *base_label, *next_label;
 285        struct commit_message msg = { NULL, NULL, NULL, NULL, NULL };
 286        char *defmsg = NULL;
 287        struct strbuf msgbuf = STRBUF_INIT;
 288        int res;
 289
 290        if (opts->no_commit) {
 291                /*
 292                 * We do not intend to commit immediately.  We just want to
 293                 * merge the differences in, so let's compute the tree
 294                 * that represents the "current" state for merge-recursive
 295                 * to work on.
 296                 */
 297                if (write_cache_as_tree(head, 0, NULL))
 298                        die (_("Your index file is unmerged."));
 299        } else {
 300                if (get_sha1("HEAD", head))
 301                        return error(_("You do not have a valid HEAD"));
 302                if (index_differs_from("HEAD", 0))
 303                        return error_dirty_index(opts);
 304        }
 305        discard_cache();
 306
 307        if (!commit->parents) {
 308                parent = NULL;
 309        }
 310        else if (commit->parents->next) {
 311                /* Reverting or cherry-picking a merge commit */
 312                int cnt;
 313                struct commit_list *p;
 314
 315                if (!opts->mainline)
 316                        return error(_("Commit %s is a merge but no -m option was given."),
 317                                sha1_to_hex(commit->object.sha1));
 318
 319                for (cnt = 1, p = commit->parents;
 320                     cnt != opts->mainline && p;
 321                     cnt++)
 322                        p = p->next;
 323                if (cnt != opts->mainline || !p)
 324                        return error(_("Commit %s does not have parent %d"),
 325                                sha1_to_hex(commit->object.sha1), opts->mainline);
 326                parent = p->item;
 327        } else if (0 < opts->mainline)
 328                return error(_("Mainline was specified but commit %s is not a merge."),
 329                        sha1_to_hex(commit->object.sha1));
 330        else
 331                parent = commit->parents->item;
 332
 333        if (opts->allow_ff && parent && !hashcmp(parent->object.sha1, head))
 334                return fast_forward_to(commit->object.sha1, head);
 335
 336        if (parent && parse_commit(parent) < 0)
 337                /* TRANSLATORS: The first %s will be "revert" or
 338                   "cherry-pick", the second %s a SHA1 */
 339                return error(_("%s: cannot parse parent commit %s"),
 340                        action_name(opts), sha1_to_hex(parent->object.sha1));
 341
 342        if (get_message(commit, &msg) != 0)
 343                return error(_("Cannot get commit message for %s"),
 344                        sha1_to_hex(commit->object.sha1));
 345
 346        /*
 347         * "commit" is an existing commit.  We would want to apply
 348         * the difference it introduces since its first parent "prev"
 349         * on top of the current HEAD if we are cherry-pick.  Or the
 350         * reverse of it if we are revert.
 351         */
 352
 353        defmsg = git_pathdup("MERGE_MSG");
 354
 355        if (opts->action == REPLAY_REVERT) {
 356                base = commit;
 357                base_label = msg.label;
 358                next = parent;
 359                next_label = msg.parent_label;
 360                strbuf_addstr(&msgbuf, "Revert \"");
 361                strbuf_addstr(&msgbuf, msg.subject);
 362                strbuf_addstr(&msgbuf, "\"\n\nThis reverts commit ");
 363                strbuf_addstr(&msgbuf, sha1_to_hex(commit->object.sha1));
 364
 365                if (commit->parents && commit->parents->next) {
 366                        strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
 367                        strbuf_addstr(&msgbuf, sha1_to_hex(parent->object.sha1));
 368                }
 369                strbuf_addstr(&msgbuf, ".\n");
 370        } else {
 371                const char *p;
 372
 373                base = parent;
 374                base_label = msg.parent_label;
 375                next = commit;
 376                next_label = msg.label;
 377
 378                /*
 379                 * Append the commit log message to msgbuf; it starts
 380                 * after the tree, parent, author, committer
 381                 * information followed by "\n\n".
 382                 */
 383                p = strstr(msg.message, "\n\n");
 384                if (p) {
 385                        p += 2;
 386                        strbuf_addstr(&msgbuf, p);
 387                }
 388
 389                if (opts->record_origin) {
 390                        strbuf_addstr(&msgbuf, "(cherry picked from commit ");
 391                        strbuf_addstr(&msgbuf, sha1_to_hex(commit->object.sha1));
 392                        strbuf_addstr(&msgbuf, ")\n");
 393                }
 394        }
 395
 396        if (!opts->strategy || !strcmp(opts->strategy, "recursive") || opts->action == REPLAY_REVERT) {
 397                res = do_recursive_merge(base, next, base_label, next_label,
 398                                         head, &msgbuf, opts);
 399                write_message(&msgbuf, defmsg);
 400        } else {
 401                struct commit_list *common = NULL;
 402                struct commit_list *remotes = NULL;
 403
 404                write_message(&msgbuf, defmsg);
 405
 406                commit_list_insert(base, &common);
 407                commit_list_insert(next, &remotes);
 408                res = try_merge_command(opts->strategy, opts->xopts_nr, opts->xopts,
 409                                        common, sha1_to_hex(head), remotes);
 410                free_commit_list(common);
 411                free_commit_list(remotes);
 412        }
 413
 414        /*
 415         * If the merge was clean or if it failed due to conflict, we write
 416         * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
 417         * However, if the merge did not even start, then we don't want to
 418         * write it at all.
 419         */
 420        if (opts->action == REPLAY_PICK && !opts->no_commit && (res == 0 || res == 1))
 421                write_cherry_pick_head(commit, "CHERRY_PICK_HEAD");
 422        if (opts->action == REPLAY_REVERT && ((opts->no_commit && res == 0) || res == 1))
 423                write_cherry_pick_head(commit, "REVERT_HEAD");
 424
 425        if (res) {
 426                error(opts->action == REPLAY_REVERT
 427                      ? _("could not revert %s... %s")
 428                      : _("could not apply %s... %s"),
 429                      find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV),
 430                      msg.subject);
 431                print_advice(res == 1, opts);
 432                rerere(opts->allow_rerere_auto);
 433        } else {
 434                if (!opts->no_commit)
 435                        res = run_git_commit(defmsg, opts);
 436        }
 437
 438        free_message(&msg);
 439        free(defmsg);
 440
 441        return res;
 442}
 443
 444static void prepare_revs(struct replay_opts *opts)
 445{
 446        if (opts->action != REPLAY_REVERT)
 447                opts->revs->reverse ^= 1;
 448
 449        if (prepare_revision_walk(opts->revs))
 450                die(_("revision walk setup failed"));
 451
 452        if (!opts->revs->commits)
 453                die(_("empty commit set passed"));
 454}
 455
 456static void read_and_refresh_cache(struct replay_opts *opts)
 457{
 458        static struct lock_file index_lock;
 459        int index_fd = hold_locked_index(&index_lock, 0);
 460        if (read_index_preload(&the_index, NULL) < 0)
 461                die(_("git %s: failed to read the index"), action_name(opts));
 462        refresh_index(&the_index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
 463        if (the_index.cache_changed) {
 464                if (write_index(&the_index, index_fd) ||
 465                    commit_locked_index(&index_lock))
 466                        die(_("git %s: failed to refresh the index"), action_name(opts));
 467        }
 468        rollback_lock_file(&index_lock);
 469}
 470
 471/*
 472 * Append a commit to the end of the commit_list.
 473 *
 474 * next starts by pointing to the variable that holds the head of an
 475 * empty commit_list, and is updated to point to the "next" field of
 476 * the last item on the list as new commits are appended.
 477 *
 478 * Usage example:
 479 *
 480 *     struct commit_list *list;
 481 *     struct commit_list **next = &list;
 482 *
 483 *     next = commit_list_append(c1, next);
 484 *     next = commit_list_append(c2, next);
 485 *     assert(commit_list_count(list) == 2);
 486 *     return list;
 487 */
 488static struct commit_list **commit_list_append(struct commit *commit,
 489                                               struct commit_list **next)
 490{
 491        struct commit_list *new = xmalloc(sizeof(struct commit_list));
 492        new->item = commit;
 493        *next = new;
 494        new->next = NULL;
 495        return &new->next;
 496}
 497
 498static int format_todo(struct strbuf *buf, struct commit_list *todo_list,
 499                struct replay_opts *opts)
 500{
 501        struct commit_list *cur = NULL;
 502        const char *sha1_abbrev = NULL;
 503        const char *action_str = opts->action == REPLAY_REVERT ? "revert" : "pick";
 504        const char *subject;
 505        int subject_len;
 506
 507        for (cur = todo_list; cur; cur = cur->next) {
 508                sha1_abbrev = find_unique_abbrev(cur->item->object.sha1, DEFAULT_ABBREV);
 509                subject_len = find_commit_subject(cur->item->buffer, &subject);
 510                strbuf_addf(buf, "%s %s %.*s\n", action_str, sha1_abbrev,
 511                        subject_len, subject);
 512        }
 513        return 0;
 514}
 515
 516static struct commit *parse_insn_line(char *bol, char *eol, struct replay_opts *opts)
 517{
 518        unsigned char commit_sha1[20];
 519        enum replay_action action;
 520        char *end_of_object_name;
 521        int saved, status, padding;
 522
 523        if (!prefixcmp(bol, "pick")) {
 524                action = REPLAY_PICK;
 525                bol += strlen("pick");
 526        } else if (!prefixcmp(bol, "revert")) {
 527                action = REPLAY_REVERT;
 528                bol += strlen("revert");
 529        } else
 530                return NULL;
 531
 532        /* Eat up extra spaces/ tabs before object name */
 533        padding = strspn(bol, " \t");
 534        if (!padding)
 535                return NULL;
 536        bol += padding;
 537
 538        end_of_object_name = bol + strcspn(bol, " \t\n");
 539        saved = *end_of_object_name;
 540        *end_of_object_name = '\0';
 541        status = get_sha1(bol, commit_sha1);
 542        *end_of_object_name = saved;
 543
 544        /*
 545         * Verify that the action matches up with the one in
 546         * opts; we don't support arbitrary instructions
 547         */
 548        if (action != opts->action) {
 549                const char *action_str;
 550                action_str = action == REPLAY_REVERT ? "revert" : "cherry-pick";
 551                error(_("Cannot %s during a %s"), action_str, action_name(opts));
 552                return NULL;
 553        }
 554
 555        if (status < 0)
 556                return NULL;
 557
 558        return lookup_commit_reference(commit_sha1);
 559}
 560
 561static int parse_insn_buffer(char *buf, struct commit_list **todo_list,
 562                        struct replay_opts *opts)
 563{
 564        struct commit_list **next = todo_list;
 565        struct commit *commit;
 566        char *p = buf;
 567        int i;
 568
 569        for (i = 1; *p; i++) {
 570                char *eol = strchrnul(p, '\n');
 571                commit = parse_insn_line(p, eol, opts);
 572                if (!commit)
 573                        return error(_("Could not parse line %d."), i);
 574                next = commit_list_append(commit, next);
 575                p = *eol ? eol + 1 : eol;
 576        }
 577        if (!*todo_list)
 578                return error(_("No commits parsed."));
 579        return 0;
 580}
 581
 582static void read_populate_todo(struct commit_list **todo_list,
 583                        struct replay_opts *opts)
 584{
 585        const char *todo_file = git_path(SEQ_TODO_FILE);
 586        struct strbuf buf = STRBUF_INIT;
 587        int fd, res;
 588
 589        fd = open(todo_file, O_RDONLY);
 590        if (fd < 0)
 591                die_errno(_("Could not open %s"), todo_file);
 592        if (strbuf_read(&buf, fd, 0) < 0) {
 593                close(fd);
 594                strbuf_release(&buf);
 595                die(_("Could not read %s."), todo_file);
 596        }
 597        close(fd);
 598
 599        res = parse_insn_buffer(buf.buf, todo_list, opts);
 600        strbuf_release(&buf);
 601        if (res)
 602                die(_("Unusable instruction sheet: %s"), todo_file);
 603}
 604
 605static int populate_opts_cb(const char *key, const char *value, void *data)
 606{
 607        struct replay_opts *opts = data;
 608        int error_flag = 1;
 609
 610        if (!value)
 611                error_flag = 0;
 612        else if (!strcmp(key, "options.no-commit"))
 613                opts->no_commit = git_config_bool_or_int(key, value, &error_flag);
 614        else if (!strcmp(key, "options.edit"))
 615                opts->edit = git_config_bool_or_int(key, value, &error_flag);
 616        else if (!strcmp(key, "options.signoff"))
 617                opts->signoff = git_config_bool_or_int(key, value, &error_flag);
 618        else if (!strcmp(key, "options.record-origin"))
 619                opts->record_origin = git_config_bool_or_int(key, value, &error_flag);
 620        else if (!strcmp(key, "options.allow-ff"))
 621                opts->allow_ff = git_config_bool_or_int(key, value, &error_flag);
 622        else if (!strcmp(key, "options.mainline"))
 623                opts->mainline = git_config_int(key, value);
 624        else if (!strcmp(key, "options.strategy"))
 625                git_config_string(&opts->strategy, key, value);
 626        else if (!strcmp(key, "options.strategy-option")) {
 627                ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
 628                opts->xopts[opts->xopts_nr++] = xstrdup(value);
 629        } else
 630                return error(_("Invalid key: %s"), key);
 631
 632        if (!error_flag)
 633                return error(_("Invalid value for %s: %s"), key, value);
 634
 635        return 0;
 636}
 637
 638static void read_populate_opts(struct replay_opts **opts_ptr)
 639{
 640        const char *opts_file = git_path(SEQ_OPTS_FILE);
 641
 642        if (!file_exists(opts_file))
 643                return;
 644        if (git_config_from_file(populate_opts_cb, opts_file, *opts_ptr) < 0)
 645                die(_("Malformed options sheet: %s"), opts_file);
 646}
 647
 648static void walk_revs_populate_todo(struct commit_list **todo_list,
 649                                struct replay_opts *opts)
 650{
 651        struct commit *commit;
 652        struct commit_list **next;
 653
 654        prepare_revs(opts);
 655
 656        next = todo_list;
 657        while ((commit = get_revision(opts->revs)))
 658                next = commit_list_append(commit, next);
 659}
 660
 661static int create_seq_dir(void)
 662{
 663        const char *seq_dir = git_path(SEQ_DIR);
 664
 665        if (file_exists(seq_dir)) {
 666                error(_("a cherry-pick or revert is already in progress"));
 667                advise(_("try \"git cherry-pick (--continue | --quit | --abort)\""));
 668                return -1;
 669        }
 670        else if (mkdir(seq_dir, 0777) < 0)
 671                die_errno(_("Could not create sequencer directory %s"), seq_dir);
 672        return 0;
 673}
 674
 675static void save_head(const char *head)
 676{
 677        const char *head_file = git_path(SEQ_HEAD_FILE);
 678        static struct lock_file head_lock;
 679        struct strbuf buf = STRBUF_INIT;
 680        int fd;
 681
 682        fd = hold_lock_file_for_update(&head_lock, head_file, LOCK_DIE_ON_ERROR);
 683        strbuf_addf(&buf, "%s\n", head);
 684        if (write_in_full(fd, buf.buf, buf.len) < 0)
 685                die_errno(_("Could not write to %s"), head_file);
 686        if (commit_lock_file(&head_lock) < 0)
 687                die(_("Error wrapping up %s."), head_file);
 688}
 689
 690static int reset_for_rollback(const unsigned char *sha1)
 691{
 692        const char *argv[4];    /* reset --merge <arg> + NULL */
 693        argv[0] = "reset";
 694        argv[1] = "--merge";
 695        argv[2] = sha1_to_hex(sha1);
 696        argv[3] = NULL;
 697        return run_command_v_opt(argv, RUN_GIT_CMD);
 698}
 699
 700static int rollback_single_pick(void)
 701{
 702        unsigned char head_sha1[20];
 703
 704        if (!file_exists(git_path("CHERRY_PICK_HEAD")) &&
 705            !file_exists(git_path("REVERT_HEAD")))
 706                return error(_("no cherry-pick or revert in progress"));
 707        if (read_ref_full("HEAD", head_sha1, 0, NULL))
 708                return error(_("cannot resolve HEAD"));
 709        if (is_null_sha1(head_sha1))
 710                return error(_("cannot abort from a branch yet to be born"));
 711        return reset_for_rollback(head_sha1);
 712}
 713
 714static int sequencer_rollback(struct replay_opts *opts)
 715{
 716        const char *filename;
 717        FILE *f;
 718        unsigned char sha1[20];
 719        struct strbuf buf = STRBUF_INIT;
 720
 721        filename = git_path(SEQ_HEAD_FILE);
 722        f = fopen(filename, "r");
 723        if (!f && errno == ENOENT) {
 724                /*
 725                 * There is no multiple-cherry-pick in progress.
 726                 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
 727                 * a single-cherry-pick in progress, abort that.
 728                 */
 729                return rollback_single_pick();
 730        }
 731        if (!f)
 732                return error(_("cannot open %s: %s"), filename,
 733                                                strerror(errno));
 734        if (strbuf_getline(&buf, f, '\n')) {
 735                error(_("cannot read %s: %s"), filename, ferror(f) ?
 736                        strerror(errno) : _("unexpected end of file"));
 737                fclose(f);
 738                goto fail;
 739        }
 740        fclose(f);
 741        if (get_sha1_hex(buf.buf, sha1) || buf.buf[40] != '\0') {
 742                error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
 743                        filename);
 744                goto fail;
 745        }
 746        if (reset_for_rollback(sha1))
 747                goto fail;
 748        remove_sequencer_state();
 749        strbuf_release(&buf);
 750        return 0;
 751fail:
 752        strbuf_release(&buf);
 753        return -1;
 754}
 755
 756static void save_todo(struct commit_list *todo_list, struct replay_opts *opts)
 757{
 758        const char *todo_file = git_path(SEQ_TODO_FILE);
 759        static struct lock_file todo_lock;
 760        struct strbuf buf = STRBUF_INIT;
 761        int fd;
 762
 763        fd = hold_lock_file_for_update(&todo_lock, todo_file, LOCK_DIE_ON_ERROR);
 764        if (format_todo(&buf, todo_list, opts) < 0)
 765                die(_("Could not format %s."), todo_file);
 766        if (write_in_full(fd, buf.buf, buf.len) < 0) {
 767                strbuf_release(&buf);
 768                die_errno(_("Could not write to %s"), todo_file);
 769        }
 770        if (commit_lock_file(&todo_lock) < 0) {
 771                strbuf_release(&buf);
 772                die(_("Error wrapping up %s."), todo_file);
 773        }
 774        strbuf_release(&buf);
 775}
 776
 777static void save_opts(struct replay_opts *opts)
 778{
 779        const char *opts_file = git_path(SEQ_OPTS_FILE);
 780
 781        if (opts->no_commit)
 782                git_config_set_in_file(opts_file, "options.no-commit", "true");
 783        if (opts->edit)
 784                git_config_set_in_file(opts_file, "options.edit", "true");
 785        if (opts->signoff)
 786                git_config_set_in_file(opts_file, "options.signoff", "true");
 787        if (opts->record_origin)
 788                git_config_set_in_file(opts_file, "options.record-origin", "true");
 789        if (opts->allow_ff)
 790                git_config_set_in_file(opts_file, "options.allow-ff", "true");
 791        if (opts->mainline) {
 792                struct strbuf buf = STRBUF_INIT;
 793                strbuf_addf(&buf, "%d", opts->mainline);
 794                git_config_set_in_file(opts_file, "options.mainline", buf.buf);
 795                strbuf_release(&buf);
 796        }
 797        if (opts->strategy)
 798                git_config_set_in_file(opts_file, "options.strategy", opts->strategy);
 799        if (opts->xopts) {
 800                int i;
 801                for (i = 0; i < opts->xopts_nr; i++)
 802                        git_config_set_multivar_in_file(opts_file,
 803                                                        "options.strategy-option",
 804                                                        opts->xopts[i], "^$", 0);
 805        }
 806}
 807
 808static int pick_commits(struct commit_list *todo_list, struct replay_opts *opts)
 809{
 810        struct commit_list *cur;
 811        int res;
 812
 813        setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
 814        if (opts->allow_ff)
 815                assert(!(opts->signoff || opts->no_commit ||
 816                                opts->record_origin || opts->edit));
 817        read_and_refresh_cache(opts);
 818
 819        for (cur = todo_list; cur; cur = cur->next) {
 820                save_todo(cur, opts);
 821                res = do_pick_commit(cur->item, opts);
 822                if (res)
 823                        return res;
 824        }
 825
 826        /*
 827         * Sequence of picks finished successfully; cleanup by
 828         * removing the .git/sequencer directory
 829         */
 830        remove_sequencer_state();
 831        return 0;
 832}
 833
 834static int continue_single_pick(void)
 835{
 836        const char *argv[] = { "commit", NULL };
 837
 838        if (!file_exists(git_path("CHERRY_PICK_HEAD")) &&
 839            !file_exists(git_path("REVERT_HEAD")))
 840                return error(_("no cherry-pick or revert in progress"));
 841        return run_command_v_opt(argv, RUN_GIT_CMD);
 842}
 843
 844static int sequencer_continue(struct replay_opts *opts)
 845{
 846        struct commit_list *todo_list = NULL;
 847
 848        if (!file_exists(git_path(SEQ_TODO_FILE)))
 849                return continue_single_pick();
 850        read_populate_opts(&opts);
 851        read_populate_todo(&todo_list, opts);
 852
 853        /* Verify that the conflict has been resolved */
 854        if (file_exists(git_path("CHERRY_PICK_HEAD")) ||
 855            file_exists(git_path("REVERT_HEAD"))) {
 856                int ret = continue_single_pick();
 857                if (ret)
 858                        return ret;
 859        }
 860        if (index_differs_from("HEAD", 0))
 861                return error_dirty_index(opts);
 862        todo_list = todo_list->next;
 863        return pick_commits(todo_list, opts);
 864}
 865
 866static int single_pick(struct commit *cmit, struct replay_opts *opts)
 867{
 868        setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
 869        return do_pick_commit(cmit, opts);
 870}
 871
 872int sequencer_pick_revisions(struct replay_opts *opts)
 873{
 874        struct commit_list *todo_list = NULL;
 875        unsigned char sha1[20];
 876
 877        if (opts->subcommand == REPLAY_NONE)
 878                assert(opts->revs);
 879
 880        read_and_refresh_cache(opts);
 881
 882        /*
 883         * Decide what to do depending on the arguments; a fresh
 884         * cherry-pick should be handled differently from an existing
 885         * one that is being continued
 886         */
 887        if (opts->subcommand == REPLAY_REMOVE_STATE) {
 888                remove_sequencer_state();
 889                return 0;
 890        }
 891        if (opts->subcommand == REPLAY_ROLLBACK)
 892                return sequencer_rollback(opts);
 893        if (opts->subcommand == REPLAY_CONTINUE)
 894                return sequencer_continue(opts);
 895
 896        /*
 897         * If we were called as "git cherry-pick <commit>", just
 898         * cherry-pick/revert it, set CHERRY_PICK_HEAD /
 899         * REVERT_HEAD, and don't touch the sequencer state.
 900         * This means it is possible to cherry-pick in the middle
 901         * of a cherry-pick sequence.
 902         */
 903        if (opts->revs->cmdline.nr == 1 &&
 904            opts->revs->cmdline.rev->whence == REV_CMD_REV &&
 905            opts->revs->no_walk &&
 906            !opts->revs->cmdline.rev->flags) {
 907                struct commit *cmit;
 908                if (prepare_revision_walk(opts->revs))
 909                        die(_("revision walk setup failed"));
 910                cmit = get_revision(opts->revs);
 911                if (!cmit || get_revision(opts->revs))
 912                        die("BUG: expected exactly one commit from walk");
 913                return single_pick(cmit, opts);
 914        }
 915
 916        /*
 917         * Start a new cherry-pick/ revert sequence; but
 918         * first, make sure that an existing one isn't in
 919         * progress
 920         */
 921
 922        walk_revs_populate_todo(&todo_list, opts);
 923        if (create_seq_dir() < 0)
 924                return -1;
 925        if (get_sha1("HEAD", sha1)) {
 926                if (opts->action == REPLAY_REVERT)
 927                        return error(_("Can't revert as initial commit"));
 928                return error(_("Can't cherry-pick into empty head"));
 929        }
 930        save_head(sha1_to_hex(sha1));
 931        save_opts(opts);
 932        return pick_commits(todo_list, opts);
 933}