builtin / reset.con commit refresh_index: remove unnecessary calls to preload_index() (6c5b7f5)
   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 "config.h"
  12#include "lockfile.h"
  13#include "tag.h"
  14#include "object.h"
  15#include "pretty.h"
  16#include "run-command.h"
  17#include "refs.h"
  18#include "diff.h"
  19#include "diffcore.h"
  20#include "tree.h"
  21#include "branch.h"
  22#include "parse-options.h"
  23#include "unpack-trees.h"
  24#include "cache-tree.h"
  25#include "submodule.h"
  26#include "submodule-config.h"
  27
  28static const char * const git_reset_usage[] = {
  29        N_("git reset [--mixed | --soft | --hard | --merge | --keep] [-q] [<commit>]"),
  30        N_("git reset [-q] [<tree-ish>] [--] <paths>..."),
  31        N_("git reset --patch [<tree-ish>] [--] [<paths>...]"),
  32        NULL
  33};
  34
  35enum reset_type { MIXED, SOFT, HARD, MERGE, KEEP, NONE };
  36static const char *reset_type_names[] = {
  37        N_("mixed"), N_("soft"), N_("hard"), N_("merge"), N_("keep"), NULL
  38};
  39
  40static inline int is_merge(void)
  41{
  42        return !access(git_path_merge_head(the_repository), F_OK);
  43}
  44
  45static int reset_index(const struct object_id *oid, int reset_type, int quiet)
  46{
  47        int i, nr = 0;
  48        struct tree_desc desc[2];
  49        struct tree *tree;
  50        struct unpack_trees_options opts;
  51        int ret = -1;
  52
  53        memset(&opts, 0, sizeof(opts));
  54        opts.head_idx = 1;
  55        opts.src_index = &the_index;
  56        opts.dst_index = &the_index;
  57        opts.fn = oneway_merge;
  58        opts.merge = 1;
  59        if (!quiet)
  60                opts.verbose_update = 1;
  61        switch (reset_type) {
  62        case KEEP:
  63        case MERGE:
  64                opts.update = 1;
  65                break;
  66        case HARD:
  67                opts.update = 1;
  68                /* fallthrough */
  69        default:
  70                opts.reset = 1;
  71        }
  72
  73        read_cache_unmerged();
  74
  75        if (reset_type == KEEP) {
  76                struct object_id head_oid;
  77                if (get_oid("HEAD", &head_oid))
  78                        return error(_("You do not have a valid HEAD."));
  79                if (!fill_tree_descriptor(desc + nr, &head_oid))
  80                        return error(_("Failed to find tree of HEAD."));
  81                nr++;
  82                opts.fn = twoway_merge;
  83        }
  84
  85        if (!fill_tree_descriptor(desc + nr, oid)) {
  86                error(_("Failed to find tree of %s."), oid_to_hex(oid));
  87                goto out;
  88        }
  89        nr++;
  90
  91        if (unpack_trees(nr, desc, &opts))
  92                goto out;
  93
  94        if (reset_type == MIXED || reset_type == HARD) {
  95                tree = parse_tree_indirect(oid);
  96                prime_cache_tree(&the_index, tree);
  97        }
  98
  99        ret = 0;
 100
 101out:
 102        for (i = 0; i < nr; i++)
 103                free((void *)desc[i].buffer);
 104        return ret;
 105}
 106
 107static void print_new_head_line(struct commit *commit)
 108{
 109        struct strbuf buf = STRBUF_INIT;
 110
 111        printf(_("HEAD is now at %s"),
 112                find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV));
 113
 114        pp_commit_easy(CMIT_FMT_ONELINE, commit, &buf);
 115        if (buf.len > 0)
 116                printf(" %s", buf.buf);
 117        putchar('\n');
 118        strbuf_release(&buf);
 119}
 120
 121static void update_index_from_diff(struct diff_queue_struct *q,
 122                struct diff_options *opt, void *data)
 123{
 124        int i;
 125        int intent_to_add = *(int *)data;
 126
 127        for (i = 0; i < q->nr; i++) {
 128                struct diff_filespec *one = q->queue[i]->one;
 129                int is_missing = !(one->mode && !is_null_oid(&one->oid));
 130                struct cache_entry *ce;
 131
 132                if (is_missing && !intent_to_add) {
 133                        remove_file_from_cache(one->path);
 134                        continue;
 135                }
 136
 137                ce = make_cache_entry(&the_index, one->mode, &one->oid, one->path,
 138                                      0, 0);
 139                if (!ce)
 140                        die(_("make_cache_entry failed for path '%s'"),
 141                            one->path);
 142                if (is_missing) {
 143                        ce->ce_flags |= CE_INTENT_TO_ADD;
 144                        set_object_name_for_intent_to_add_entry(ce);
 145                }
 146                add_cache_entry(ce, ADD_CACHE_OK_TO_ADD | ADD_CACHE_OK_TO_REPLACE);
 147        }
 148}
 149
 150static int read_from_tree(const struct pathspec *pathspec,
 151                          struct object_id *tree_oid,
 152                          int intent_to_add)
 153{
 154        struct diff_options opt;
 155
 156        memset(&opt, 0, sizeof(opt));
 157        copy_pathspec(&opt.pathspec, pathspec);
 158        opt.output_format = DIFF_FORMAT_CALLBACK;
 159        opt.format_callback = update_index_from_diff;
 160        opt.format_callback_data = &intent_to_add;
 161        opt.flags.override_submodule_config = 1;
 162        opt.repo = the_repository;
 163
 164        if (do_diff_cache(tree_oid, &opt))
 165                return 1;
 166        diffcore_std(&opt);
 167        diff_flush(&opt);
 168        clear_pathspec(&opt.pathspec);
 169
 170        return 0;
 171}
 172
 173static void set_reflog_message(struct strbuf *sb, const char *action,
 174                               const char *rev)
 175{
 176        const char *rla = getenv("GIT_REFLOG_ACTION");
 177
 178        strbuf_reset(sb);
 179        if (rla)
 180                strbuf_addf(sb, "%s: %s", rla, action);
 181        else if (rev)
 182                strbuf_addf(sb, "reset: moving to %s", rev);
 183        else
 184                strbuf_addf(sb, "reset: %s", action);
 185}
 186
 187static void die_if_unmerged_cache(int reset_type)
 188{
 189        if (is_merge() || unmerged_cache())
 190                die(_("Cannot do a %s reset in the middle of a merge."),
 191                    _(reset_type_names[reset_type]));
 192
 193}
 194
 195static void parse_args(struct pathspec *pathspec,
 196                       const char **argv, const char *prefix,
 197                       int patch_mode,
 198                       const char **rev_ret)
 199{
 200        const char *rev = "HEAD";
 201        struct object_id unused;
 202        /*
 203         * Possible arguments are:
 204         *
 205         * git reset [-opts] [<rev>]
 206         * git reset [-opts] <tree> [<paths>...]
 207         * git reset [-opts] <tree> -- [<paths>...]
 208         * git reset [-opts] -- [<paths>...]
 209         * git reset [-opts] <paths>...
 210         *
 211         * At this point, argv points immediately after [-opts].
 212         */
 213
 214        if (argv[0]) {
 215                if (!strcmp(argv[0], "--")) {
 216                        argv++; /* reset to HEAD, possibly with paths */
 217                } else if (argv[1] && !strcmp(argv[1], "--")) {
 218                        rev = argv[0];
 219                        argv += 2;
 220                }
 221                /*
 222                 * Otherwise, argv[0] could be either <rev> or <paths> and
 223                 * has to be unambiguous. If there is a single argument, it
 224                 * can not be a tree
 225                 */
 226                else if ((!argv[1] && !get_oid_committish(argv[0], &unused)) ||
 227                         (argv[1] && !get_oid_treeish(argv[0], &unused))) {
 228                        /*
 229                         * Ok, argv[0] looks like a commit/tree; it should not
 230                         * be a filename.
 231                         */
 232                        verify_non_filename(prefix, argv[0]);
 233                        rev = *argv++;
 234                } else {
 235                        /* Otherwise we treat this as a filename */
 236                        verify_filename(prefix, argv[0], 1);
 237                }
 238        }
 239        *rev_ret = rev;
 240
 241        if (read_cache() < 0)
 242                die(_("index file corrupt"));
 243
 244        parse_pathspec(pathspec, 0,
 245                       PATHSPEC_PREFER_FULL |
 246                       (patch_mode ? PATHSPEC_PREFIX_ORIGIN : 0),
 247                       prefix, argv);
 248}
 249
 250static int reset_refs(const char *rev, const struct object_id *oid)
 251{
 252        int update_ref_status;
 253        struct strbuf msg = STRBUF_INIT;
 254        struct object_id *orig = NULL, oid_orig,
 255                *old_orig = NULL, oid_old_orig;
 256
 257        if (!get_oid("ORIG_HEAD", &oid_old_orig))
 258                old_orig = &oid_old_orig;
 259        if (!get_oid("HEAD", &oid_orig)) {
 260                orig = &oid_orig;
 261                set_reflog_message(&msg, "updating ORIG_HEAD", NULL);
 262                update_ref(msg.buf, "ORIG_HEAD", orig, old_orig, 0,
 263                           UPDATE_REFS_MSG_ON_ERR);
 264        } else if (old_orig)
 265                delete_ref(NULL, "ORIG_HEAD", old_orig, 0);
 266        set_reflog_message(&msg, "updating HEAD", rev);
 267        update_ref_status = update_ref(msg.buf, "HEAD", oid, orig, 0,
 268                                       UPDATE_REFS_MSG_ON_ERR);
 269        strbuf_release(&msg);
 270        return update_ref_status;
 271}
 272
 273static int git_reset_config(const char *var, const char *value, void *cb)
 274{
 275        if (!strcmp(var, "submodule.recurse"))
 276                return git_default_submodule_config(var, value, cb);
 277
 278        return git_default_config(var, value, cb);
 279}
 280
 281int cmd_reset(int argc, const char **argv, const char *prefix)
 282{
 283        int reset_type = NONE, update_ref_status = 0, quiet = 0;
 284        int patch_mode = 0, unborn;
 285        const char *rev;
 286        struct object_id oid;
 287        struct pathspec pathspec;
 288        int intent_to_add = 0;
 289        const struct option options[] = {
 290                OPT__QUIET(&quiet, N_("be quiet, only report errors")),
 291                OPT_SET_INT(0, "mixed", &reset_type,
 292                                                N_("reset HEAD and index"), MIXED),
 293                OPT_SET_INT(0, "soft", &reset_type, N_("reset only HEAD"), SOFT),
 294                OPT_SET_INT(0, "hard", &reset_type,
 295                                N_("reset HEAD, index and working tree"), HARD),
 296                OPT_SET_INT(0, "merge", &reset_type,
 297                                N_("reset HEAD, index and working tree"), MERGE),
 298                OPT_SET_INT(0, "keep", &reset_type,
 299                                N_("reset HEAD but keep local changes"), KEEP),
 300                { OPTION_CALLBACK, 0, "recurse-submodules", NULL,
 301                            "reset", "control recursive updating of submodules",
 302                            PARSE_OPT_OPTARG, option_parse_recurse_submodules_worktree_updater },
 303                OPT_BOOL('p', "patch", &patch_mode, N_("select hunks interactively")),
 304                OPT_BOOL('N', "intent-to-add", &intent_to_add,
 305                                N_("record only the fact that removed paths will be added later")),
 306                OPT_END()
 307        };
 308
 309        git_config(git_reset_config, NULL);
 310
 311        argc = parse_options(argc, argv, prefix, options, git_reset_usage,
 312                                                PARSE_OPT_KEEP_DASHDASH);
 313        parse_args(&pathspec, argv, prefix, patch_mode, &rev);
 314
 315        unborn = !strcmp(rev, "HEAD") && get_oid("HEAD", &oid);
 316        if (unborn) {
 317                /* reset on unborn branch: treat as reset to empty tree */
 318                oidcpy(&oid, the_hash_algo->empty_tree);
 319        } else if (!pathspec.nr) {
 320                struct commit *commit;
 321                if (get_oid_committish(rev, &oid))
 322                        die(_("Failed to resolve '%s' as a valid revision."), rev);
 323                commit = lookup_commit_reference(the_repository, &oid);
 324                if (!commit)
 325                        die(_("Could not parse object '%s'."), rev);
 326                oidcpy(&oid, &commit->object.oid);
 327        } else {
 328                struct tree *tree;
 329                if (get_oid_treeish(rev, &oid))
 330                        die(_("Failed to resolve '%s' as a valid tree."), rev);
 331                tree = parse_tree_indirect(&oid);
 332                if (!tree)
 333                        die(_("Could not parse object '%s'."), rev);
 334                oidcpy(&oid, &tree->object.oid);
 335        }
 336
 337        if (patch_mode) {
 338                if (reset_type != NONE)
 339                        die(_("--patch is incompatible with --{hard,mixed,soft}"));
 340                return run_add_interactive(rev, "--patch=reset", &pathspec);
 341        }
 342
 343        /* git reset tree [--] paths... can be used to
 344         * load chosen paths from the tree into the index without
 345         * affecting the working tree nor HEAD. */
 346        if (pathspec.nr) {
 347                if (reset_type == MIXED)
 348                        warning(_("--mixed with paths is deprecated; use 'git reset -- <paths>' instead."));
 349                else if (reset_type != NONE)
 350                        die(_("Cannot do %s reset with paths."),
 351                                        _(reset_type_names[reset_type]));
 352        }
 353        if (reset_type == NONE)
 354                reset_type = MIXED; /* by default */
 355
 356        if (reset_type != SOFT && (reset_type != MIXED || get_git_work_tree()))
 357                setup_work_tree();
 358
 359        if (reset_type == MIXED && is_bare_repository())
 360                die(_("%s reset is not allowed in a bare repository"),
 361                    _(reset_type_names[reset_type]));
 362
 363        if (intent_to_add && reset_type != MIXED)
 364                die(_("-N can only be used with --mixed"));
 365
 366        /* Soft reset does not touch the index file nor the working tree
 367         * at all, but requires them in a good order.  Other resets reset
 368         * the index file to the tree object we are switching to. */
 369        if (reset_type == SOFT || reset_type == KEEP)
 370                die_if_unmerged_cache(reset_type);
 371
 372        if (reset_type != SOFT) {
 373                struct lock_file lock = LOCK_INIT;
 374                hold_locked_index(&lock, LOCK_DIE_ON_ERROR);
 375                if (reset_type == MIXED) {
 376                        int flags = quiet ? REFRESH_QUIET : REFRESH_IN_PORCELAIN;
 377                        if (read_from_tree(&pathspec, &oid, intent_to_add))
 378                                return 1;
 379                        if (get_git_work_tree())
 380                                refresh_index(&the_index, flags, NULL, NULL,
 381                                              _("Unstaged changes after reset:"));
 382                } else {
 383                        int err = reset_index(&oid, reset_type, quiet);
 384                        if (reset_type == KEEP && !err)
 385                                err = reset_index(&oid, MIXED, quiet);
 386                        if (err)
 387                                die(_("Could not reset index file to revision '%s'."), rev);
 388                }
 389
 390                if (write_locked_index(&the_index, &lock, COMMIT_LOCK))
 391                        die(_("Could not write new index file."));
 392        }
 393
 394        if (!pathspec.nr && !unborn) {
 395                /* Any resets without paths update HEAD to the head being
 396                 * switched to, saving the previous head in ORIG_HEAD before. */
 397                update_ref_status = reset_refs(rev, &oid);
 398
 399                if (reset_type == HARD && !update_ref_status && !quiet)
 400                        print_new_head_line(lookup_commit_reference(the_repository, &oid));
 401        }
 402        if (!pathspec.nr)
 403                remove_branch_state();
 404
 405        return update_ref_status;
 406}