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