71929ba8cdeb45dc4a05a6513ac72b90dacf32be
   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        /* 7 is max possible length of our args array including NULL */
 264        const char *args[7];
 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        if (opts->allow_empty)
 276                args[i++] = "--allow-empty";
 277
 278        args[i] = NULL;
 279
 280        return run_command_v_opt(args, RUN_GIT_CMD);
 281}
 282
 283static int do_pick_commit(struct commit *commit, struct replay_opts *opts)
 284{
 285        unsigned char head[20];
 286        struct commit *base, *next, *parent;
 287        const char *base_label, *next_label;
 288        struct commit_message msg = { NULL, NULL, NULL, NULL, NULL };
 289        char *defmsg = NULL;
 290        struct strbuf msgbuf = STRBUF_INIT;
 291        int res;
 292
 293        if (opts->no_commit) {
 294                /*
 295                 * We do not intend to commit immediately.  We just want to
 296                 * merge the differences in, so let's compute the tree
 297                 * that represents the "current" state for merge-recursive
 298                 * to work on.
 299                 */
 300                if (write_cache_as_tree(head, 0, NULL))
 301                        die (_("Your index file is unmerged."));
 302        } else {
 303                if (get_sha1("HEAD", head))
 304                        return error(_("You do not have a valid HEAD"));
 305                if (index_differs_from("HEAD", 0))
 306                        return error_dirty_index(opts);
 307        }
 308        discard_cache();
 309
 310        if (!commit->parents) {
 311                parent = NULL;
 312        }
 313        else if (commit->parents->next) {
 314                /* Reverting or cherry-picking a merge commit */
 315                int cnt;
 316                struct commit_list *p;
 317
 318                if (!opts->mainline)
 319                        return error(_("Commit %s is a merge but no -m option was given."),
 320                                sha1_to_hex(commit->object.sha1));
 321
 322                for (cnt = 1, p = commit->parents;
 323                     cnt != opts->mainline && p;
 324                     cnt++)
 325                        p = p->next;
 326                if (cnt != opts->mainline || !p)
 327                        return error(_("Commit %s does not have parent %d"),
 328                                sha1_to_hex(commit->object.sha1), opts->mainline);
 329                parent = p->item;
 330        } else if (0 < opts->mainline)
 331                return error(_("Mainline was specified but commit %s is not a merge."),
 332                        sha1_to_hex(commit->object.sha1));
 333        else
 334                parent = commit->parents->item;
 335
 336        if (opts->allow_ff && parent && !hashcmp(parent->object.sha1, head))
 337                return fast_forward_to(commit->object.sha1, head);
 338
 339        if (parent && parse_commit(parent) < 0)
 340                /* TRANSLATORS: The first %s will be "revert" or
 341                   "cherry-pick", the second %s a SHA1 */
 342                return error(_("%s: cannot parse parent commit %s"),
 343                        action_name(opts), sha1_to_hex(parent->object.sha1));
 344
 345        if (get_message(commit, &msg) != 0)
 346                return error(_("Cannot get commit message for %s"),
 347                        sha1_to_hex(commit->object.sha1));
 348
 349        /*
 350         * "commit" is an existing commit.  We would want to apply
 351         * the difference it introduces since its first parent "prev"
 352         * on top of the current HEAD if we are cherry-pick.  Or the
 353         * reverse of it if we are revert.
 354         */
 355
 356        defmsg = git_pathdup("MERGE_MSG");
 357
 358        if (opts->action == REPLAY_REVERT) {
 359                base = commit;
 360                base_label = msg.label;
 361                next = parent;
 362                next_label = msg.parent_label;
 363                strbuf_addstr(&msgbuf, "Revert \"");
 364                strbuf_addstr(&msgbuf, msg.subject);
 365                strbuf_addstr(&msgbuf, "\"\n\nThis reverts commit ");
 366                strbuf_addstr(&msgbuf, sha1_to_hex(commit->object.sha1));
 367
 368                if (commit->parents && commit->parents->next) {
 369                        strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
 370                        strbuf_addstr(&msgbuf, sha1_to_hex(parent->object.sha1));
 371                }
 372                strbuf_addstr(&msgbuf, ".\n");
 373        } else {
 374                const char *p;
 375
 376                base = parent;
 377                base_label = msg.parent_label;
 378                next = commit;
 379                next_label = msg.label;
 380
 381                /*
 382                 * Append the commit log message to msgbuf; it starts
 383                 * after the tree, parent, author, committer
 384                 * information followed by "\n\n".
 385                 */
 386                p = strstr(msg.message, "\n\n");
 387                if (p) {
 388                        p += 2;
 389                        strbuf_addstr(&msgbuf, p);
 390                }
 391
 392                if (opts->record_origin) {
 393                        strbuf_addstr(&msgbuf, "(cherry picked from commit ");
 394                        strbuf_addstr(&msgbuf, sha1_to_hex(commit->object.sha1));
 395                        strbuf_addstr(&msgbuf, ")\n");
 396                }
 397        }
 398
 399        if (!opts->strategy || !strcmp(opts->strategy, "recursive") || opts->action == REPLAY_REVERT) {
 400                res = do_recursive_merge(base, next, base_label, next_label,
 401                                         head, &msgbuf, opts);
 402                write_message(&msgbuf, defmsg);
 403        } else {
 404                struct commit_list *common = NULL;
 405                struct commit_list *remotes = NULL;
 406
 407                write_message(&msgbuf, defmsg);
 408
 409                commit_list_insert(base, &common);
 410                commit_list_insert(next, &remotes);
 411                res = try_merge_command(opts->strategy, opts->xopts_nr, opts->xopts,
 412                                        common, sha1_to_hex(head), remotes);
 413                free_commit_list(common);
 414                free_commit_list(remotes);
 415        }
 416
 417        /*
 418         * If the merge was clean or if it failed due to conflict, we write
 419         * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
 420         * However, if the merge did not even start, then we don't want to
 421         * write it at all.
 422         */
 423        if (opts->action == REPLAY_PICK && !opts->no_commit && (res == 0 || res == 1))
 424                write_cherry_pick_head(commit, "CHERRY_PICK_HEAD");
 425        if (opts->action == REPLAY_REVERT && ((opts->no_commit && res == 0) || res == 1))
 426                write_cherry_pick_head(commit, "REVERT_HEAD");
 427
 428        if (res) {
 429                error(opts->action == REPLAY_REVERT
 430                      ? _("could not revert %s... %s")
 431                      : _("could not apply %s... %s"),
 432                      find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV),
 433                      msg.subject);
 434                print_advice(res == 1, opts);
 435                rerere(opts->allow_rerere_auto);
 436        } else {
 437                if (!opts->no_commit)
 438                        res = run_git_commit(defmsg, opts);
 439        }
 440
 441        free_message(&msg);
 442        free(defmsg);
 443
 444        return res;
 445}
 446
 447static void prepare_revs(struct replay_opts *opts)
 448{
 449        if (opts->action != REPLAY_REVERT)
 450                opts->revs->reverse ^= 1;
 451
 452        if (prepare_revision_walk(opts->revs))
 453                die(_("revision walk setup failed"));
 454
 455        if (!opts->revs->commits)
 456                die(_("empty commit set passed"));
 457}
 458
 459static void read_and_refresh_cache(struct replay_opts *opts)
 460{
 461        static struct lock_file index_lock;
 462        int index_fd = hold_locked_index(&index_lock, 0);
 463        if (read_index_preload(&the_index, NULL) < 0)
 464                die(_("git %s: failed to read the index"), action_name(opts));
 465        refresh_index(&the_index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
 466        if (the_index.cache_changed) {
 467                if (write_index(&the_index, index_fd) ||
 468                    commit_locked_index(&index_lock))
 469                        die(_("git %s: failed to refresh the index"), action_name(opts));
 470        }
 471        rollback_lock_file(&index_lock);
 472}
 473
 474/*
 475 * Append a commit to the end of the commit_list.
 476 *
 477 * next starts by pointing to the variable that holds the head of an
 478 * empty commit_list, and is updated to point to the "next" field of
 479 * the last item on the list as new commits are appended.
 480 *
 481 * Usage example:
 482 *
 483 *     struct commit_list *list;
 484 *     struct commit_list **next = &list;
 485 *
 486 *     next = commit_list_append(c1, next);
 487 *     next = commit_list_append(c2, next);
 488 *     assert(commit_list_count(list) == 2);
 489 *     return list;
 490 */
 491static struct commit_list **commit_list_append(struct commit *commit,
 492                                               struct commit_list **next)
 493{
 494        struct commit_list *new = xmalloc(sizeof(struct commit_list));
 495        new->item = commit;
 496        *next = new;
 497        new->next = NULL;
 498        return &new->next;
 499}
 500
 501static int format_todo(struct strbuf *buf, struct commit_list *todo_list,
 502                struct replay_opts *opts)
 503{
 504        struct commit_list *cur = NULL;
 505        const char *sha1_abbrev = NULL;
 506        const char *action_str = opts->action == REPLAY_REVERT ? "revert" : "pick";
 507        const char *subject;
 508        int subject_len;
 509
 510        for (cur = todo_list; cur; cur = cur->next) {
 511                sha1_abbrev = find_unique_abbrev(cur->item->object.sha1, DEFAULT_ABBREV);
 512                subject_len = find_commit_subject(cur->item->buffer, &subject);
 513                strbuf_addf(buf, "%s %s %.*s\n", action_str, sha1_abbrev,
 514                        subject_len, subject);
 515        }
 516        return 0;
 517}
 518
 519static struct commit *parse_insn_line(char *bol, char *eol, struct replay_opts *opts)
 520{
 521        unsigned char commit_sha1[20];
 522        enum replay_action action;
 523        char *end_of_object_name;
 524        int saved, status, padding;
 525
 526        if (!prefixcmp(bol, "pick")) {
 527                action = REPLAY_PICK;
 528                bol += strlen("pick");
 529        } else if (!prefixcmp(bol, "revert")) {
 530                action = REPLAY_REVERT;
 531                bol += strlen("revert");
 532        } else
 533                return NULL;
 534
 535        /* Eat up extra spaces/ tabs before object name */
 536        padding = strspn(bol, " \t");
 537        if (!padding)
 538                return NULL;
 539        bol += padding;
 540
 541        end_of_object_name = bol + strcspn(bol, " \t\n");
 542        saved = *end_of_object_name;
 543        *end_of_object_name = '\0';
 544        status = get_sha1(bol, commit_sha1);
 545        *end_of_object_name = saved;
 546
 547        /*
 548         * Verify that the action matches up with the one in
 549         * opts; we don't support arbitrary instructions
 550         */
 551        if (action != opts->action) {
 552                const char *action_str;
 553                action_str = action == REPLAY_REVERT ? "revert" : "cherry-pick";
 554                error(_("Cannot %s during a %s"), action_str, action_name(opts));
 555                return NULL;
 556        }
 557
 558        if (status < 0)
 559                return NULL;
 560
 561        return lookup_commit_reference(commit_sha1);
 562}
 563
 564static int parse_insn_buffer(char *buf, struct commit_list **todo_list,
 565                        struct replay_opts *opts)
 566{
 567        struct commit_list **next = todo_list;
 568        struct commit *commit;
 569        char *p = buf;
 570        int i;
 571
 572        for (i = 1; *p; i++) {
 573                char *eol = strchrnul(p, '\n');
 574                commit = parse_insn_line(p, eol, opts);
 575                if (!commit)
 576                        return error(_("Could not parse line %d."), i);
 577                next = commit_list_append(commit, next);
 578                p = *eol ? eol + 1 : eol;
 579        }
 580        if (!*todo_list)
 581                return error(_("No commits parsed."));
 582        return 0;
 583}
 584
 585static void read_populate_todo(struct commit_list **todo_list,
 586                        struct replay_opts *opts)
 587{
 588        const char *todo_file = git_path(SEQ_TODO_FILE);
 589        struct strbuf buf = STRBUF_INIT;
 590        int fd, res;
 591
 592        fd = open(todo_file, O_RDONLY);
 593        if (fd < 0)
 594                die_errno(_("Could not open %s"), todo_file);
 595        if (strbuf_read(&buf, fd, 0) < 0) {
 596                close(fd);
 597                strbuf_release(&buf);
 598                die(_("Could not read %s."), todo_file);
 599        }
 600        close(fd);
 601
 602        res = parse_insn_buffer(buf.buf, todo_list, opts);
 603        strbuf_release(&buf);
 604        if (res)
 605                die(_("Unusable instruction sheet: %s"), todo_file);
 606}
 607
 608static int populate_opts_cb(const char *key, const char *value, void *data)
 609{
 610        struct replay_opts *opts = data;
 611        int error_flag = 1;
 612
 613        if (!value)
 614                error_flag = 0;
 615        else if (!strcmp(key, "options.no-commit"))
 616                opts->no_commit = git_config_bool_or_int(key, value, &error_flag);
 617        else if (!strcmp(key, "options.edit"))
 618                opts->edit = git_config_bool_or_int(key, value, &error_flag);
 619        else if (!strcmp(key, "options.signoff"))
 620                opts->signoff = git_config_bool_or_int(key, value, &error_flag);
 621        else if (!strcmp(key, "options.record-origin"))
 622                opts->record_origin = git_config_bool_or_int(key, value, &error_flag);
 623        else if (!strcmp(key, "options.allow-ff"))
 624                opts->allow_ff = git_config_bool_or_int(key, value, &error_flag);
 625        else if (!strcmp(key, "options.mainline"))
 626                opts->mainline = git_config_int(key, value);
 627        else if (!strcmp(key, "options.strategy"))
 628                git_config_string(&opts->strategy, key, value);
 629        else if (!strcmp(key, "options.strategy-option")) {
 630                ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
 631                opts->xopts[opts->xopts_nr++] = xstrdup(value);
 632        } else
 633                return error(_("Invalid key: %s"), key);
 634
 635        if (!error_flag)
 636                return error(_("Invalid value for %s: %s"), key, value);
 637
 638        return 0;
 639}
 640
 641static void read_populate_opts(struct replay_opts **opts_ptr)
 642{
 643        const char *opts_file = git_path(SEQ_OPTS_FILE);
 644
 645        if (!file_exists(opts_file))
 646                return;
 647        if (git_config_from_file(populate_opts_cb, opts_file, *opts_ptr) < 0)
 648                die(_("Malformed options sheet: %s"), opts_file);
 649}
 650
 651static void walk_revs_populate_todo(struct commit_list **todo_list,
 652                                struct replay_opts *opts)
 653{
 654        struct commit *commit;
 655        struct commit_list **next;
 656
 657        prepare_revs(opts);
 658
 659        next = todo_list;
 660        while ((commit = get_revision(opts->revs)))
 661                next = commit_list_append(commit, next);
 662}
 663
 664static int create_seq_dir(void)
 665{
 666        const char *seq_dir = git_path(SEQ_DIR);
 667
 668        if (file_exists(seq_dir)) {
 669                error(_("a cherry-pick or revert is already in progress"));
 670                advise(_("try \"git cherry-pick (--continue | --quit | --abort)\""));
 671                return -1;
 672        }
 673        else if (mkdir(seq_dir, 0777) < 0)
 674                die_errno(_("Could not create sequencer directory %s"), seq_dir);
 675        return 0;
 676}
 677
 678static void save_head(const char *head)
 679{
 680        const char *head_file = git_path(SEQ_HEAD_FILE);
 681        static struct lock_file head_lock;
 682        struct strbuf buf = STRBUF_INIT;
 683        int fd;
 684
 685        fd = hold_lock_file_for_update(&head_lock, head_file, LOCK_DIE_ON_ERROR);
 686        strbuf_addf(&buf, "%s\n", head);
 687        if (write_in_full(fd, buf.buf, buf.len) < 0)
 688                die_errno(_("Could not write to %s"), head_file);
 689        if (commit_lock_file(&head_lock) < 0)
 690                die(_("Error wrapping up %s."), head_file);
 691}
 692
 693static int reset_for_rollback(const unsigned char *sha1)
 694{
 695        const char *argv[4];    /* reset --merge <arg> + NULL */
 696        argv[0] = "reset";
 697        argv[1] = "--merge";
 698        argv[2] = sha1_to_hex(sha1);
 699        argv[3] = NULL;
 700        return run_command_v_opt(argv, RUN_GIT_CMD);
 701}
 702
 703static int rollback_single_pick(void)
 704{
 705        unsigned char head_sha1[20];
 706
 707        if (!file_exists(git_path("CHERRY_PICK_HEAD")) &&
 708            !file_exists(git_path("REVERT_HEAD")))
 709                return error(_("no cherry-pick or revert in progress"));
 710        if (read_ref_full("HEAD", head_sha1, 0, NULL))
 711                return error(_("cannot resolve HEAD"));
 712        if (is_null_sha1(head_sha1))
 713                return error(_("cannot abort from a branch yet to be born"));
 714        return reset_for_rollback(head_sha1);
 715}
 716
 717static int sequencer_rollback(struct replay_opts *opts)
 718{
 719        const char *filename;
 720        FILE *f;
 721        unsigned char sha1[20];
 722        struct strbuf buf = STRBUF_INIT;
 723
 724        filename = git_path(SEQ_HEAD_FILE);
 725        f = fopen(filename, "r");
 726        if (!f && errno == ENOENT) {
 727                /*
 728                 * There is no multiple-cherry-pick in progress.
 729                 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
 730                 * a single-cherry-pick in progress, abort that.
 731                 */
 732                return rollback_single_pick();
 733        }
 734        if (!f)
 735                return error(_("cannot open %s: %s"), filename,
 736                                                strerror(errno));
 737        if (strbuf_getline(&buf, f, '\n')) {
 738                error(_("cannot read %s: %s"), filename, ferror(f) ?
 739                        strerror(errno) : _("unexpected end of file"));
 740                fclose(f);
 741                goto fail;
 742        }
 743        fclose(f);
 744        if (get_sha1_hex(buf.buf, sha1) || buf.buf[40] != '\0') {
 745                error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
 746                        filename);
 747                goto fail;
 748        }
 749        if (reset_for_rollback(sha1))
 750                goto fail;
 751        remove_sequencer_state();
 752        strbuf_release(&buf);
 753        return 0;
 754fail:
 755        strbuf_release(&buf);
 756        return -1;
 757}
 758
 759static void save_todo(struct commit_list *todo_list, struct replay_opts *opts)
 760{
 761        const char *todo_file = git_path(SEQ_TODO_FILE);
 762        static struct lock_file todo_lock;
 763        struct strbuf buf = STRBUF_INIT;
 764        int fd;
 765
 766        fd = hold_lock_file_for_update(&todo_lock, todo_file, LOCK_DIE_ON_ERROR);
 767        if (format_todo(&buf, todo_list, opts) < 0)
 768                die(_("Could not format %s."), todo_file);
 769        if (write_in_full(fd, buf.buf, buf.len) < 0) {
 770                strbuf_release(&buf);
 771                die_errno(_("Could not write to %s"), todo_file);
 772        }
 773        if (commit_lock_file(&todo_lock) < 0) {
 774                strbuf_release(&buf);
 775                die(_("Error wrapping up %s."), todo_file);
 776        }
 777        strbuf_release(&buf);
 778}
 779
 780static void save_opts(struct replay_opts *opts)
 781{
 782        const char *opts_file = git_path(SEQ_OPTS_FILE);
 783
 784        if (opts->no_commit)
 785                git_config_set_in_file(opts_file, "options.no-commit", "true");
 786        if (opts->edit)
 787                git_config_set_in_file(opts_file, "options.edit", "true");
 788        if (opts->signoff)
 789                git_config_set_in_file(opts_file, "options.signoff", "true");
 790        if (opts->record_origin)
 791                git_config_set_in_file(opts_file, "options.record-origin", "true");
 792        if (opts->allow_ff)
 793                git_config_set_in_file(opts_file, "options.allow-ff", "true");
 794        if (opts->mainline) {
 795                struct strbuf buf = STRBUF_INIT;
 796                strbuf_addf(&buf, "%d", opts->mainline);
 797                git_config_set_in_file(opts_file, "options.mainline", buf.buf);
 798                strbuf_release(&buf);
 799        }
 800        if (opts->strategy)
 801                git_config_set_in_file(opts_file, "options.strategy", opts->strategy);
 802        if (opts->xopts) {
 803                int i;
 804                for (i = 0; i < opts->xopts_nr; i++)
 805                        git_config_set_multivar_in_file(opts_file,
 806                                                        "options.strategy-option",
 807                                                        opts->xopts[i], "^$", 0);
 808        }
 809}
 810
 811static int pick_commits(struct commit_list *todo_list, struct replay_opts *opts)
 812{
 813        struct commit_list *cur;
 814        int res;
 815
 816        setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
 817        if (opts->allow_ff)
 818                assert(!(opts->signoff || opts->no_commit ||
 819                                opts->record_origin || opts->edit));
 820        read_and_refresh_cache(opts);
 821
 822        for (cur = todo_list; cur; cur = cur->next) {
 823                save_todo(cur, opts);
 824                res = do_pick_commit(cur->item, opts);
 825                if (res)
 826                        return res;
 827        }
 828
 829        /*
 830         * Sequence of picks finished successfully; cleanup by
 831         * removing the .git/sequencer directory
 832         */
 833        remove_sequencer_state();
 834        return 0;
 835}
 836
 837static int continue_single_pick(void)
 838{
 839        const char *argv[] = { "commit", NULL };
 840
 841        if (!file_exists(git_path("CHERRY_PICK_HEAD")) &&
 842            !file_exists(git_path("REVERT_HEAD")))
 843                return error(_("no cherry-pick or revert in progress"));
 844        return run_command_v_opt(argv, RUN_GIT_CMD);
 845}
 846
 847static int sequencer_continue(struct replay_opts *opts)
 848{
 849        struct commit_list *todo_list = NULL;
 850
 851        if (!file_exists(git_path(SEQ_TODO_FILE)))
 852                return continue_single_pick();
 853        read_populate_opts(&opts);
 854        read_populate_todo(&todo_list, opts);
 855
 856        /* Verify that the conflict has been resolved */
 857        if (file_exists(git_path("CHERRY_PICK_HEAD")) ||
 858            file_exists(git_path("REVERT_HEAD"))) {
 859                int ret = continue_single_pick();
 860                if (ret)
 861                        return ret;
 862        }
 863        if (index_differs_from("HEAD", 0))
 864                return error_dirty_index(opts);
 865        todo_list = todo_list->next;
 866        return pick_commits(todo_list, opts);
 867}
 868
 869static int single_pick(struct commit *cmit, struct replay_opts *opts)
 870{
 871        setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
 872        return do_pick_commit(cmit, opts);
 873}
 874
 875int sequencer_pick_revisions(struct replay_opts *opts)
 876{
 877        struct commit_list *todo_list = NULL;
 878        unsigned char sha1[20];
 879
 880        if (opts->subcommand == REPLAY_NONE)
 881                assert(opts->revs);
 882
 883        read_and_refresh_cache(opts);
 884
 885        /*
 886         * Decide what to do depending on the arguments; a fresh
 887         * cherry-pick should be handled differently from an existing
 888         * one that is being continued
 889         */
 890        if (opts->subcommand == REPLAY_REMOVE_STATE) {
 891                remove_sequencer_state();
 892                return 0;
 893        }
 894        if (opts->subcommand == REPLAY_ROLLBACK)
 895                return sequencer_rollback(opts);
 896        if (opts->subcommand == REPLAY_CONTINUE)
 897                return sequencer_continue(opts);
 898
 899        /*
 900         * If we were called as "git cherry-pick <commit>", just
 901         * cherry-pick/revert it, set CHERRY_PICK_HEAD /
 902         * REVERT_HEAD, and don't touch the sequencer state.
 903         * This means it is possible to cherry-pick in the middle
 904         * of a cherry-pick sequence.
 905         */
 906        if (opts->revs->cmdline.nr == 1 &&
 907            opts->revs->cmdline.rev->whence == REV_CMD_REV &&
 908            opts->revs->no_walk &&
 909            !opts->revs->cmdline.rev->flags) {
 910                struct commit *cmit;
 911                if (prepare_revision_walk(opts->revs))
 912                        die(_("revision walk setup failed"));
 913                cmit = get_revision(opts->revs);
 914                if (!cmit || get_revision(opts->revs))
 915                        die("BUG: expected exactly one commit from walk");
 916                return single_pick(cmit, opts);
 917        }
 918
 919        /*
 920         * Start a new cherry-pick/ revert sequence; but
 921         * first, make sure that an existing one isn't in
 922         * progress
 923         */
 924
 925        walk_revs_populate_todo(&todo_list, opts);
 926        if (create_seq_dir() < 0)
 927                return -1;
 928        if (get_sha1("HEAD", sha1)) {
 929                if (opts->action == REPLAY_REVERT)
 930                        return error(_("Can't revert as initial commit"));
 931                return error(_("Can't cherry-pick into empty head"));
 932        }
 933        save_head(sha1_to_hex(sha1));
 934        save_opts(opts);
 935        return pick_commits(todo_list, opts);
 936}