f088e1cc7123442485c5e64d7e3c17aa46332a13
   1#include "cache.h"
   2#include "builtin.h"
   3#include "object.h"
   4#include "commit.h"
   5#include "tag.h"
   6#include "run-command.h"
   7#include "exec_cmd.h"
   8#include "utf8.h"
   9#include "parse-options.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 "dir.h"
  17
  18/*
  19 * This implements the builtins revert and cherry-pick.
  20 *
  21 * Copyright (c) 2007 Johannes E. Schindelin
  22 *
  23 * Based on git-revert.sh, which is
  24 *
  25 * Copyright (c) 2005 Linus Torvalds
  26 * Copyright (c) 2005 Junio C Hamano
  27 */
  28
  29static const char * const revert_usage[] = {
  30        "git revert [options] <commit-ish>",
  31        NULL
  32};
  33
  34static const char * const cherry_pick_usage[] = {
  35        "git cherry-pick [options] <commit-ish>",
  36        NULL
  37};
  38
  39enum replay_action { REVERT, CHERRY_PICK };
  40
  41struct replay_opts {
  42        enum replay_action action;
  43
  44        /* Boolean options */
  45        int edit;
  46        int record_origin;
  47        int no_commit;
  48        int signoff;
  49        int allow_ff;
  50        int allow_rerere_auto;
  51
  52        int mainline;
  53        int commit_argc;
  54        const char **commit_argv;
  55
  56        /* Merge strategy */
  57        const char *strategy;
  58        const char **xopts;
  59        size_t xopts_nr, xopts_alloc;
  60};
  61
  62#define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
  63
  64#define SEQ_DIR         "sequencer"
  65#define SEQ_HEAD_FILE   "sequencer/head"
  66#define SEQ_TODO_FILE   "sequencer/todo"
  67#define SEQ_OPTS_FILE   "sequencer/opts"
  68
  69static const char *action_name(const struct replay_opts *opts)
  70{
  71        return opts->action == REVERT ? "revert" : "cherry-pick";
  72}
  73
  74static char *get_encoding(const char *message);
  75
  76static const char * const *revert_or_cherry_pick_usage(struct replay_opts *opts)
  77{
  78        return opts->action == REVERT ? revert_usage : cherry_pick_usage;
  79}
  80
  81static int option_parse_x(const struct option *opt,
  82                          const char *arg, int unset)
  83{
  84        struct replay_opts **opts_ptr = opt->value;
  85        struct replay_opts *opts = *opts_ptr;
  86
  87        if (unset)
  88                return 0;
  89
  90        ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
  91        opts->xopts[opts->xopts_nr++] = xstrdup(arg);
  92        return 0;
  93}
  94
  95static void verify_opt_compatible(const char *me, const char *base_opt, ...)
  96{
  97        const char *this_opt;
  98        va_list ap;
  99
 100        va_start(ap, base_opt);
 101        while ((this_opt = va_arg(ap, const char *))) {
 102                if (va_arg(ap, int))
 103                        break;
 104        }
 105        va_end(ap);
 106
 107        if (this_opt)
 108                die(_("%s: %s cannot be used with %s"), me, this_opt, base_opt);
 109}
 110
 111static void parse_args(int argc, const char **argv, struct replay_opts *opts)
 112{
 113        const char * const * usage_str = revert_or_cherry_pick_usage(opts);
 114        const char *me = action_name(opts);
 115        int noop;
 116        struct option options[] = {
 117                OPT_BOOLEAN('n', "no-commit", &opts->no_commit, "don't automatically commit"),
 118                OPT_BOOLEAN('e', "edit", &opts->edit, "edit the commit message"),
 119                { OPTION_BOOLEAN, 'r', NULL, &noop, NULL, "no-op (backward compatibility)",
 120                  PARSE_OPT_NOARG | PARSE_OPT_HIDDEN, NULL, 0 },
 121                OPT_BOOLEAN('s', "signoff", &opts->signoff, "add Signed-off-by:"),
 122                OPT_INTEGER('m', "mainline", &opts->mainline, "parent number"),
 123                OPT_RERERE_AUTOUPDATE(&opts->allow_rerere_auto),
 124                OPT_STRING(0, "strategy", &opts->strategy, "strategy", "merge strategy"),
 125                OPT_CALLBACK('X', "strategy-option", &opts, "option",
 126                        "option for merge strategy", option_parse_x),
 127                OPT_END(),
 128                OPT_END(),
 129                OPT_END(),
 130        };
 131
 132        if (opts->action == CHERRY_PICK) {
 133                struct option cp_extra[] = {
 134                        OPT_BOOLEAN('x', NULL, &opts->record_origin, "append commit name"),
 135                        OPT_BOOLEAN(0, "ff", &opts->allow_ff, "allow fast-forward"),
 136                        OPT_END(),
 137                };
 138                if (parse_options_concat(options, ARRAY_SIZE(options), cp_extra))
 139                        die(_("program error"));
 140        }
 141
 142        opts->commit_argc = parse_options(argc, argv, NULL, options, usage_str,
 143                                        PARSE_OPT_KEEP_ARGV0 |
 144                                        PARSE_OPT_KEEP_UNKNOWN);
 145        if (opts->commit_argc < 2)
 146                usage_with_options(usage_str, options);
 147
 148        if (opts->allow_ff)
 149                verify_opt_compatible(me, "--ff",
 150                                "--signoff", opts->signoff,
 151                                "--no-commit", opts->no_commit,
 152                                "-x", opts->record_origin,
 153                                "--edit", opts->edit,
 154                                NULL);
 155        opts->commit_argv = argv;
 156}
 157
 158struct commit_message {
 159        char *parent_label;
 160        const char *label;
 161        const char *subject;
 162        char *reencoded_message;
 163        const char *message;
 164};
 165
 166static int get_message(struct commit *commit, struct commit_message *out)
 167{
 168        const char *encoding;
 169        const char *abbrev, *subject;
 170        int abbrev_len, subject_len;
 171        char *q;
 172
 173        if (!commit->buffer)
 174                return -1;
 175        encoding = get_encoding(commit->buffer);
 176        if (!encoding)
 177                encoding = "UTF-8";
 178        if (!git_commit_encoding)
 179                git_commit_encoding = "UTF-8";
 180
 181        out->reencoded_message = NULL;
 182        out->message = commit->buffer;
 183        if (strcmp(encoding, git_commit_encoding))
 184                out->reencoded_message = reencode_string(commit->buffer,
 185                                        git_commit_encoding, encoding);
 186        if (out->reencoded_message)
 187                out->message = out->reencoded_message;
 188
 189        abbrev = find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV);
 190        abbrev_len = strlen(abbrev);
 191
 192        subject_len = find_commit_subject(out->message, &subject);
 193
 194        out->parent_label = xmalloc(strlen("parent of ") + abbrev_len +
 195                              strlen("... ") + subject_len + 1);
 196        q = out->parent_label;
 197        q = mempcpy(q, "parent of ", strlen("parent of "));
 198        out->label = q;
 199        q = mempcpy(q, abbrev, abbrev_len);
 200        q = mempcpy(q, "... ", strlen("... "));
 201        out->subject = q;
 202        q = mempcpy(q, subject, subject_len);
 203        *q = '\0';
 204        return 0;
 205}
 206
 207static void free_message(struct commit_message *msg)
 208{
 209        free(msg->parent_label);
 210        free(msg->reencoded_message);
 211}
 212
 213static char *get_encoding(const char *message)
 214{
 215        const char *p = message, *eol;
 216
 217        while (*p && *p != '\n') {
 218                for (eol = p + 1; *eol && *eol != '\n'; eol++)
 219                        ; /* do nothing */
 220                if (!prefixcmp(p, "encoding ")) {
 221                        char *result = xmalloc(eol - 8 - p);
 222                        strlcpy(result, p + 9, eol - 8 - p);
 223                        return result;
 224                }
 225                p = eol;
 226                if (*p == '\n')
 227                        p++;
 228        }
 229        return NULL;
 230}
 231
 232static void write_cherry_pick_head(struct commit *commit)
 233{
 234        int fd;
 235        struct strbuf buf = STRBUF_INIT;
 236
 237        strbuf_addf(&buf, "%s\n", sha1_to_hex(commit->object.sha1));
 238
 239        fd = open(git_path("CHERRY_PICK_HEAD"), O_WRONLY | O_CREAT, 0666);
 240        if (fd < 0)
 241                die_errno(_("Could not open '%s' for writing"),
 242                          git_path("CHERRY_PICK_HEAD"));
 243        if (write_in_full(fd, buf.buf, buf.len) != buf.len || close(fd))
 244                die_errno(_("Could not write to '%s'"), git_path("CHERRY_PICK_HEAD"));
 245        strbuf_release(&buf);
 246}
 247
 248static void print_advice(void)
 249{
 250        char *msg = getenv("GIT_CHERRY_PICK_HELP");
 251
 252        if (msg) {
 253                fprintf(stderr, "%s\n", msg);
 254                /*
 255                 * A conflict has occured but the porcelain
 256                 * (typically rebase --interactive) wants to take care
 257                 * of the commit itself so remove CHERRY_PICK_HEAD
 258                 */
 259                unlink(git_path("CHERRY_PICK_HEAD"));
 260                return;
 261        }
 262
 263        advise("after resolving the conflicts, mark the corrected paths");
 264        advise("with 'git add <paths>' or 'git rm <paths>'");
 265        advise("and commit the result with 'git commit'");
 266}
 267
 268static void write_message(struct strbuf *msgbuf, const char *filename)
 269{
 270        static struct lock_file msg_file;
 271
 272        int msg_fd = hold_lock_file_for_update(&msg_file, filename,
 273                                               LOCK_DIE_ON_ERROR);
 274        if (write_in_full(msg_fd, msgbuf->buf, msgbuf->len) < 0)
 275                die_errno(_("Could not write to %s."), filename);
 276        strbuf_release(msgbuf);
 277        if (commit_lock_file(&msg_file) < 0)
 278                die(_("Error wrapping up %s"), filename);
 279}
 280
 281static struct tree *empty_tree(void)
 282{
 283        struct tree *tree = xcalloc(1, sizeof(struct tree));
 284
 285        tree->object.parsed = 1;
 286        tree->object.type = OBJ_TREE;
 287        pretend_sha1_file(NULL, 0, OBJ_TREE, tree->object.sha1);
 288        return tree;
 289}
 290
 291static NORETURN void die_dirty_index(struct replay_opts *opts)
 292{
 293        if (read_cache_unmerged()) {
 294                die_resolve_conflict(action_name(opts));
 295        } else {
 296                if (advice_commit_before_merge) {
 297                        if (opts->action == REVERT)
 298                                die(_("Your local changes would be overwritten by revert.\n"
 299                                          "Please, commit your changes or stash them to proceed."));
 300                        else
 301                                die(_("Your local changes would be overwritten by cherry-pick.\n"
 302                                          "Please, commit your changes or stash them to proceed."));
 303                } else {
 304                        if (opts->action == REVERT)
 305                                die(_("Your local changes would be overwritten by revert.\n"));
 306                        else
 307                                die(_("Your local changes would be overwritten by cherry-pick.\n"));
 308                }
 309        }
 310}
 311
 312static int fast_forward_to(const unsigned char *to, const unsigned char *from)
 313{
 314        struct ref_lock *ref_lock;
 315
 316        read_cache();
 317        if (checkout_fast_forward(from, to))
 318                exit(1); /* the callee should have complained already */
 319        ref_lock = lock_any_ref_for_update("HEAD", from, 0);
 320        return write_ref_sha1(ref_lock, to, "cherry-pick");
 321}
 322
 323static int do_recursive_merge(struct commit *base, struct commit *next,
 324                              const char *base_label, const char *next_label,
 325                              unsigned char *head, struct strbuf *msgbuf,
 326                              struct replay_opts *opts)
 327{
 328        struct merge_options o;
 329        struct tree *result, *next_tree, *base_tree, *head_tree;
 330        int clean, index_fd;
 331        const char **xopt;
 332        static struct lock_file index_lock;
 333
 334        index_fd = hold_locked_index(&index_lock, 1);
 335
 336        read_cache();
 337
 338        init_merge_options(&o);
 339        o.ancestor = base ? base_label : "(empty tree)";
 340        o.branch1 = "HEAD";
 341        o.branch2 = next ? next_label : "(empty tree)";
 342
 343        head_tree = parse_tree_indirect(head);
 344        next_tree = next ? next->tree : empty_tree();
 345        base_tree = base ? base->tree : empty_tree();
 346
 347        for (xopt = opts->xopts; xopt != opts->xopts + opts->xopts_nr; xopt++)
 348                parse_merge_opt(&o, *xopt);
 349
 350        clean = merge_trees(&o,
 351                            head_tree,
 352                            next_tree, base_tree, &result);
 353
 354        if (active_cache_changed &&
 355            (write_cache(index_fd, active_cache, active_nr) ||
 356             commit_locked_index(&index_lock)))
 357                /* TRANSLATORS: %s will be "revert" or "cherry-pick" */
 358                die(_("%s: Unable to write new index file"), action_name(opts));
 359        rollback_lock_file(&index_lock);
 360
 361        if (!clean) {
 362                int i;
 363                strbuf_addstr(msgbuf, "\nConflicts:\n\n");
 364                for (i = 0; i < active_nr;) {
 365                        struct cache_entry *ce = active_cache[i++];
 366                        if (ce_stage(ce)) {
 367                                strbuf_addch(msgbuf, '\t');
 368                                strbuf_addstr(msgbuf, ce->name);
 369                                strbuf_addch(msgbuf, '\n');
 370                                while (i < active_nr && !strcmp(ce->name,
 371                                                active_cache[i]->name))
 372                                        i++;
 373                        }
 374                }
 375        }
 376
 377        return !clean;
 378}
 379
 380/*
 381 * If we are cherry-pick, and if the merge did not result in
 382 * hand-editing, we will hit this commit and inherit the original
 383 * author date and name.
 384 * If we are revert, or if our cherry-pick results in a hand merge,
 385 * we had better say that the current user is responsible for that.
 386 */
 387static int run_git_commit(const char *defmsg, struct replay_opts *opts)
 388{
 389        /* 6 is max possible length of our args array including NULL */
 390        const char *args[6];
 391        int i = 0;
 392
 393        args[i++] = "commit";
 394        args[i++] = "-n";
 395        if (opts->signoff)
 396                args[i++] = "-s";
 397        if (!opts->edit) {
 398                args[i++] = "-F";
 399                args[i++] = defmsg;
 400        }
 401        args[i] = NULL;
 402
 403        return run_command_v_opt(args, RUN_GIT_CMD);
 404}
 405
 406static int do_pick_commit(struct commit *commit, struct replay_opts *opts)
 407{
 408        unsigned char head[20];
 409        struct commit *base, *next, *parent;
 410        const char *base_label, *next_label;
 411        struct commit_message msg = { NULL, NULL, NULL, NULL, NULL };
 412        char *defmsg = NULL;
 413        struct strbuf msgbuf = STRBUF_INIT;
 414        int res;
 415
 416        if (opts->no_commit) {
 417                /*
 418                 * We do not intend to commit immediately.  We just want to
 419                 * merge the differences in, so let's compute the tree
 420                 * that represents the "current" state for merge-recursive
 421                 * to work on.
 422                 */
 423                if (write_cache_as_tree(head, 0, NULL))
 424                        die (_("Your index file is unmerged."));
 425        } else {
 426                if (get_sha1("HEAD", head))
 427                        die (_("You do not have a valid HEAD"));
 428                if (index_differs_from("HEAD", 0))
 429                        die_dirty_index(opts);
 430        }
 431        discard_cache();
 432
 433        if (!commit->parents) {
 434                parent = NULL;
 435        }
 436        else if (commit->parents->next) {
 437                /* Reverting or cherry-picking a merge commit */
 438                int cnt;
 439                struct commit_list *p;
 440
 441                if (!opts->mainline)
 442                        die(_("Commit %s is a merge but no -m option was given."),
 443                            sha1_to_hex(commit->object.sha1));
 444
 445                for (cnt = 1, p = commit->parents;
 446                     cnt != opts->mainline && p;
 447                     cnt++)
 448                        p = p->next;
 449                if (cnt != opts->mainline || !p)
 450                        die(_("Commit %s does not have parent %d"),
 451                            sha1_to_hex(commit->object.sha1), opts->mainline);
 452                parent = p->item;
 453        } else if (0 < opts->mainline)
 454                die(_("Mainline was specified but commit %s is not a merge."),
 455                    sha1_to_hex(commit->object.sha1));
 456        else
 457                parent = commit->parents->item;
 458
 459        if (opts->allow_ff && parent && !hashcmp(parent->object.sha1, head))
 460                return fast_forward_to(commit->object.sha1, head);
 461
 462        if (parent && parse_commit(parent) < 0)
 463                /* TRANSLATORS: The first %s will be "revert" or
 464                   "cherry-pick", the second %s a SHA1 */
 465                die(_("%s: cannot parse parent commit %s"),
 466                    action_name(opts), sha1_to_hex(parent->object.sha1));
 467
 468        if (get_message(commit, &msg) != 0)
 469                die(_("Cannot get commit message for %s"),
 470                                sha1_to_hex(commit->object.sha1));
 471
 472        /*
 473         * "commit" is an existing commit.  We would want to apply
 474         * the difference it introduces since its first parent "prev"
 475         * on top of the current HEAD if we are cherry-pick.  Or the
 476         * reverse of it if we are revert.
 477         */
 478
 479        defmsg = git_pathdup("MERGE_MSG");
 480
 481        if (opts->action == REVERT) {
 482                base = commit;
 483                base_label = msg.label;
 484                next = parent;
 485                next_label = msg.parent_label;
 486                strbuf_addstr(&msgbuf, "Revert \"");
 487                strbuf_addstr(&msgbuf, msg.subject);
 488                strbuf_addstr(&msgbuf, "\"\n\nThis reverts commit ");
 489                strbuf_addstr(&msgbuf, sha1_to_hex(commit->object.sha1));
 490
 491                if (commit->parents && commit->parents->next) {
 492                        strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
 493                        strbuf_addstr(&msgbuf, sha1_to_hex(parent->object.sha1));
 494                }
 495                strbuf_addstr(&msgbuf, ".\n");
 496        } else {
 497                const char *p;
 498
 499                base = parent;
 500                base_label = msg.parent_label;
 501                next = commit;
 502                next_label = msg.label;
 503
 504                /*
 505                 * Append the commit log message to msgbuf; it starts
 506                 * after the tree, parent, author, committer
 507                 * information followed by "\n\n".
 508                 */
 509                p = strstr(msg.message, "\n\n");
 510                if (p) {
 511                        p += 2;
 512                        strbuf_addstr(&msgbuf, p);
 513                }
 514
 515                if (opts->record_origin) {
 516                        strbuf_addstr(&msgbuf, "(cherry picked from commit ");
 517                        strbuf_addstr(&msgbuf, sha1_to_hex(commit->object.sha1));
 518                        strbuf_addstr(&msgbuf, ")\n");
 519                }
 520                if (!opts->no_commit)
 521                        write_cherry_pick_head(commit);
 522        }
 523
 524        if (!opts->strategy || !strcmp(opts->strategy, "recursive") || opts->action == REVERT) {
 525                res = do_recursive_merge(base, next, base_label, next_label,
 526                                         head, &msgbuf, opts);
 527                write_message(&msgbuf, defmsg);
 528        } else {
 529                struct commit_list *common = NULL;
 530                struct commit_list *remotes = NULL;
 531
 532                write_message(&msgbuf, defmsg);
 533
 534                commit_list_insert(base, &common);
 535                commit_list_insert(next, &remotes);
 536                res = try_merge_command(opts->strategy, opts->xopts_nr, opts->xopts,
 537                                        common, sha1_to_hex(head), remotes);
 538                free_commit_list(common);
 539                free_commit_list(remotes);
 540        }
 541
 542        if (res) {
 543                error(opts->action == REVERT
 544                      ? _("could not revert %s... %s")
 545                      : _("could not apply %s... %s"),
 546                      find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV),
 547                      msg.subject);
 548                print_advice();
 549                rerere(opts->allow_rerere_auto);
 550        } else {
 551                if (!opts->no_commit)
 552                        res = run_git_commit(defmsg, opts);
 553        }
 554
 555        free_message(&msg);
 556        free(defmsg);
 557
 558        return res;
 559}
 560
 561static void prepare_revs(struct rev_info *revs, struct replay_opts *opts)
 562{
 563        int argc;
 564
 565        init_revisions(revs, NULL);
 566        revs->no_walk = 1;
 567        if (opts->action != REVERT)
 568                revs->reverse = 1;
 569
 570        argc = setup_revisions(opts->commit_argc, opts->commit_argv, revs, NULL);
 571        if (argc > 1)
 572                usage(*revert_or_cherry_pick_usage(opts));
 573
 574        if (prepare_revision_walk(revs))
 575                die(_("revision walk setup failed"));
 576
 577        if (!revs->commits)
 578                die(_("empty commit set passed"));
 579}
 580
 581static void read_and_refresh_cache(struct replay_opts *opts)
 582{
 583        static struct lock_file index_lock;
 584        int index_fd = hold_locked_index(&index_lock, 0);
 585        if (read_index_preload(&the_index, NULL) < 0)
 586                die(_("git %s: failed to read the index"), action_name(opts));
 587        refresh_index(&the_index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
 588        if (the_index.cache_changed) {
 589                if (write_index(&the_index, index_fd) ||
 590                    commit_locked_index(&index_lock))
 591                        die(_("git %s: failed to refresh the index"), action_name(opts));
 592        }
 593        rollback_lock_file(&index_lock);
 594}
 595
 596/*
 597 * Append a commit to the end of the commit_list.
 598 *
 599 * next starts by pointing to the variable that holds the head of an
 600 * empty commit_list, and is updated to point to the "next" field of
 601 * the last item on the list as new commits are appended.
 602 *
 603 * Usage example:
 604 *
 605 *     struct commit_list *list;
 606 *     struct commit_list **next = &list;
 607 *
 608 *     next = commit_list_append(c1, next);
 609 *     next = commit_list_append(c2, next);
 610 *     assert(commit_list_count(list) == 2);
 611 *     return list;
 612 */
 613struct commit_list **commit_list_append(struct commit *commit,
 614                                        struct commit_list **next)
 615{
 616        struct commit_list *new = xmalloc(sizeof(struct commit_list));
 617        new->item = commit;
 618        *next = new;
 619        new->next = NULL;
 620        return &new->next;
 621}
 622
 623static int format_todo(struct strbuf *buf, struct commit_list *todo_list,
 624                struct replay_opts *opts)
 625{
 626        struct commit_list *cur = NULL;
 627        struct commit_message msg = { NULL, NULL, NULL, NULL, NULL };
 628        const char *sha1_abbrev = NULL;
 629        const char *action_str = opts->action == REVERT ? "revert" : "pick";
 630
 631        for (cur = todo_list; cur; cur = cur->next) {
 632                sha1_abbrev = find_unique_abbrev(cur->item->object.sha1, DEFAULT_ABBREV);
 633                if (get_message(cur->item, &msg))
 634                        return error(_("Cannot get commit message for %s"), sha1_abbrev);
 635                strbuf_addf(buf, "%s %s %s\n", action_str, sha1_abbrev, msg.subject);
 636        }
 637        return 0;
 638}
 639
 640static void walk_revs_populate_todo(struct commit_list **todo_list,
 641                                struct replay_opts *opts)
 642{
 643        struct rev_info revs;
 644        struct commit *commit;
 645        struct commit_list **next;
 646
 647        prepare_revs(&revs, opts);
 648
 649        next = todo_list;
 650        while ((commit = get_revision(&revs)))
 651                next = commit_list_append(commit, next);
 652}
 653
 654static void create_seq_dir(void)
 655{
 656        const char *seq_dir = git_path(SEQ_DIR);
 657
 658        if (!(file_exists(seq_dir) && is_directory(seq_dir))
 659                && mkdir(seq_dir, 0777) < 0)
 660                die_errno(_("Could not create sequencer directory '%s'."), seq_dir);
 661}
 662
 663static void save_head(const char *head)
 664{
 665        const char *head_file = git_path(SEQ_HEAD_FILE);
 666        static struct lock_file head_lock;
 667        struct strbuf buf = STRBUF_INIT;
 668        int fd;
 669
 670        fd = hold_lock_file_for_update(&head_lock, head_file, LOCK_DIE_ON_ERROR);
 671        strbuf_addf(&buf, "%s\n", head);
 672        if (write_in_full(fd, buf.buf, buf.len) < 0)
 673                die_errno(_("Could not write to %s."), head_file);
 674        if (commit_lock_file(&head_lock) < 0)
 675                die(_("Error wrapping up %s."), head_file);
 676}
 677
 678static void save_todo(struct commit_list *todo_list, struct replay_opts *opts)
 679{
 680        const char *todo_file = git_path(SEQ_TODO_FILE);
 681        static struct lock_file todo_lock;
 682        struct strbuf buf = STRBUF_INIT;
 683        int fd;
 684
 685        fd = hold_lock_file_for_update(&todo_lock, todo_file, LOCK_DIE_ON_ERROR);
 686        if (format_todo(&buf, todo_list, opts) < 0)
 687                die(_("Could not format %s."), todo_file);
 688        if (write_in_full(fd, buf.buf, buf.len) < 0) {
 689                strbuf_release(&buf);
 690                die_errno(_("Could not write to %s."), todo_file);
 691        }
 692        if (commit_lock_file(&todo_lock) < 0) {
 693                strbuf_release(&buf);
 694                die(_("Error wrapping up %s."), todo_file);
 695        }
 696        strbuf_release(&buf);
 697}
 698
 699static void save_opts(struct replay_opts *opts)
 700{
 701        const char *opts_file = git_path(SEQ_OPTS_FILE);
 702
 703        if (opts->no_commit)
 704                git_config_set_in_file(opts_file, "options.no-commit", "true");
 705        if (opts->edit)
 706                git_config_set_in_file(opts_file, "options.edit", "true");
 707        if (opts->signoff)
 708                git_config_set_in_file(opts_file, "options.signoff", "true");
 709        if (opts->record_origin)
 710                git_config_set_in_file(opts_file, "options.record-origin", "true");
 711        if (opts->allow_ff)
 712                git_config_set_in_file(opts_file, "options.allow-ff", "true");
 713        if (opts->mainline) {
 714                struct strbuf buf = STRBUF_INIT;
 715                strbuf_addf(&buf, "%d", opts->mainline);
 716                git_config_set_in_file(opts_file, "options.mainline", buf.buf);
 717                strbuf_release(&buf);
 718        }
 719        if (opts->strategy)
 720                git_config_set_in_file(opts_file, "options.strategy", opts->strategy);
 721        if (opts->xopts) {
 722                int i;
 723                for (i = 0; i < opts->xopts_nr; i++)
 724                        git_config_set_multivar_in_file(opts_file,
 725                                                        "options.strategy-option",
 726                                                        opts->xopts[i], "^$", 0);
 727        }
 728}
 729
 730static int pick_commits(struct commit_list *todo_list, struct replay_opts *opts)
 731{
 732        struct strbuf buf = STRBUF_INIT;
 733        struct commit_list *cur;
 734        int res;
 735
 736        setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
 737        if (opts->allow_ff)
 738                assert(!(opts->signoff || opts->no_commit ||
 739                                opts->record_origin || opts->edit));
 740        read_and_refresh_cache(opts);
 741
 742        for (cur = todo_list; cur; cur = cur->next) {
 743                save_todo(cur, opts);
 744                res = do_pick_commit(cur->item, opts);
 745                if (res)
 746                        return res;
 747        }
 748
 749        /*
 750         * Sequence of picks finished successfully; cleanup by
 751         * removing the .git/sequencer directory
 752         */
 753        strbuf_addf(&buf, "%s", git_path(SEQ_DIR));
 754        remove_dir_recursively(&buf, 0);
 755        strbuf_release(&buf);
 756        return 0;
 757}
 758
 759static int pick_revisions(struct replay_opts *opts)
 760{
 761        struct commit_list *todo_list = NULL;
 762        unsigned char sha1[20];
 763
 764        read_and_refresh_cache(opts);
 765
 766        /*
 767         * Decide what to do depending on the arguments; a fresh
 768         * cherry-pick should be handled differently from an existing
 769         * one that is being continued
 770         */
 771        walk_revs_populate_todo(&todo_list, opts);
 772        create_seq_dir();
 773        if (get_sha1("HEAD", sha1)) {
 774                if (opts->action == REVERT)
 775                        die(_("Can't revert as initial commit"));
 776                die(_("Can't cherry-pick into empty head"));
 777        }
 778        save_head(sha1_to_hex(sha1));
 779        save_opts(opts);
 780
 781        return pick_commits(todo_list, opts);
 782}
 783
 784int cmd_revert(int argc, const char **argv, const char *prefix)
 785{
 786        struct replay_opts opts;
 787
 788        memset(&opts, 0, sizeof(opts));
 789        if (isatty(0))
 790                opts.edit = 1;
 791        opts.action = REVERT;
 792        git_config(git_default_config, NULL);
 793        parse_args(argc, argv, &opts);
 794        return pick_revisions(&opts);
 795}
 796
 797int cmd_cherry_pick(int argc, const char **argv, const char *prefix)
 798{
 799        struct replay_opts opts;
 800
 801        memset(&opts, 0, sizeof(opts));
 802        opts.action = CHERRY_PICK;
 803        git_config(git_default_config, NULL);
 804        parse_args(argc, argv, &opts);
 805        return pick_revisions(&opts);
 806}