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