d47794495abcbb31b39258adee57d4f9c6c3fe75
   1#include "cache.h"
   2#include "builtin.h"
   3#include "object.h"
   4#include "commit.h"
   5#include "tag.h"
   6#include "wt-status.h"
   7#include "run-command.h"
   8#include "exec_cmd.h"
   9#include "utf8.h"
  10#include "parse-options.h"
  11#include "cache-tree.h"
  12#include "diff.h"
  13#include "revision.h"
  14#include "rerere.h"
  15#include "merge-recursive.h"
  16#include "refs.h"
  17
  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
  39static int edit, no_replay, no_commit, mainline, signoff, allow_ff;
  40static enum { REVERT, CHERRY_PICK } action;
  41static struct commit *commit;
  42static const char *commit_name;
  43static int allow_rerere_auto;
  44
  45static const char *me;
  46
  47#define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
  48
  49static char *get_encoding(const char *message);
  50
  51static void parse_args(int argc, const char **argv)
  52{
  53        const char * const * usage_str =
  54                action == REVERT ?  revert_usage : cherry_pick_usage;
  55        unsigned char sha1[20];
  56        int noop;
  57        struct option options[] = {
  58                OPT_BOOLEAN('n', "no-commit", &no_commit, "don't automatically commit"),
  59                OPT_BOOLEAN('e', "edit", &edit, "edit the commit message"),
  60                OPT_BOOLEAN('x', NULL, &no_replay, "append commit name when cherry-picking"),
  61                OPT_BOOLEAN('r', NULL, &noop, "no-op (backward compatibility)"),
  62                OPT_BOOLEAN('s', "signoff", &signoff, "add Signed-off-by:"),
  63                OPT_INTEGER('m', "mainline", &mainline, "parent number"),
  64                OPT_RERERE_AUTOUPDATE(&allow_rerere_auto),
  65                OPT_END(),
  66                OPT_END(),
  67                OPT_END(),
  68        };
  69
  70        if (action == CHERRY_PICK) {
  71                struct option cp_extra[] = {
  72                        OPT_BOOLEAN(0, "ff", &allow_ff, "allow fast-forward"),
  73                        OPT_END(),
  74                };
  75                if (parse_options_concat(options, ARRAY_SIZE(options), cp_extra))
  76                        die("program error");
  77        }
  78
  79        if (parse_options(argc, argv, NULL, options, usage_str, 0) != 1)
  80                usage_with_options(usage_str, options);
  81
  82        commit_name = argv[0];
  83        if (get_sha1(commit_name, sha1))
  84                die ("Cannot find '%s'", commit_name);
  85        commit = lookup_commit_reference(sha1);
  86        if (!commit)
  87                exit(1);
  88}
  89
  90struct commit_message {
  91        char *parent_label;
  92        const char *label;
  93        const char *subject;
  94        char *reencoded_message;
  95        const char *message;
  96};
  97
  98static int get_message(const char *raw_message, struct commit_message *out)
  99{
 100        const char *encoding;
 101        const char *p, *abbrev;
 102        char *q;
 103        int abbrev_len, oneline_len;
 104
 105        if (!raw_message)
 106                return -1;
 107        encoding = get_encoding(raw_message);
 108        if (!encoding)
 109                encoding = "UTF-8";
 110        if (!git_commit_encoding)
 111                git_commit_encoding = "UTF-8";
 112
 113        out->reencoded_message = NULL;
 114        out->message = raw_message;
 115        if (strcmp(encoding, git_commit_encoding))
 116                out->reencoded_message = reencode_string(raw_message,
 117                                        git_commit_encoding, encoding);
 118        if (out->reencoded_message)
 119                out->message = out->reencoded_message;
 120
 121        abbrev = find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV);
 122        abbrev_len = strlen(abbrev);
 123
 124        oneline_len = find_commit_subject(out->message, &p);
 125
 126        out->parent_label = xmalloc(strlen("parent of ") + abbrev_len +
 127                              strlen("... ") + oneline_len + 1);
 128        q = out->parent_label;
 129        q = mempcpy(q, "parent of ", strlen("parent of "));
 130        out->label = q;
 131        q = mempcpy(q, abbrev, abbrev_len);
 132        q = mempcpy(q, "... ", strlen("... "));
 133        out->subject = q;
 134        q = mempcpy(q, p, oneline_len);
 135        *q = '\0';
 136        return 0;
 137}
 138
 139static void free_message(struct commit_message *msg)
 140{
 141        free(msg->parent_label);
 142        free(msg->reencoded_message);
 143}
 144
 145static char *get_encoding(const char *message)
 146{
 147        const char *p = message, *eol;
 148
 149        if (!p)
 150                die ("Could not read commit message of %s",
 151                                sha1_to_hex(commit->object.sha1));
 152        while (*p && *p != '\n') {
 153                for (eol = p + 1; *eol && *eol != '\n'; eol++)
 154                        ; /* do nothing */
 155                if (!prefixcmp(p, "encoding ")) {
 156                        char *result = xmalloc(eol - 8 - p);
 157                        strlcpy(result, p + 9, eol - 8 - p);
 158                        return result;
 159                }
 160                p = eol;
 161                if (*p == '\n')
 162                        p++;
 163        }
 164        return NULL;
 165}
 166
 167static struct lock_file msg_file;
 168static int msg_fd;
 169
 170static void add_to_msg(const char *string)
 171{
 172        int len = strlen(string);
 173        if (write_in_full(msg_fd, string, len) < 0)
 174                die_errno ("Could not write to MERGE_MSG");
 175}
 176
 177static void add_message_to_msg(const char *message)
 178{
 179        const char *p = message;
 180        while (*p && (*p != '\n' || p[1] != '\n'))
 181                p++;
 182
 183        if (!*p)
 184                add_to_msg(sha1_to_hex(commit->object.sha1));
 185
 186        p += 2;
 187        add_to_msg(p);
 188        return;
 189}
 190
 191static void set_author_ident_env(const char *message)
 192{
 193        const char *p = message;
 194        if (!p)
 195                die ("Could not read commit message of %s",
 196                                sha1_to_hex(commit->object.sha1));
 197        while (*p && *p != '\n') {
 198                const char *eol;
 199
 200                for (eol = p; *eol && *eol != '\n'; eol++)
 201                        ; /* do nothing */
 202                if (!prefixcmp(p, "author ")) {
 203                        char *line, *pend, *email, *timestamp;
 204
 205                        p += 7;
 206                        line = xmemdupz(p, eol - p);
 207                        email = strchr(line, '<');
 208                        if (!email)
 209                                die ("Could not extract author email from %s",
 210                                        sha1_to_hex(commit->object.sha1));
 211                        if (email == line)
 212                                pend = line;
 213                        else
 214                                for (pend = email; pend != line + 1 &&
 215                                                isspace(pend[-1]); pend--);
 216                                        ; /* do nothing */
 217                        *pend = '\0';
 218                        email++;
 219                        timestamp = strchr(email, '>');
 220                        if (!timestamp)
 221                                die ("Could not extract author time from %s",
 222                                        sha1_to_hex(commit->object.sha1));
 223                        *timestamp = '\0';
 224                        for (timestamp++; *timestamp && isspace(*timestamp);
 225                                        timestamp++)
 226                                ; /* do nothing */
 227                        setenv("GIT_AUTHOR_NAME", line, 1);
 228                        setenv("GIT_AUTHOR_EMAIL", email, 1);
 229                        setenv("GIT_AUTHOR_DATE", timestamp, 1);
 230                        free(line);
 231                        return;
 232                }
 233                p = eol;
 234                if (*p == '\n')
 235                        p++;
 236        }
 237        die ("No author information found in %s",
 238                        sha1_to_hex(commit->object.sha1));
 239}
 240
 241static char *help_msg(const char *name)
 242{
 243        struct strbuf helpbuf = STRBUF_INIT;
 244        char *msg = getenv("GIT_CHERRY_PICK_HELP");
 245
 246        if (msg)
 247                return msg;
 248
 249        strbuf_addstr(&helpbuf, "  After resolving the conflicts,\n"
 250                "mark the corrected paths with 'git add <paths>' or 'git rm <paths>'\n"
 251                "and commit the result");
 252
 253        if (action == CHERRY_PICK) {
 254                strbuf_addf(&helpbuf, " with: \n"
 255                        "\n"
 256                        "        git commit -c %s\n",
 257                        name);
 258        }
 259        else
 260                strbuf_addch(&helpbuf, '.');
 261        return strbuf_detach(&helpbuf, NULL);
 262}
 263
 264static struct tree *empty_tree(void)
 265{
 266        struct tree *tree = xcalloc(1, sizeof(struct tree));
 267
 268        tree->object.parsed = 1;
 269        tree->object.type = OBJ_TREE;
 270        pretend_sha1_file(NULL, 0, OBJ_TREE, tree->object.sha1);
 271        return tree;
 272}
 273
 274static NORETURN void die_dirty_index(const char *me)
 275{
 276        if (read_cache_unmerged()) {
 277                die_resolve_conflict(me);
 278        } else {
 279                if (advice_commit_before_merge)
 280                        die("Your local changes would be overwritten by %s.\n"
 281                            "Please, commit your changes or stash them to proceed.", me);
 282                else
 283                        die("Your local changes would be overwritten by %s.\n", me);
 284        }
 285}
 286
 287static int fast_forward_to(const unsigned char *to, const unsigned char *from)
 288{
 289        struct ref_lock *ref_lock;
 290
 291        read_cache();
 292        if (checkout_fast_forward(from, to))
 293                exit(1); /* the callee should have complained already */
 294        ref_lock = lock_any_ref_for_update("HEAD", from, 0);
 295        return write_ref_sha1(ref_lock, to, "cherry-pick");
 296}
 297
 298static int revert_or_cherry_pick(int argc, const char **argv)
 299{
 300        unsigned char head[20];
 301        struct commit *base, *next, *parent;
 302        const char *base_label, *next_label;
 303        int i, index_fd, clean;
 304        struct commit_message msg = { NULL, NULL, NULL, NULL, NULL };
 305        char *defmsg = NULL;
 306        struct merge_options o;
 307        struct tree *result, *next_tree, *base_tree, *head_tree;
 308        static struct lock_file index_lock;
 309
 310        git_config(git_default_config, NULL);
 311        me = action == REVERT ? "revert" : "cherry-pick";
 312        setenv(GIT_REFLOG_ACTION, me, 0);
 313        parse_args(argc, argv);
 314
 315        /* this is copied from the shell script, but it's never triggered... */
 316        if (action == REVERT && !no_replay)
 317                die("revert is incompatible with replay");
 318
 319        if (allow_ff) {
 320                if (signoff)
 321                        die("cherry-pick --ff cannot be used with --signoff");
 322                if (no_commit)
 323                        die("cherry-pick --ff cannot be used with --no-commit");
 324                if (no_replay)
 325                        die("cherry-pick --ff cannot be used with -x");
 326                if (edit)
 327                        die("cherry-pick --ff cannot be used with --edit");
 328        }
 329
 330        if (read_cache() < 0)
 331                die("git %s: failed to read the index", me);
 332        if (no_commit) {
 333                /*
 334                 * We do not intend to commit immediately.  We just want to
 335                 * merge the differences in, so let's compute the tree
 336                 * that represents the "current" state for merge-recursive
 337                 * to work on.
 338                 */
 339                if (write_cache_as_tree(head, 0, NULL))
 340                        die ("Your index file is unmerged.");
 341        } else {
 342                if (get_sha1("HEAD", head))
 343                        die ("You do not have a valid HEAD");
 344                if (index_differs_from("HEAD", 0))
 345                        die_dirty_index(me);
 346        }
 347        discard_cache();
 348
 349        if (!commit->parents) {
 350                if (action == REVERT)
 351                        die ("Cannot revert a root commit");
 352                parent = NULL;
 353        }
 354        else if (commit->parents->next) {
 355                /* Reverting or cherry-picking a merge commit */
 356                int cnt;
 357                struct commit_list *p;
 358
 359                if (!mainline)
 360                        die("Commit %s is a merge but no -m option was given.",
 361                            sha1_to_hex(commit->object.sha1));
 362
 363                for (cnt = 1, p = commit->parents;
 364                     cnt != mainline && p;
 365                     cnt++)
 366                        p = p->next;
 367                if (cnt != mainline || !p)
 368                        die("Commit %s does not have parent %d",
 369                            sha1_to_hex(commit->object.sha1), mainline);
 370                parent = p->item;
 371        } else if (0 < mainline)
 372                die("Mainline was specified but commit %s is not a merge.",
 373                    sha1_to_hex(commit->object.sha1));
 374        else
 375                parent = commit->parents->item;
 376
 377        if (allow_ff && !hashcmp(parent->object.sha1, head))
 378                return fast_forward_to(commit->object.sha1, head);
 379
 380        if (parent && parse_commit(parent) < 0)
 381                die("%s: cannot parse parent commit %s",
 382                    me, sha1_to_hex(parent->object.sha1));
 383
 384        if (get_message(commit->buffer, &msg) != 0)
 385                die("Cannot get commit message for %s",
 386                                sha1_to_hex(commit->object.sha1));
 387
 388        /*
 389         * "commit" is an existing commit.  We would want to apply
 390         * the difference it introduces since its first parent "prev"
 391         * on top of the current HEAD if we are cherry-pick.  Or the
 392         * reverse of it if we are revert.
 393         */
 394
 395        defmsg = git_pathdup("MERGE_MSG");
 396        msg_fd = hold_lock_file_for_update(&msg_file, defmsg,
 397                                           LOCK_DIE_ON_ERROR);
 398
 399        index_fd = hold_locked_index(&index_lock, 1);
 400
 401        if (action == REVERT) {
 402                base = commit;
 403                base_label = msg.label;
 404                next = parent;
 405                next_label = msg.parent_label;
 406                add_to_msg("Revert \"");
 407                add_to_msg(msg.subject);
 408                add_to_msg("\"\n\nThis reverts commit ");
 409                add_to_msg(sha1_to_hex(commit->object.sha1));
 410
 411                if (commit->parents->next) {
 412                        add_to_msg(", reversing\nchanges made to ");
 413                        add_to_msg(sha1_to_hex(parent->object.sha1));
 414                }
 415                add_to_msg(".\n");
 416        } else {
 417                base = parent;
 418                base_label = msg.parent_label;
 419                next = commit;
 420                next_label = msg.label;
 421                set_author_ident_env(msg.message);
 422                add_message_to_msg(msg.message);
 423                if (no_replay) {
 424                        add_to_msg("(cherry picked from commit ");
 425                        add_to_msg(sha1_to_hex(commit->object.sha1));
 426                        add_to_msg(")\n");
 427                }
 428        }
 429
 430        read_cache();
 431        init_merge_options(&o);
 432        o.ancestor = base ? base_label : "(empty tree)";
 433        o.branch1 = "HEAD";
 434        o.branch2 = next ? next_label : "(empty tree)";
 435
 436        head_tree = parse_tree_indirect(head);
 437        next_tree = next ? next->tree : empty_tree();
 438        base_tree = base ? base->tree : empty_tree();
 439
 440        clean = merge_trees(&o,
 441                            head_tree,
 442                            next_tree, base_tree, &result);
 443
 444        if (active_cache_changed &&
 445            (write_cache(index_fd, active_cache, active_nr) ||
 446             commit_locked_index(&index_lock)))
 447                die("%s: Unable to write new index file", me);
 448        rollback_lock_file(&index_lock);
 449
 450        if (!clean) {
 451                add_to_msg("\nConflicts:\n\n");
 452                for (i = 0; i < active_nr;) {
 453                        struct cache_entry *ce = active_cache[i++];
 454                        if (ce_stage(ce)) {
 455                                add_to_msg("\t");
 456                                add_to_msg(ce->name);
 457                                add_to_msg("\n");
 458                                while (i < active_nr && !strcmp(ce->name,
 459                                                active_cache[i]->name))
 460                                        i++;
 461                        }
 462                }
 463                if (commit_lock_file(&msg_file) < 0)
 464                        die ("Error wrapping up %s", defmsg);
 465                fprintf(stderr, "Automatic %s failed.%s\n",
 466                        me, help_msg(commit_name));
 467                rerere(allow_rerere_auto);
 468                exit(1);
 469        }
 470        if (commit_lock_file(&msg_file) < 0)
 471                die ("Error wrapping up %s", defmsg);
 472        fprintf(stderr, "Finished one %s.\n", me);
 473
 474        /*
 475         *
 476         * If we are cherry-pick, and if the merge did not result in
 477         * hand-editing, we will hit this commit and inherit the original
 478         * author date and name.
 479         * If we are revert, or if our cherry-pick results in a hand merge,
 480         * we had better say that the current user is responsible for that.
 481         */
 482
 483        if (!no_commit) {
 484                /* 6 is max possible length of our args array including NULL */
 485                const char *args[6];
 486                int i = 0;
 487                args[i++] = "commit";
 488                args[i++] = "-n";
 489                if (signoff)
 490                        args[i++] = "-s";
 491                if (!edit) {
 492                        args[i++] = "-F";
 493                        args[i++] = defmsg;
 494                }
 495                args[i] = NULL;
 496                return execv_git_cmd(args);
 497        }
 498        free_message(&msg);
 499        free(defmsg);
 500
 501        return 0;
 502}
 503
 504int cmd_revert(int argc, const char **argv, const char *prefix)
 505{
 506        if (isatty(0))
 507                edit = 1;
 508        no_replay = 1;
 509        action = REVERT;
 510        return revert_or_cherry_pick(argc, argv);
 511}
 512
 513int cmd_cherry_pick(int argc, const char **argv, const char *prefix)
 514{
 515        no_replay = 0;
 516        action = CHERRY_PICK;
 517        return revert_or_cherry_pick(argc, argv);
 518}