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