97fa9f78592b28e741c57d9157a111f13ac99893
   1/*
   2 * "git reset" builtin command
   3 *
   4 * Copyright (c) 2007 Carlos Rica
   5 *
   6 * Based on git-reset.sh, which is
   7 *
   8 * Copyright (c) 2005, 2006 Linus Torvalds and Junio C Hamano
   9 */
  10#include "builtin.h"
  11#include "tag.h"
  12#include "object.h"
  13#include "commit.h"
  14#include "run-command.h"
  15#include "refs.h"
  16#include "diff.h"
  17#include "diffcore.h"
  18#include "tree.h"
  19#include "branch.h"
  20#include "parse-options.h"
  21#include "unpack-trees.h"
  22#include "cache-tree.h"
  23
  24static const char * const git_reset_usage[] = {
  25        N_("git reset [--mixed | --soft | --hard | --merge | --keep] [-q] [<commit>]"),
  26        N_("git reset [-q] <commit> [--] <paths>..."),
  27        N_("git reset --patch [<commit>] [--] [<paths>...]"),
  28        NULL
  29};
  30
  31enum reset_type { MIXED, SOFT, HARD, MERGE, KEEP, NONE };
  32static const char *reset_type_names[] = {
  33        N_("mixed"), N_("soft"), N_("hard"), N_("merge"), N_("keep"), NULL
  34};
  35
  36static inline int is_merge(void)
  37{
  38        return !access(git_path("MERGE_HEAD"), F_OK);
  39}
  40
  41static int reset_index(const unsigned char *sha1, int reset_type, int quiet)
  42{
  43        int nr = 1;
  44        struct tree_desc desc[2];
  45        struct tree *tree;
  46        struct unpack_trees_options opts;
  47
  48        memset(&opts, 0, sizeof(opts));
  49        opts.head_idx = 1;
  50        opts.src_index = &the_index;
  51        opts.dst_index = &the_index;
  52        opts.fn = oneway_merge;
  53        opts.merge = 1;
  54        if (!quiet)
  55                opts.verbose_update = 1;
  56        switch (reset_type) {
  57        case KEEP:
  58        case MERGE:
  59                opts.update = 1;
  60                break;
  61        case HARD:
  62                opts.update = 1;
  63                /* fallthrough */
  64        default:
  65                opts.reset = 1;
  66        }
  67
  68        read_cache_unmerged();
  69
  70        if (reset_type == KEEP) {
  71                unsigned char head_sha1[20];
  72                if (get_sha1("HEAD", head_sha1))
  73                        return error(_("You do not have a valid HEAD."));
  74                if (!fill_tree_descriptor(desc, head_sha1))
  75                        return error(_("Failed to find tree of HEAD."));
  76                nr++;
  77                opts.fn = twoway_merge;
  78        }
  79
  80        if (!fill_tree_descriptor(desc + nr - 1, sha1))
  81                return error(_("Failed to find tree of %s."), sha1_to_hex(sha1));
  82        if (unpack_trees(nr, desc, &opts))
  83                return -1;
  84
  85        if (reset_type == MIXED || reset_type == HARD) {
  86                tree = parse_tree_indirect(sha1);
  87                prime_cache_tree(&active_cache_tree, tree);
  88        }
  89
  90        return 0;
  91}
  92
  93static void print_new_head_line(struct commit *commit)
  94{
  95        const char *hex, *body;
  96
  97        hex = find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV);
  98        printf(_("HEAD is now at %s"), hex);
  99        body = strstr(commit->buffer, "\n\n");
 100        if (body) {
 101                const char *eol;
 102                size_t len;
 103                body += 2;
 104                eol = strchr(body, '\n');
 105                len = eol ? eol - body : strlen(body);
 106                printf(" %.*s\n", (int) len, body);
 107        }
 108        else
 109                printf("\n");
 110}
 111
 112static int update_index_refresh(int fd, struct lock_file *index_lock, int flags)
 113{
 114        if (!index_lock) {
 115                index_lock = xcalloc(1, sizeof(struct lock_file));
 116                fd = hold_locked_index(index_lock, 1);
 117        }
 118
 119        refresh_index(&the_index, (flags), NULL, NULL,
 120                      _("Unstaged changes after reset:"));
 121        if (write_cache(fd, active_cache, active_nr) ||
 122                        commit_locked_index(index_lock))
 123                return error ("Could not refresh index");
 124        return 0;
 125}
 126
 127static void update_index_from_diff(struct diff_queue_struct *q,
 128                struct diff_options *opt, void *data)
 129{
 130        int i;
 131
 132        for (i = 0; i < q->nr; i++) {
 133                struct diff_filespec *one = q->queue[i]->one;
 134                if (one->mode && !is_null_sha1(one->sha1)) {
 135                        struct cache_entry *ce;
 136                        ce = make_cache_entry(one->mode, one->sha1, one->path,
 137                                0, 0);
 138                        if (!ce)
 139                                die(_("make_cache_entry failed for path '%s'"),
 140                                    one->path);
 141                        add_cache_entry(ce, ADD_CACHE_OK_TO_ADD |
 142                                ADD_CACHE_OK_TO_REPLACE);
 143                } else
 144                        remove_file_from_cache(one->path);
 145        }
 146}
 147
 148static int read_from_tree(const char **pathspec, unsigned char *tree_sha1,
 149                          int refresh_flags)
 150{
 151        struct lock_file *lock = xcalloc(1, sizeof(struct lock_file));
 152        int index_fd;
 153        struct diff_options opt;
 154
 155        memset(&opt, 0, sizeof(opt));
 156        diff_tree_setup_paths(pathspec, &opt);
 157        opt.output_format = DIFF_FORMAT_CALLBACK;
 158        opt.format_callback = update_index_from_diff;
 159
 160        index_fd = hold_locked_index(lock, 1);
 161        read_cache();
 162        if (do_diff_cache(tree_sha1, &opt))
 163                return 1;
 164        diffcore_std(&opt);
 165        diff_flush(&opt);
 166        diff_tree_release_paths(&opt);
 167
 168        return update_index_refresh(index_fd, lock, refresh_flags);
 169}
 170
 171static void set_reflog_message(struct strbuf *sb, const char *action,
 172                               const char *rev)
 173{
 174        const char *rla = getenv("GIT_REFLOG_ACTION");
 175
 176        strbuf_reset(sb);
 177        if (rla)
 178                strbuf_addf(sb, "%s: %s", rla, action);
 179        else if (rev)
 180                strbuf_addf(sb, "reset: moving to %s", rev);
 181        else
 182                strbuf_addf(sb, "reset: %s", action);
 183}
 184
 185static void die_if_unmerged_cache(int reset_type)
 186{
 187        if (is_merge() || read_cache() < 0 || unmerged_cache())
 188                die(_("Cannot do a %s reset in the middle of a merge."),
 189                    _(reset_type_names[reset_type]));
 190
 191}
 192
 193static const char **parse_args(const char **argv, const char *prefix, const char **rev_ret)
 194{
 195        const char *rev = "HEAD";
 196        unsigned char unused[20];
 197        /*
 198         * Possible arguments are:
 199         *
 200         * git reset [-opts] <rev> <paths>...
 201         * git reset [-opts] <rev> -- <paths>...
 202         * git reset [-opts] -- <paths>...
 203         * git reset [-opts] <paths>...
 204         *
 205         * At this point, argv points immediately after [-opts].
 206         */
 207
 208        if (argv[0]) {
 209                if (!strcmp(argv[0], "--")) {
 210                        argv++; /* reset to HEAD, possibly with paths */
 211                } else if (argv[1] && !strcmp(argv[1], "--")) {
 212                        rev = argv[0];
 213                        argv += 2;
 214                }
 215                /*
 216                 * Otherwise, argv[0] could be either <rev> or <paths> and
 217                 * has to be unambiguous.
 218                 */
 219                else if (!get_sha1_committish(argv[0], unused)) {
 220                        /*
 221                         * Ok, argv[0] looks like a rev; it should not
 222                         * be a filename.
 223                         */
 224                        verify_non_filename(prefix, argv[0]);
 225                        rev = *argv++;
 226                } else {
 227                        /* Otherwise we treat this as a filename */
 228                        verify_filename(prefix, argv[0], 1);
 229                }
 230        }
 231        *rev_ret = rev;
 232        return argv[0] ? get_pathspec(prefix, argv) : NULL;
 233}
 234
 235static int update_refs(const char *rev, const unsigned char *sha1)
 236{
 237        int update_ref_status;
 238        struct strbuf msg = STRBUF_INIT;
 239        unsigned char *orig = NULL, sha1_orig[20],
 240                *old_orig = NULL, sha1_old_orig[20];
 241
 242        if (!get_sha1("ORIG_HEAD", sha1_old_orig))
 243                old_orig = sha1_old_orig;
 244        if (!get_sha1("HEAD", sha1_orig)) {
 245                orig = sha1_orig;
 246                set_reflog_message(&msg, "updating ORIG_HEAD", NULL);
 247                update_ref(msg.buf, "ORIG_HEAD", orig, old_orig, 0, MSG_ON_ERR);
 248        } else if (old_orig)
 249                delete_ref("ORIG_HEAD", old_orig, 0);
 250        set_reflog_message(&msg, "updating HEAD", rev);
 251        update_ref_status = update_ref(msg.buf, "HEAD", sha1, orig, 0, MSG_ON_ERR);
 252        strbuf_release(&msg);
 253        return update_ref_status;
 254}
 255
 256int cmd_reset(int argc, const char **argv, const char *prefix)
 257{
 258        int reset_type = NONE, update_ref_status = 0, quiet = 0;
 259        int patch_mode = 0;
 260        const char *rev;
 261        unsigned char sha1[20];
 262        const char **pathspec = NULL;
 263        struct commit *commit;
 264        const struct option options[] = {
 265                OPT__QUIET(&quiet, N_("be quiet, only report errors")),
 266                OPT_SET_INT(0, "mixed", &reset_type,
 267                                                N_("reset HEAD and index"), MIXED),
 268                OPT_SET_INT(0, "soft", &reset_type, N_("reset only HEAD"), SOFT),
 269                OPT_SET_INT(0, "hard", &reset_type,
 270                                N_("reset HEAD, index and working tree"), HARD),
 271                OPT_SET_INT(0, "merge", &reset_type,
 272                                N_("reset HEAD, index and working tree"), MERGE),
 273                OPT_SET_INT(0, "keep", &reset_type,
 274                                N_("reset HEAD but keep local changes"), KEEP),
 275                OPT_BOOLEAN('p', "patch", &patch_mode, N_("select hunks interactively")),
 276                OPT_END()
 277        };
 278
 279        git_config(git_default_config, NULL);
 280
 281        argc = parse_options(argc, argv, prefix, options, git_reset_usage,
 282                                                PARSE_OPT_KEEP_DASHDASH);
 283        pathspec = parse_args(argv, prefix, &rev);
 284
 285        if (get_sha1_committish(rev, sha1))
 286                die(_("Failed to resolve '%s' as a valid ref."), rev);
 287
 288        /*
 289         * NOTE: As "git reset $treeish -- $path" should be usable on
 290         * any tree-ish, this is not strictly correct. We are not
 291         * moving the HEAD to any commit; we are merely resetting the
 292         * entries in the index to that of a treeish.
 293         */
 294        commit = lookup_commit_reference(sha1);
 295        if (!commit)
 296                die(_("Could not parse object '%s'."), rev);
 297        hashcpy(sha1, commit->object.sha1);
 298
 299        if (patch_mode) {
 300                if (reset_type != NONE)
 301                        die(_("--patch is incompatible with --{hard,mixed,soft}"));
 302                return run_add_interactive(rev, "--patch=reset", pathspec);
 303        }
 304
 305        /* git reset tree [--] paths... can be used to
 306         * load chosen paths from the tree into the index without
 307         * affecting the working tree nor HEAD. */
 308        if (pathspec) {
 309                if (reset_type == MIXED)
 310                        warning(_("--mixed with paths is deprecated; use 'git reset -- <paths>' instead."));
 311                else if (reset_type != NONE)
 312                        die(_("Cannot do %s reset with paths."),
 313                                        _(reset_type_names[reset_type]));
 314        }
 315        if (reset_type == NONE)
 316                reset_type = MIXED; /* by default */
 317
 318        if (reset_type != SOFT && reset_type != MIXED)
 319                setup_work_tree();
 320
 321        if (reset_type == MIXED && is_bare_repository())
 322                die(_("%s reset is not allowed in a bare repository"),
 323                    _(reset_type_names[reset_type]));
 324
 325        if (pathspec)
 326                return read_from_tree(pathspec, sha1,
 327                                quiet ? REFRESH_QUIET : REFRESH_IN_PORCELAIN);
 328
 329        /* Soft reset does not touch the index file nor the working tree
 330         * at all, but requires them in a good order.  Other resets reset
 331         * the index file to the tree object we are switching to. */
 332        if (reset_type == SOFT || reset_type == KEEP)
 333                die_if_unmerged_cache(reset_type);
 334
 335        if (reset_type != SOFT) {
 336                struct lock_file *lock = xcalloc(1, sizeof(struct lock_file));
 337                int newfd = hold_locked_index(lock, 1);
 338                int err = reset_index(sha1, reset_type, quiet);
 339                if (reset_type == KEEP && !err)
 340                        err = reset_index(sha1, MIXED, quiet);
 341                if (err)
 342                        die(_("Could not reset index file to revision '%s'."), rev);
 343                if (write_cache(newfd, active_cache, active_nr) ||
 344                    commit_locked_index(lock))
 345                        die(_("Could not write new index file."));
 346        }
 347
 348        /* Any resets update HEAD to the head being switched to,
 349         * saving the previous head in ORIG_HEAD before. */
 350        update_ref_status = update_refs(rev, sha1);
 351
 352        switch (reset_type) {
 353        case HARD:
 354                if (!update_ref_status && !quiet)
 355                        print_new_head_line(commit);
 356                break;
 357        case SOFT: /* Nothing else to do. */
 358                break;
 359        case MIXED: /* Report what has not been updated. */
 360                update_index_refresh(0, NULL,
 361                                quiet ? REFRESH_QUIET : REFRESH_IN_PORCELAIN);
 362                break;
 363        }
 364
 365        remove_branch_state();
 366
 367        return update_ref_status;
 368}