Merge branch 'jc/doc-branch-update-checked-out-branch' into maint-2.39
[alt-git.git] / builtin / reset.c
blob1fa86edb4c92f31a21d838bcbff76e687cd15c23
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_VARIABLE
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 opts.preserve_ignored = 0; /* FIXME: !overwrite_ignore */
72 break;
73 case HARD:
74 opts.update = 1;
75 opts.reset = UNPACK_RESET_OVERWRITE_UNTRACKED;
76 opts.skip_cache_tree_update = 1;
77 break;
78 case MIXED:
79 opts.reset = UNPACK_RESET_PROTECT_UNTRACKED;
80 opts.skip_cache_tree_update = 1;
81 /* but opts.update=0, so working tree not updated */
82 break;
83 default:
84 BUG("invalid reset_type passed to reset_index");
87 repo_read_index_unmerged(the_repository);
89 if (reset_type == KEEP) {
90 struct object_id head_oid;
91 if (get_oid("HEAD", &head_oid))
92 return error(_("You do not have a valid HEAD."));
93 if (!fill_tree_descriptor(the_repository, desc + nr, &head_oid))
94 return error(_("Failed to find tree of HEAD."));
95 nr++;
96 opts.fn = twoway_merge;
99 if (!fill_tree_descriptor(the_repository, desc + nr, oid)) {
100 error(_("Failed to find tree of %s."), oid_to_hex(oid));
101 goto out;
103 nr++;
105 if (unpack_trees(nr, desc, &opts))
106 goto out;
108 if (reset_type == MIXED || reset_type == HARD) {
109 tree = parse_tree_indirect(oid);
110 prime_cache_tree(the_repository, the_repository->index, tree);
113 ret = 0;
115 out:
116 for (i = 0; i < nr; i++)
117 free((void *)desc[i].buffer);
118 return ret;
121 static void print_new_head_line(struct commit *commit)
123 struct strbuf buf = STRBUF_INIT;
125 printf(_("HEAD is now at %s"),
126 find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV));
128 pp_commit_easy(CMIT_FMT_ONELINE, commit, &buf);
129 if (buf.len > 0)
130 printf(" %s", buf.buf);
131 putchar('\n');
132 strbuf_release(&buf);
135 static void update_index_from_diff(struct diff_queue_struct *q,
136 struct diff_options *opt, void *data)
138 int i;
139 int intent_to_add = *(int *)data;
141 for (i = 0; i < q->nr; i++) {
142 int pos;
143 struct diff_filespec *one = q->queue[i]->one;
144 int is_in_reset_tree = one->mode && !is_null_oid(&one->oid);
145 struct cache_entry *ce;
147 if (!is_in_reset_tree && !intent_to_add) {
148 remove_file_from_index(&the_index, one->path);
149 continue;
152 ce = make_cache_entry(&the_index, one->mode, &one->oid, one->path,
153 0, 0);
156 * If the file 1) corresponds to an existing index entry with
157 * skip-worktree set, or 2) does not exist in the index but is
158 * outside the sparse checkout definition, add a skip-worktree bit
159 * to the new index entry. Note that a sparse index will be expanded
160 * if this entry is outside the sparse cone - this is necessary
161 * to properly construct the reset sparse directory.
163 pos = index_name_pos(&the_index, one->path, strlen(one->path));
164 if ((pos >= 0 && ce_skip_worktree(the_index.cache[pos])) ||
165 (pos < 0 && !path_in_sparse_checkout(one->path, &the_index)))
166 ce->ce_flags |= CE_SKIP_WORKTREE;
168 if (!ce)
169 die(_("make_cache_entry failed for path '%s'"),
170 one->path);
171 if (!is_in_reset_tree) {
172 ce->ce_flags |= CE_INTENT_TO_ADD;
173 set_object_name_for_intent_to_add_entry(ce);
175 add_index_entry(&the_index, ce,
176 ADD_CACHE_OK_TO_ADD | ADD_CACHE_OK_TO_REPLACE);
180 static int read_from_tree(const struct pathspec *pathspec,
181 struct object_id *tree_oid,
182 int intent_to_add)
184 struct diff_options opt;
186 memset(&opt, 0, sizeof(opt));
187 copy_pathspec(&opt.pathspec, pathspec);
188 opt.output_format = DIFF_FORMAT_CALLBACK;
189 opt.format_callback = update_index_from_diff;
190 opt.format_callback_data = &intent_to_add;
191 opt.flags.override_submodule_config = 1;
192 opt.flags.recursive = 1;
193 opt.repo = the_repository;
194 opt.change = diff_change;
195 opt.add_remove = diff_addremove;
197 if (pathspec->nr && pathspec_needs_expanded_index(&the_index, pathspec))
198 ensure_full_index(&the_index);
200 if (do_diff_cache(tree_oid, &opt))
201 return 1;
202 diffcore_std(&opt);
203 diff_flush(&opt);
205 return 0;
208 static void set_reflog_message(struct strbuf *sb, const char *action,
209 const char *rev)
211 const char *rla = getenv("GIT_REFLOG_ACTION");
213 strbuf_reset(sb);
214 if (rla)
215 strbuf_addf(sb, "%s: %s", rla, action);
216 else if (rev)
217 strbuf_addf(sb, "reset: moving to %s", rev);
218 else
219 strbuf_addf(sb, "reset: %s", action);
222 static void die_if_unmerged_cache(int reset_type)
224 if (is_merge() || unmerged_index(&the_index))
225 die(_("Cannot do a %s reset in the middle of a merge."),
226 _(reset_type_names[reset_type]));
230 static void parse_args(struct pathspec *pathspec,
231 const char **argv, const char *prefix,
232 int patch_mode,
233 const char **rev_ret)
235 const char *rev = "HEAD";
236 struct object_id unused;
238 * Possible arguments are:
240 * git reset [-opts] [<rev>]
241 * git reset [-opts] <tree> [<paths>...]
242 * git reset [-opts] <tree> -- [<paths>...]
243 * git reset [-opts] -- [<paths>...]
244 * git reset [-opts] <paths>...
246 * At this point, argv points immediately after [-opts].
249 if (argv[0]) {
250 if (!strcmp(argv[0], "--")) {
251 argv++; /* reset to HEAD, possibly with paths */
252 } else if (argv[1] && !strcmp(argv[1], "--")) {
253 rev = argv[0];
254 argv += 2;
257 * Otherwise, argv[0] could be either <rev> or <paths> and
258 * has to be unambiguous. If there is a single argument, it
259 * can not be a tree
261 else if ((!argv[1] && !get_oid_committish(argv[0], &unused)) ||
262 (argv[1] && !get_oid_treeish(argv[0], &unused))) {
264 * Ok, argv[0] looks like a commit/tree; it should not
265 * be a filename.
267 verify_non_filename(prefix, argv[0]);
268 rev = *argv++;
269 } else {
270 /* Otherwise we treat this as a filename */
271 verify_filename(prefix, argv[0], 1);
274 *rev_ret = rev;
276 parse_pathspec(pathspec, 0,
277 PATHSPEC_PREFER_FULL |
278 (patch_mode ? PATHSPEC_PREFIX_ORIGIN : 0),
279 prefix, argv);
282 static int reset_refs(const char *rev, const struct object_id *oid)
284 int update_ref_status;
285 struct strbuf msg = STRBUF_INIT;
286 struct object_id *orig = NULL, oid_orig,
287 *old_orig = NULL, oid_old_orig;
289 if (!get_oid("ORIG_HEAD", &oid_old_orig))
290 old_orig = &oid_old_orig;
291 if (!get_oid("HEAD", &oid_orig)) {
292 orig = &oid_orig;
293 set_reflog_message(&msg, "updating ORIG_HEAD", NULL);
294 update_ref(msg.buf, "ORIG_HEAD", orig, old_orig, 0,
295 UPDATE_REFS_MSG_ON_ERR);
296 } else if (old_orig)
297 delete_ref(NULL, "ORIG_HEAD", old_orig, 0);
298 set_reflog_message(&msg, "updating HEAD", rev);
299 update_ref_status = update_ref(msg.buf, "HEAD", oid, orig, 0,
300 UPDATE_REFS_MSG_ON_ERR);
301 strbuf_release(&msg);
302 return update_ref_status;
305 static int git_reset_config(const char *var, const char *value, void *cb)
307 if (!strcmp(var, "submodule.recurse"))
308 return git_default_submodule_config(var, value, cb);
310 return git_default_config(var, value, cb);
313 int cmd_reset(int argc, const char **argv, const char *prefix)
315 int reset_type = NONE, update_ref_status = 0, quiet = 0;
316 int no_refresh = 0;
317 int patch_mode = 0, pathspec_file_nul = 0, unborn;
318 const char *rev, *pathspec_from_file = NULL;
319 struct object_id oid;
320 struct pathspec pathspec;
321 int intent_to_add = 0;
322 const struct option options[] = {
323 OPT__QUIET(&quiet, N_("be quiet, only report errors")),
324 OPT_BOOL(0, "no-refresh", &no_refresh,
325 N_("skip refreshing the index after reset")),
326 OPT_SET_INT(0, "mixed", &reset_type,
327 N_("reset HEAD and index"), MIXED),
328 OPT_SET_INT(0, "soft", &reset_type, N_("reset only HEAD"), SOFT),
329 OPT_SET_INT(0, "hard", &reset_type,
330 N_("reset HEAD, index and working tree"), HARD),
331 OPT_SET_INT(0, "merge", &reset_type,
332 N_("reset HEAD, index and working tree"), MERGE),
333 OPT_SET_INT(0, "keep", &reset_type,
334 N_("reset HEAD but keep local changes"), KEEP),
335 OPT_CALLBACK_F(0, "recurse-submodules", NULL,
336 "reset", "control recursive updating of submodules",
337 PARSE_OPT_OPTARG, option_parse_recurse_submodules_worktree_updater),
338 OPT_BOOL('p', "patch", &patch_mode, N_("select hunks interactively")),
339 OPT_BOOL('N', "intent-to-add", &intent_to_add,
340 N_("record only the fact that removed paths will be added later")),
341 OPT_PATHSPEC_FROM_FILE(&pathspec_from_file),
342 OPT_PATHSPEC_FILE_NUL(&pathspec_file_nul),
343 OPT_END()
346 git_config(git_reset_config, NULL);
348 argc = parse_options(argc, argv, prefix, options, git_reset_usage,
349 PARSE_OPT_KEEP_DASHDASH);
350 parse_args(&pathspec, argv, prefix, patch_mode, &rev);
352 if (pathspec_from_file) {
353 if (patch_mode)
354 die(_("options '%s' and '%s' cannot be used together"), "--pathspec-from-file", "--patch");
356 if (pathspec.nr)
357 die(_("'%s' and pathspec arguments cannot be used together"), "--pathspec-from-file");
359 parse_pathspec_file(&pathspec, 0,
360 PATHSPEC_PREFER_FULL,
361 prefix, pathspec_from_file, pathspec_file_nul);
362 } else if (pathspec_file_nul) {
363 die(_("the option '%s' requires '%s'"), "--pathspec-file-nul", "--pathspec-from-file");
366 unborn = !strcmp(rev, "HEAD") && get_oid("HEAD", &oid);
367 if (unborn) {
368 /* reset on unborn branch: treat as reset to empty tree */
369 oidcpy(&oid, the_hash_algo->empty_tree);
370 } else if (!pathspec.nr && !patch_mode) {
371 struct commit *commit;
372 if (get_oid_committish(rev, &oid))
373 die(_("Failed to resolve '%s' as a valid revision."), rev);
374 commit = lookup_commit_reference(the_repository, &oid);
375 if (!commit)
376 die(_("Could not parse object '%s'."), rev);
377 oidcpy(&oid, &commit->object.oid);
378 } else {
379 struct tree *tree;
380 if (get_oid_treeish(rev, &oid))
381 die(_("Failed to resolve '%s' as a valid tree."), rev);
382 tree = parse_tree_indirect(&oid);
383 if (!tree)
384 die(_("Could not parse object '%s'."), rev);
385 oidcpy(&oid, &tree->object.oid);
388 if (patch_mode) {
389 if (reset_type != NONE)
390 die(_("options '%s' and '%s' cannot be used together"), "--patch", "--{hard,mixed,soft}");
391 trace2_cmd_mode("patch-interactive");
392 return run_add_interactive(rev, "--patch=reset", &pathspec);
395 /* git reset tree [--] paths... can be used to
396 * load chosen paths from the tree into the index without
397 * affecting the working tree nor HEAD. */
398 if (pathspec.nr) {
399 if (reset_type == MIXED)
400 warning(_("--mixed with paths is deprecated; use 'git reset -- <paths>' instead."));
401 else if (reset_type != NONE)
402 die(_("Cannot do %s reset with paths."),
403 _(reset_type_names[reset_type]));
405 if (reset_type == NONE)
406 reset_type = MIXED; /* by default */
408 if (pathspec.nr)
409 trace2_cmd_mode("path");
410 else
411 trace2_cmd_mode(reset_type_names[reset_type]);
413 if (reset_type != SOFT && (reset_type != MIXED || get_git_work_tree()))
414 setup_work_tree();
416 if (reset_type == MIXED && is_bare_repository())
417 die(_("%s reset is not allowed in a bare repository"),
418 _(reset_type_names[reset_type]));
420 if (intent_to_add && reset_type != MIXED)
421 die(_("the option '%s' requires '%s'"), "-N", "--mixed");
423 prepare_repo_settings(the_repository);
424 the_repository->settings.command_requires_full_index = 0;
426 if (repo_read_index(the_repository) < 0)
427 die(_("index file corrupt"));
429 /* Soft reset does not touch the index file nor the working tree
430 * at all, but requires them in a good order. Other resets reset
431 * the index file to the tree object we are switching to. */
432 if (reset_type == SOFT || reset_type == KEEP)
433 die_if_unmerged_cache(reset_type);
435 if (reset_type != SOFT) {
436 struct lock_file lock = LOCK_INIT;
437 repo_hold_locked_index(the_repository, &lock,
438 LOCK_DIE_ON_ERROR);
439 if (reset_type == MIXED) {
440 int flags = quiet ? REFRESH_QUIET : REFRESH_IN_PORCELAIN;
441 if (read_from_tree(&pathspec, &oid, intent_to_add))
442 return 1;
443 the_index.updated_skipworktree = 1;
444 if (!no_refresh && get_git_work_tree()) {
445 uint64_t t_begin, t_delta_in_ms;
447 t_begin = getnanotime();
448 refresh_index(&the_index, flags, NULL, NULL,
449 _("Unstaged changes after reset:"));
450 t_delta_in_ms = (getnanotime() - t_begin) / 1000000;
451 if (!quiet && advice_enabled(ADVICE_RESET_NO_REFRESH_WARNING) && t_delta_in_ms > REFRESH_INDEX_DELAY_WARNING_IN_MS) {
452 advise(_("It took %.2f seconds to refresh the index after reset. You can use\n"
453 "'--no-refresh' to avoid this."), t_delta_in_ms / 1000.0);
456 } else {
457 struct object_id dummy;
458 char *ref = NULL;
459 int err;
461 dwim_ref(rev, strlen(rev), &dummy, &ref, 0);
462 if (ref && !starts_with(ref, "refs/"))
463 FREE_AND_NULL(ref);
465 err = reset_index(ref, &oid, reset_type, quiet);
466 if (reset_type == KEEP && !err)
467 err = reset_index(ref, &oid, MIXED, quiet);
468 if (err)
469 die(_("Could not reset index file to revision '%s'."), rev);
470 free(ref);
473 if (write_locked_index(&the_index, &lock, COMMIT_LOCK))
474 die(_("Could not write new index file."));
477 if (!pathspec.nr && !unborn) {
478 /* Any resets without paths update HEAD to the head being
479 * switched to, saving the previous head in ORIG_HEAD before. */
480 update_ref_status = reset_refs(rev, &oid);
482 if (reset_type == HARD && !update_ref_status && !quiet)
483 print_new_head_line(lookup_commit_reference(the_repository, &oid));
485 if (!pathspec.nr)
486 remove_branch_state(the_repository, 0);
488 return update_ref_status;