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