reset: integrate with sparse index
[alt-git.git] / builtin / reset.c
blob0ac0de7dc977a05ee9b288bf35006abf20a1709d
1 /*
2 * "git reset" builtin command
4 * Copyright (c) 2007 Carlos Rica
6 * Based on git-reset.sh, which is
8 * Copyright (c) 2005, 2006 Linus Torvalds and Junio C Hamano
9 */
10 #define USE_THE_INDEX_COMPATIBILITY_MACROS
11 #include "builtin.h"
12 #include "config.h"
13 #include "lockfile.h"
14 #include "tag.h"
15 #include "object.h"
16 #include "pretty.h"
17 #include "run-command.h"
18 #include "refs.h"
19 #include "diff.h"
20 #include "diffcore.h"
21 #include "tree.h"
22 #include "branch.h"
23 #include "parse-options.h"
24 #include "unpack-trees.h"
25 #include "cache-tree.h"
26 #include "submodule.h"
27 #include "submodule-config.h"
28 #include "dir.h"
30 #define REFRESH_INDEX_DELAY_WARNING_IN_MS (2 * 1000)
32 static const char * const git_reset_usage[] = {
33 N_("git reset [--mixed | --soft | --hard | --merge | --keep] [-q] [<commit>]"),
34 N_("git reset [-q] [<tree-ish>] [--] <pathspec>..."),
35 N_("git reset [-q] [--pathspec-from-file [--pathspec-file-nul]] [<tree-ish>]"),
36 N_("git reset --patch [<tree-ish>] [--] [<pathspec>...]"),
37 NULL
40 enum reset_type { MIXED, SOFT, HARD, MERGE, KEEP, NONE };
41 static const char *reset_type_names[] = {
42 N_("mixed"), N_("soft"), N_("hard"), N_("merge"), N_("keep"), NULL
45 static inline int is_merge(void)
47 return !access(git_path_merge_head(the_repository), F_OK);
50 static int reset_index(const char *ref, const struct object_id *oid, int reset_type, int quiet)
52 int i, nr = 0;
53 struct tree_desc desc[2];
54 struct tree *tree;
55 struct unpack_trees_options opts;
56 int ret = -1;
58 memset(&opts, 0, sizeof(opts));
59 opts.head_idx = 1;
60 opts.src_index = &the_index;
61 opts.dst_index = &the_index;
62 opts.fn = oneway_merge;
63 opts.merge = 1;
64 init_checkout_metadata(&opts.meta, ref, oid, NULL);
65 if (!quiet)
66 opts.verbose_update = 1;
67 switch (reset_type) {
68 case KEEP:
69 case MERGE:
70 opts.update = 1;
71 break;
72 case HARD:
73 opts.update = 1;
74 /* fallthrough */
75 default:
76 opts.reset = 1;
79 read_cache_unmerged();
81 if (reset_type == KEEP) {
82 struct object_id head_oid;
83 if (get_oid("HEAD", &head_oid))
84 return error(_("You do not have a valid HEAD."));
85 if (!fill_tree_descriptor(the_repository, desc + nr, &head_oid))
86 return error(_("Failed to find tree of HEAD."));
87 nr++;
88 opts.fn = twoway_merge;
91 if (!fill_tree_descriptor(the_repository, desc + nr, oid)) {
92 error(_("Failed to find tree of %s."), oid_to_hex(oid));
93 goto out;
95 nr++;
97 if (unpack_trees(nr, desc, &opts))
98 goto out;
100 if (reset_type == MIXED || reset_type == HARD) {
101 tree = parse_tree_indirect(oid);
102 prime_cache_tree(the_repository, the_repository->index, tree);
105 ret = 0;
107 out:
108 for (i = 0; i < nr; i++)
109 free((void *)desc[i].buffer);
110 return ret;
113 static void print_new_head_line(struct commit *commit)
115 struct strbuf buf = STRBUF_INIT;
117 printf(_("HEAD is now at %s"),
118 find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV));
120 pp_commit_easy(CMIT_FMT_ONELINE, commit, &buf);
121 if (buf.len > 0)
122 printf(" %s", buf.buf);
123 putchar('\n');
124 strbuf_release(&buf);
127 static void update_index_from_diff(struct diff_queue_struct *q,
128 struct diff_options *opt, void *data)
130 int i;
131 int intent_to_add = *(int *)data;
133 for (i = 0; i < q->nr; i++) {
134 int pos;
135 struct diff_filespec *one = q->queue[i]->one;
136 int is_in_reset_tree = one->mode && !is_null_oid(&one->oid);
137 struct cache_entry *ce;
139 if (!is_in_reset_tree && !intent_to_add) {
140 remove_file_from_cache(one->path);
141 continue;
144 ce = make_cache_entry(&the_index, one->mode, &one->oid, one->path,
145 0, 0);
148 * If the file 1) corresponds to an existing index entry with
149 * skip-worktree set, or 2) does not exist in the index but is
150 * outside the sparse checkout definition, add a skip-worktree bit
151 * to the new index entry.
153 pos = cache_name_pos(one->path, strlen(one->path));
154 if ((pos >= 0 && ce_skip_worktree(active_cache[pos])) ||
155 (pos < 0 && !path_in_sparse_checkout(one->path, &the_index)))
156 ce->ce_flags |= CE_SKIP_WORKTREE;
158 if (!ce)
159 die(_("make_cache_entry failed for path '%s'"),
160 one->path);
161 if (!is_in_reset_tree) {
162 ce->ce_flags |= CE_INTENT_TO_ADD;
163 set_object_name_for_intent_to_add_entry(ce);
165 add_cache_entry(ce, ADD_CACHE_OK_TO_ADD | ADD_CACHE_OK_TO_REPLACE);
169 static int read_from_tree(const struct pathspec *pathspec,
170 struct object_id *tree_oid,
171 int intent_to_add)
173 struct diff_options opt;
175 memset(&opt, 0, sizeof(opt));
176 copy_pathspec(&opt.pathspec, pathspec);
177 opt.output_format = DIFF_FORMAT_CALLBACK;
178 opt.format_callback = update_index_from_diff;
179 opt.format_callback_data = &intent_to_add;
180 opt.flags.override_submodule_config = 1;
181 opt.repo = the_repository;
183 ensure_full_index(&the_index);
184 if (do_diff_cache(tree_oid, &opt))
185 return 1;
186 diffcore_std(&opt);
187 diff_flush(&opt);
188 clear_pathspec(&opt.pathspec);
190 return 0;
193 static void set_reflog_message(struct strbuf *sb, const char *action,
194 const char *rev)
196 const char *rla = getenv("GIT_REFLOG_ACTION");
198 strbuf_reset(sb);
199 if (rla)
200 strbuf_addf(sb, "%s: %s", rla, action);
201 else if (rev)
202 strbuf_addf(sb, "reset: moving to %s", rev);
203 else
204 strbuf_addf(sb, "reset: %s", action);
207 static void die_if_unmerged_cache(int reset_type)
209 if (is_merge() || unmerged_cache())
210 die(_("Cannot do a %s reset in the middle of a merge."),
211 _(reset_type_names[reset_type]));
215 static void parse_args(struct pathspec *pathspec,
216 const char **argv, const char *prefix,
217 int patch_mode,
218 const char **rev_ret)
220 const char *rev = "HEAD";
221 struct object_id unused;
223 * Possible arguments are:
225 * git reset [-opts] [<rev>]
226 * git reset [-opts] <tree> [<paths>...]
227 * git reset [-opts] <tree> -- [<paths>...]
228 * git reset [-opts] -- [<paths>...]
229 * git reset [-opts] <paths>...
231 * At this point, argv points immediately after [-opts].
234 if (argv[0]) {
235 if (!strcmp(argv[0], "--")) {
236 argv++; /* reset to HEAD, possibly with paths */
237 } else if (argv[1] && !strcmp(argv[1], "--")) {
238 rev = argv[0];
239 argv += 2;
242 * Otherwise, argv[0] could be either <rev> or <paths> and
243 * has to be unambiguous. If there is a single argument, it
244 * can not be a tree
246 else if ((!argv[1] && !get_oid_committish(argv[0], &unused)) ||
247 (argv[1] && !get_oid_treeish(argv[0], &unused))) {
249 * Ok, argv[0] looks like a commit/tree; it should not
250 * be a filename.
252 verify_non_filename(prefix, argv[0]);
253 rev = *argv++;
254 } else {
255 /* Otherwise we treat this as a filename */
256 verify_filename(prefix, argv[0], 1);
259 *rev_ret = rev;
261 parse_pathspec(pathspec, 0,
262 PATHSPEC_PREFER_FULL |
263 (patch_mode ? PATHSPEC_PREFIX_ORIGIN : 0),
264 prefix, argv);
267 static int reset_refs(const char *rev, const struct object_id *oid)
269 int update_ref_status;
270 struct strbuf msg = STRBUF_INIT;
271 struct object_id *orig = NULL, oid_orig,
272 *old_orig = NULL, oid_old_orig;
274 if (!get_oid("ORIG_HEAD", &oid_old_orig))
275 old_orig = &oid_old_orig;
276 if (!get_oid("HEAD", &oid_orig)) {
277 orig = &oid_orig;
278 set_reflog_message(&msg, "updating ORIG_HEAD", NULL);
279 update_ref(msg.buf, "ORIG_HEAD", orig, old_orig, 0,
280 UPDATE_REFS_MSG_ON_ERR);
281 } else if (old_orig)
282 delete_ref(NULL, "ORIG_HEAD", old_orig, 0);
283 set_reflog_message(&msg, "updating HEAD", rev);
284 update_ref_status = update_ref(msg.buf, "HEAD", oid, orig, 0,
285 UPDATE_REFS_MSG_ON_ERR);
286 strbuf_release(&msg);
287 return update_ref_status;
290 static int git_reset_config(const char *var, const char *value, void *cb)
292 if (!strcmp(var, "submodule.recurse"))
293 return git_default_submodule_config(var, value, cb);
295 return git_default_config(var, value, cb);
298 int cmd_reset(int argc, const char **argv, const char *prefix)
300 int reset_type = NONE, update_ref_status = 0, quiet = 0;
301 int patch_mode = 0, pathspec_file_nul = 0, unborn;
302 const char *rev, *pathspec_from_file = NULL;
303 struct object_id oid;
304 struct pathspec pathspec;
305 int intent_to_add = 0;
306 const struct option options[] = {
307 OPT__QUIET(&quiet, N_("be quiet, only report errors")),
308 OPT_SET_INT(0, "mixed", &reset_type,
309 N_("reset HEAD and index"), MIXED),
310 OPT_SET_INT(0, "soft", &reset_type, N_("reset only HEAD"), SOFT),
311 OPT_SET_INT(0, "hard", &reset_type,
312 N_("reset HEAD, index and working tree"), HARD),
313 OPT_SET_INT(0, "merge", &reset_type,
314 N_("reset HEAD, index and working tree"), MERGE),
315 OPT_SET_INT(0, "keep", &reset_type,
316 N_("reset HEAD but keep local changes"), KEEP),
317 OPT_CALLBACK_F(0, "recurse-submodules", NULL,
318 "reset", "control recursive updating of submodules",
319 PARSE_OPT_OPTARG, option_parse_recurse_submodules_worktree_updater),
320 OPT_BOOL('p', "patch", &patch_mode, N_("select hunks interactively")),
321 OPT_BOOL('N', "intent-to-add", &intent_to_add,
322 N_("record only the fact that removed paths will be added later")),
323 OPT_PATHSPEC_FROM_FILE(&pathspec_from_file),
324 OPT_PATHSPEC_FILE_NUL(&pathspec_file_nul),
325 OPT_END()
328 git_config(git_reset_config, NULL);
329 git_config_get_bool("reset.quiet", &quiet);
331 argc = parse_options(argc, argv, prefix, options, git_reset_usage,
332 PARSE_OPT_KEEP_DASHDASH);
333 parse_args(&pathspec, argv, prefix, patch_mode, &rev);
335 if (pathspec_from_file) {
336 if (patch_mode)
337 die(_("--pathspec-from-file is incompatible with --patch"));
339 if (pathspec.nr)
340 die(_("--pathspec-from-file is incompatible with pathspec arguments"));
342 parse_pathspec_file(&pathspec, 0,
343 PATHSPEC_PREFER_FULL,
344 prefix, pathspec_from_file, pathspec_file_nul);
345 } else if (pathspec_file_nul) {
346 die(_("--pathspec-file-nul requires --pathspec-from-file"));
349 unborn = !strcmp(rev, "HEAD") && get_oid("HEAD", &oid);
350 if (unborn) {
351 /* reset on unborn branch: treat as reset to empty tree */
352 oidcpy(&oid, the_hash_algo->empty_tree);
353 } else if (!pathspec.nr && !patch_mode) {
354 struct commit *commit;
355 if (get_oid_committish(rev, &oid))
356 die(_("Failed to resolve '%s' as a valid revision."), rev);
357 commit = lookup_commit_reference(the_repository, &oid);
358 if (!commit)
359 die(_("Could not parse object '%s'."), rev);
360 oidcpy(&oid, &commit->object.oid);
361 } else {
362 struct tree *tree;
363 if (get_oid_treeish(rev, &oid))
364 die(_("Failed to resolve '%s' as a valid tree."), rev);
365 tree = parse_tree_indirect(&oid);
366 if (!tree)
367 die(_("Could not parse object '%s'."), rev);
368 oidcpy(&oid, &tree->object.oid);
371 if (patch_mode) {
372 if (reset_type != NONE)
373 die(_("--patch is incompatible with --{hard,mixed,soft}"));
374 trace2_cmd_mode("patch-interactive");
375 return run_add_interactive(rev, "--patch=reset", &pathspec);
378 /* git reset tree [--] paths... can be used to
379 * load chosen paths from the tree into the index without
380 * affecting the working tree nor HEAD. */
381 if (pathspec.nr) {
382 if (reset_type == MIXED)
383 warning(_("--mixed with paths is deprecated; use 'git reset -- <paths>' instead."));
384 else if (reset_type != NONE)
385 die(_("Cannot do %s reset with paths."),
386 _(reset_type_names[reset_type]));
388 if (reset_type == NONE)
389 reset_type = MIXED; /* by default */
391 if (pathspec.nr)
392 trace2_cmd_mode("path");
393 else
394 trace2_cmd_mode(reset_type_names[reset_type]);
396 if (reset_type != SOFT && (reset_type != MIXED || get_git_work_tree()))
397 setup_work_tree();
399 if (reset_type == MIXED && is_bare_repository())
400 die(_("%s reset is not allowed in a bare repository"),
401 _(reset_type_names[reset_type]));
403 if (intent_to_add && reset_type != MIXED)
404 die(_("-N can only be used with --mixed"));
406 prepare_repo_settings(the_repository);
407 the_repository->settings.command_requires_full_index = 0;
409 if (read_cache() < 0)
410 die(_("index file corrupt"));
412 /* Soft reset does not touch the index file nor the working tree
413 * at all, but requires them in a good order. Other resets reset
414 * the index file to the tree object we are switching to. */
415 if (reset_type == SOFT || reset_type == KEEP)
416 die_if_unmerged_cache(reset_type);
418 if (reset_type != SOFT) {
419 struct lock_file lock = LOCK_INIT;
420 hold_locked_index(&lock, LOCK_DIE_ON_ERROR);
421 if (reset_type == MIXED) {
422 int flags = quiet ? REFRESH_QUIET : REFRESH_IN_PORCELAIN;
423 if (read_from_tree(&pathspec, &oid, intent_to_add))
424 return 1;
425 the_index.updated_skipworktree = 1;
426 if (!quiet && get_git_work_tree()) {
427 uint64_t t_begin, t_delta_in_ms;
429 t_begin = getnanotime();
430 refresh_index(&the_index, flags, NULL, NULL,
431 _("Unstaged changes after reset:"));
432 t_delta_in_ms = (getnanotime() - t_begin) / 1000000;
433 if (advice_enabled(ADVICE_RESET_QUIET_WARNING) && t_delta_in_ms > REFRESH_INDEX_DELAY_WARNING_IN_MS) {
434 printf(_("\nIt took %.2f seconds to enumerate unstaged changes after reset. You can\n"
435 "use '--quiet' to avoid this. Set the config setting reset.quiet to true\n"
436 "to make this the default.\n"), t_delta_in_ms / 1000.0);
439 } else {
440 struct object_id dummy;
441 char *ref = NULL;
442 int err;
444 dwim_ref(rev, strlen(rev), &dummy, &ref, 0);
445 if (ref && !starts_with(ref, "refs/"))
446 FREE_AND_NULL(ref);
448 err = reset_index(ref, &oid, reset_type, quiet);
449 if (reset_type == KEEP && !err)
450 err = reset_index(ref, &oid, MIXED, quiet);
451 if (err)
452 die(_("Could not reset index file to revision '%s'."), rev);
453 free(ref);
456 if (write_locked_index(&the_index, &lock, COMMIT_LOCK))
457 die(_("Could not write new index file."));
460 if (!pathspec.nr && !unborn) {
461 /* Any resets without paths update HEAD to the head being
462 * switched to, saving the previous head in ORIG_HEAD before. */
463 update_ref_status = reset_refs(rev, &oid);
465 if (reset_type == HARD && !update_ref_status && !quiet)
466 print_new_head_line(lookup_commit_reference(the_repository, &oid));
468 if (!pathspec.nr)
469 remove_branch_state(the_repository, 0);
471 return update_ref_status;