builtin / reset.con commit Merge branch 'mh/avoid-rewriting-packed-refs' into maint (02abc6b)
   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 "commit.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(), 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        const char *hex, *body;
 110        const char *msg;
 111
 112        hex = find_unique_abbrev(commit->object.oid.hash, DEFAULT_ABBREV);
 113        printf(_("HEAD is now at %s"), hex);
 114        msg = logmsg_reencode(commit, NULL, get_log_output_encoding());
 115        body = strstr(msg, "\n\n");
 116        if (body) {
 117                const char *eol;
 118                size_t len;
 119                body = skip_blank_lines(body + 2);
 120                eol = strchr(body, '\n');
 121                len = eol ? eol - body : strlen(body);
 122                printf(" %.*s\n", (int) len, body);
 123        }
 124        else
 125                printf("\n");
 126        unuse_commit_buffer(commit, msg);
 127}
 128
 129static void update_index_from_diff(struct diff_queue_struct *q,
 130                struct diff_options *opt, void *data)
 131{
 132        int i;
 133        int intent_to_add = *(int *)data;
 134
 135        for (i = 0; i < q->nr; i++) {
 136                struct diff_filespec *one = q->queue[i]->one;
 137                int is_missing = !(one->mode && !is_null_oid(&one->oid));
 138                struct cache_entry *ce;
 139
 140                if (is_missing && !intent_to_add) {
 141                        remove_file_from_cache(one->path);
 142                        continue;
 143                }
 144
 145                ce = make_cache_entry(one->mode, one->oid.hash, one->path,
 146                                      0, 0);
 147                if (!ce)
 148                        die(_("make_cache_entry failed for path '%s'"),
 149                            one->path);
 150                if (is_missing) {
 151                        ce->ce_flags |= CE_INTENT_TO_ADD;
 152                        set_object_name_for_intent_to_add_entry(ce);
 153                }
 154                add_cache_entry(ce, ADD_CACHE_OK_TO_ADD | ADD_CACHE_OK_TO_REPLACE);
 155        }
 156}
 157
 158static int read_from_tree(const struct pathspec *pathspec,
 159                          struct object_id *tree_oid,
 160                          int intent_to_add)
 161{
 162        struct diff_options opt;
 163
 164        memset(&opt, 0, sizeof(opt));
 165        copy_pathspec(&opt.pathspec, pathspec);
 166        opt.output_format = DIFF_FORMAT_CALLBACK;
 167        opt.format_callback = update_index_from_diff;
 168        opt.format_callback_data = &intent_to_add;
 169        opt.flags |= DIFF_OPT_OVERRIDE_SUBMODULE_CONFIG;
 170
 171        if (do_diff_cache(tree_oid, &opt))
 172                return 1;
 173        diffcore_std(&opt);
 174        diff_flush(&opt);
 175        clear_pathspec(&opt.pathspec);
 176
 177        return 0;
 178}
 179
 180static void set_reflog_message(struct strbuf *sb, const char *action,
 181                               const char *rev)
 182{
 183        const char *rla = getenv("GIT_REFLOG_ACTION");
 184
 185        strbuf_reset(sb);
 186        if (rla)
 187                strbuf_addf(sb, "%s: %s", rla, action);
 188        else if (rev)
 189                strbuf_addf(sb, "reset: moving to %s", rev);
 190        else
 191                strbuf_addf(sb, "reset: %s", action);
 192}
 193
 194static void die_if_unmerged_cache(int reset_type)
 195{
 196        if (is_merge() || unmerged_cache())
 197                die(_("Cannot do a %s reset in the middle of a merge."),
 198                    _(reset_type_names[reset_type]));
 199
 200}
 201
 202static void parse_args(struct pathspec *pathspec,
 203                       const char **argv, const char *prefix,
 204                       int patch_mode,
 205                       const char **rev_ret)
 206{
 207        const char *rev = "HEAD";
 208        struct object_id unused;
 209        /*
 210         * Possible arguments are:
 211         *
 212         * git reset [-opts] [<rev>]
 213         * git reset [-opts] <tree> [<paths>...]
 214         * git reset [-opts] <tree> -- [<paths>...]
 215         * git reset [-opts] -- [<paths>...]
 216         * git reset [-opts] <paths>...
 217         *
 218         * At this point, argv points immediately after [-opts].
 219         */
 220
 221        if (argv[0]) {
 222                if (!strcmp(argv[0], "--")) {
 223                        argv++; /* reset to HEAD, possibly with paths */
 224                } else if (argv[1] && !strcmp(argv[1], "--")) {
 225                        rev = argv[0];
 226                        argv += 2;
 227                }
 228                /*
 229                 * Otherwise, argv[0] could be either <rev> or <paths> and
 230                 * has to be unambiguous. If there is a single argument, it
 231                 * can not be a tree
 232                 */
 233                else if ((!argv[1] && !get_oid_committish(argv[0], &unused)) ||
 234                         (argv[1] && !get_oid_treeish(argv[0], &unused))) {
 235                        /*
 236                         * Ok, argv[0] looks like a commit/tree; it should not
 237                         * be a filename.
 238                         */
 239                        verify_non_filename(prefix, argv[0]);
 240                        rev = *argv++;
 241                } else {
 242                        /* Otherwise we treat this as a filename */
 243                        verify_filename(prefix, argv[0], 1);
 244                }
 245        }
 246        *rev_ret = rev;
 247
 248        if (read_cache() < 0)
 249                die(_("index file corrupt"));
 250
 251        parse_pathspec(pathspec, 0,
 252                       PATHSPEC_PREFER_FULL |
 253                       (patch_mode ? PATHSPEC_PREFIX_ORIGIN : 0),
 254                       prefix, argv);
 255}
 256
 257static int reset_refs(const char *rev, const struct object_id *oid)
 258{
 259        int update_ref_status;
 260        struct strbuf msg = STRBUF_INIT;
 261        struct object_id *orig = NULL, oid_orig,
 262                *old_orig = NULL, oid_old_orig;
 263
 264        if (!get_oid("ORIG_HEAD", &oid_old_orig))
 265                old_orig = &oid_old_orig;
 266        if (!get_oid("HEAD", &oid_orig)) {
 267                orig = &oid_orig;
 268                set_reflog_message(&msg, "updating ORIG_HEAD", NULL);
 269                update_ref_oid(msg.buf, "ORIG_HEAD", orig, old_orig, 0,
 270                           UPDATE_REFS_MSG_ON_ERR);
 271        } else if (old_orig)
 272                delete_ref(NULL, "ORIG_HEAD", old_orig->hash, 0);
 273        set_reflog_message(&msg, "updating HEAD", rev);
 274        update_ref_status = update_ref_oid(msg.buf, "HEAD", oid, orig, 0,
 275                                       UPDATE_REFS_MSG_ON_ERR);
 276        strbuf_release(&msg);
 277        return update_ref_status;
 278}
 279
 280static int git_reset_config(const char *var, const char *value, void *cb)
 281{
 282        if (!strcmp(var, "submodule.recurse"))
 283                return git_default_submodule_config(var, value, cb);
 284
 285        return git_default_config(var, value, cb);
 286}
 287
 288int cmd_reset(int argc, const char **argv, const char *prefix)
 289{
 290        int reset_type = NONE, update_ref_status = 0, quiet = 0;
 291        int patch_mode = 0, unborn;
 292        const char *rev;
 293        struct object_id oid;
 294        struct pathspec pathspec;
 295        int intent_to_add = 0;
 296        const struct option options[] = {
 297                OPT__QUIET(&quiet, N_("be quiet, only report errors")),
 298                OPT_SET_INT(0, "mixed", &reset_type,
 299                                                N_("reset HEAD and index"), MIXED),
 300                OPT_SET_INT(0, "soft", &reset_type, N_("reset only HEAD"), SOFT),
 301                OPT_SET_INT(0, "hard", &reset_type,
 302                                N_("reset HEAD, index and working tree"), HARD),
 303                OPT_SET_INT(0, "merge", &reset_type,
 304                                N_("reset HEAD, index and working tree"), MERGE),
 305                OPT_SET_INT(0, "keep", &reset_type,
 306                                N_("reset HEAD but keep local changes"), KEEP),
 307                { OPTION_CALLBACK, 0, "recurse-submodules", NULL,
 308                            "reset", "control recursive updating of submodules",
 309                            PARSE_OPT_OPTARG, option_parse_recurse_submodules_worktree_updater },
 310                OPT_BOOL('p', "patch", &patch_mode, N_("select hunks interactively")),
 311                OPT_BOOL('N', "intent-to-add", &intent_to_add,
 312                                N_("record only the fact that removed paths will be added later")),
 313                OPT_END()
 314        };
 315
 316        git_config(git_reset_config, NULL);
 317
 318        argc = parse_options(argc, argv, prefix, options, git_reset_usage,
 319                                                PARSE_OPT_KEEP_DASHDASH);
 320        parse_args(&pathspec, argv, prefix, patch_mode, &rev);
 321
 322        unborn = !strcmp(rev, "HEAD") && get_oid("HEAD", &oid);
 323        if (unborn) {
 324                /* reset on unborn branch: treat as reset to empty tree */
 325                hashcpy(oid.hash, EMPTY_TREE_SHA1_BIN);
 326        } else if (!pathspec.nr) {
 327                struct commit *commit;
 328                if (get_oid_committish(rev, &oid))
 329                        die(_("Failed to resolve '%s' as a valid revision."), rev);
 330                commit = lookup_commit_reference(&oid);
 331                if (!commit)
 332                        die(_("Could not parse object '%s'."), rev);
 333                oidcpy(&oid, &commit->object.oid);
 334        } else {
 335                struct tree *tree;
 336                if (get_oid_treeish(rev, &oid))
 337                        die(_("Failed to resolve '%s' as a valid tree."), rev);
 338                tree = parse_tree_indirect(&oid);
 339                if (!tree)
 340                        die(_("Could not parse object '%s'."), rev);
 341                oidcpy(&oid, &tree->object.oid);
 342        }
 343
 344        if (patch_mode) {
 345                if (reset_type != NONE)
 346                        die(_("--patch is incompatible with --{hard,mixed,soft}"));
 347                return run_add_interactive(rev, "--patch=reset", &pathspec);
 348        }
 349
 350        /* git reset tree [--] paths... can be used to
 351         * load chosen paths from the tree into the index without
 352         * affecting the working tree nor HEAD. */
 353        if (pathspec.nr) {
 354                if (reset_type == MIXED)
 355                        warning(_("--mixed with paths is deprecated; use 'git reset -- <paths>' instead."));
 356                else if (reset_type != NONE)
 357                        die(_("Cannot do %s reset with paths."),
 358                                        _(reset_type_names[reset_type]));
 359        }
 360        if (reset_type == NONE)
 361                reset_type = MIXED; /* by default */
 362
 363        if (reset_type != SOFT && (reset_type != MIXED || get_git_work_tree()))
 364                setup_work_tree();
 365
 366        if (reset_type == MIXED && is_bare_repository())
 367                die(_("%s reset is not allowed in a bare repository"),
 368                    _(reset_type_names[reset_type]));
 369
 370        if (intent_to_add && reset_type != MIXED)
 371                die(_("-N can only be used with --mixed"));
 372
 373        /* Soft reset does not touch the index file nor the working tree
 374         * at all, but requires them in a good order.  Other resets reset
 375         * the index file to the tree object we are switching to. */
 376        if (reset_type == SOFT || reset_type == KEEP)
 377                die_if_unmerged_cache(reset_type);
 378
 379        if (reset_type != SOFT) {
 380                struct lock_file lock = LOCK_INIT;
 381                hold_locked_index(&lock, LOCK_DIE_ON_ERROR);
 382                if (reset_type == MIXED) {
 383                        int flags = quiet ? REFRESH_QUIET : REFRESH_IN_PORCELAIN;
 384                        if (read_from_tree(&pathspec, &oid, intent_to_add))
 385                                return 1;
 386                        if (get_git_work_tree())
 387                                refresh_index(&the_index, flags, NULL, NULL,
 388                                              _("Unstaged changes after reset:"));
 389                } else {
 390                        int err = reset_index(&oid, reset_type, quiet);
 391                        if (reset_type == KEEP && !err)
 392                                err = reset_index(&oid, MIXED, quiet);
 393                        if (err)
 394                                die(_("Could not reset index file to revision '%s'."), rev);
 395                }
 396
 397                if (write_locked_index(&the_index, &lock, COMMIT_LOCK))
 398                        die(_("Could not write new index file."));
 399        }
 400
 401        if (!pathspec.nr && !unborn) {
 402                /* Any resets without paths update HEAD to the head being
 403                 * switched to, saving the previous head in ORIG_HEAD before. */
 404                update_ref_status = reset_refs(rev, &oid);
 405
 406                if (reset_type == HARD && !update_ref_status && !quiet)
 407                        print_new_head_line(lookup_commit_reference(&oid));
 408        }
 409        if (!pathspec.nr)
 410                remove_branch_state();
 411
 412        return update_ref_status;
 413}