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