Raw
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
11 #define USE_THE_REPOSITORY_VARIABLE
12
13 #include "builtin.h"
14 #include "advice.h"
15 #include "config.h"
16 #include "environment.h"
17 #include "gettext.h"
18 #include "hash.h"
19 #include "hex.h"
20 #include "lockfile.h"
21 #include "object.h"
22 #include "pretty.h"
23 #include "refs.h"
24 #include "diff.h"
25 #include "diffcore.h"
26 #include "tree.h"
27 #include "branch.h"
28 #include "object-name.h"
29 #include "parse-options.h"
30 #include "path.h"
31 #include "repository.h"
32 #include "unpack-trees.h"
33 #include "cache-tree.h"
34 #include "setup.h"
35 #include "sparse-index.h"
36 #include "submodule.h"
37 #include "trace.h"
38 #include "trace2.h"
39 #include "dir.h"
40 #include "add-interactive.h"
41
42 #define REFRESH_INDEX_DELAY_WARNING_IN_MS (2 * 1000)
43
44 static const char * const git_reset_usage[] = {
45 N_("git reset [--mixed | --soft | --hard | --merge | --keep] [-q] [<commit>]"),
46 N_("git reset [-q] [<tree-ish>] [--] <pathspec>..."),
47 N_("git reset [-q] [--pathspec-from-file [--pathspec-file-nul]] [<tree-ish>]"),
48 N_("git reset --patch [<tree-ish>] [--] [<pathspec>...]"),
49 NULL
50 };
51
52 enum reset_type { MIXED, SOFT, HARD, MERGE, KEEP, NONE };
53 static const char *reset_type_names[] = {
54 N_("mixed"), N_("soft"), N_("hard"), N_("merge"), N_("keep"), NULL
55 };
56
57 static inline int is_merge(void)
58 {
59 return !access(git_path_merge_head(the_repository), F_OK);
60 }
61
62 static int reset_index(const char *ref, const struct object_id *oid, int reset_type, int quiet)
63 {
64 int i, nr = 0;
65 struct tree_desc desc[2];
66 struct tree *tree;
67 struct unpack_trees_options opts;
68 int ret = -1;
69
70 memset(&opts, 0, sizeof(opts));
71 opts.head_idx = 1;
72 opts.src_index = the_repository->index;
73 opts.dst_index = the_repository->index;
74 opts.fn = oneway_merge;
75 opts.merge = 1;
76 init_checkout_metadata(&opts.meta, ref, oid, NULL);
77 if (!quiet)
78 opts.verbose_update = 1;
79 switch (reset_type) {
80 case KEEP:
81 case MERGE:
82 opts.update = 1;
83 opts.preserve_ignored = 0; /* FIXME: !overwrite_ignore */
84 break;
85 case HARD:
86 opts.update = 1;
87 opts.reset = UNPACK_RESET_OVERWRITE_UNTRACKED;
88 opts.skip_cache_tree_update = 1;
89 break;
90 case MIXED:
91 opts.reset = UNPACK_RESET_PROTECT_UNTRACKED;
92 opts.skip_cache_tree_update = 1;
93 /* but opts.update=0, so working tree not updated */
94 break;
95 default:
96 BUG("invalid reset_type passed to reset_index");
97 }
98
99 repo_read_index_unmerged(the_repository);
100
101 if (reset_type == KEEP) {
102 struct object_id head_oid;
103 if (repo_get_oid(the_repository, "HEAD", &head_oid))
104 return error(_("You do not have a valid HEAD."));
105 if (!fill_tree_descriptor(the_repository, desc + nr, &head_oid))
106 return error(_("Failed to find tree of HEAD."));
107 nr++;
108 opts.fn = twoway_merge;
109 }
110
111 if (!fill_tree_descriptor(the_repository, desc + nr, oid)) {
112 error(_("Failed to find tree of %s."), oid_to_hex(oid));
113 goto out;
114 }
115 nr++;
116
117 if (unpack_trees(nr, desc, &opts))
118 goto out;
119
120 if (reset_type == MIXED || reset_type == HARD) {
121 tree = repo_parse_tree_indirect(the_repository, oid);
122 if (!tree) {
123 error(_("unable to read tree (%s)"), oid_to_hex(oid));
124 goto out;
125 }
126 prime_cache_tree(the_repository, the_repository->index, tree);
127 }
128
129 ret = 0;
130
131 out:
132 for (i = 0; i < nr; i++)
133 free((void *)desc[i].buffer);
134 return ret;
135 }
136
137 static void print_new_head_line(struct commit *commit)
138 {
139 struct strbuf buf = STRBUF_INIT;
140
141 printf(_("HEAD is now at %s"),
142 repo_find_unique_abbrev(the_repository, &commit->object.oid, DEFAULT_ABBREV));
143
144 pp_commit_easy(CMIT_FMT_ONELINE, commit, &buf);
145 if (buf.len > 0)
146 printf(" %s", buf.buf);
147 putchar('\n');
148 strbuf_release(&buf);
149 }
150
151 static void update_index_from_diff(struct diff_queue_struct *q,
152 struct diff_options *opt UNUSED,
153 void *data)
154 {
155 int i;
156 int intent_to_add = *(int *)data;
157
158 for (i = 0; i < q->nr; i++) {
159 int pos;
160 struct diff_filespec *one = q->queue[i]->one;
161 int is_in_reset_tree = one->mode && !is_null_oid(&one->oid);
162 struct cache_entry *ce;
163
164 if (!is_in_reset_tree && !intent_to_add) {
165 remove_file_from_index(the_repository->index, one->path);
166 continue;
167 }
168
169 ce = make_cache_entry(the_repository->index, one->mode, &one->oid, one->path,
170 0, 0);
171
172 /*
173 * If the file 1) corresponds to an existing index entry with
174 * skip-worktree set, or 2) does not exist in the index but is
175 * outside the sparse checkout definition, add a skip-worktree bit
176 * to the new index entry. Note that a sparse index will be expanded
177 * if this entry is outside the sparse cone - this is necessary
178 * to properly construct the reset sparse directory.
179 */
180 pos = index_name_pos(the_repository->index, one->path, strlen(one->path));
181 if ((pos >= 0 && ce_skip_worktree(the_repository->index->cache[pos])) ||
182 (pos < 0 && !path_in_sparse_checkout(one->path, the_repository->index)))
183 ce->ce_flags |= CE_SKIP_WORKTREE;
184
185 if (!ce)
186 die(_("make_cache_entry failed for path '%s'"),
187 one->path);
188 if (!is_in_reset_tree) {
189 ce->ce_flags |= CE_INTENT_TO_ADD;
190 set_object_name_for_intent_to_add_entry(ce);
191 }
192 add_index_entry(the_repository->index, ce,
193 ADD_CACHE_OK_TO_ADD | ADD_CACHE_OK_TO_REPLACE);
194 }
195 }
196
197 static int read_from_tree(const struct pathspec *pathspec,
198 struct object_id *tree_oid,
199 int intent_to_add)
200 {
201 struct diff_options opt;
202
203 memset(&opt, 0, sizeof(opt));
204 copy_pathspec(&opt.pathspec, pathspec);
205 opt.output_format = DIFF_FORMAT_CALLBACK;
206 opt.format_callback = update_index_from_diff;
207 opt.format_callback_data = &intent_to_add;
208 opt.flags.override_submodule_config = 1;
209 opt.flags.recursive = 1;
210 opt.repo = the_repository;
211 opt.change = diff_change;
212 opt.add_remove = diff_addremove;
213
214 if (pathspec->nr && pathspec_needs_expanded_index(the_repository->index, pathspec))
215 ensure_full_index(the_repository->index);
216
217 if (do_diff_cache(tree_oid, &opt))
218 return 1;
219 diffcore_std(&opt);
220 diff_flush(&opt);
221
222 return 0;
223 }
224
225 static void set_reflog_message(struct strbuf *sb, const char *action,
226 const char *rev)
227 {
228 const char *rla = getenv("GIT_REFLOG_ACTION");
229
230 strbuf_reset(sb);
231 if (rla)
232 strbuf_addf(sb, "%s: %s", rla, action);
233 else if (rev)
234 strbuf_addf(sb, "reset: moving to %s", rev);
235 else
236 strbuf_addf(sb, "reset: %s", action);
237 }
238
239 static void die_if_unmerged_cache(int reset_type)
240 {
241 if (is_merge() || unmerged_index(the_repository->index))
242 die(_("Cannot do a %s reset in the middle of a merge."),
243 _(reset_type_names[reset_type]));
244
245 }
246
247 static void parse_args(struct pathspec *pathspec,
248 const char **argv, const char *prefix,
249 int patch_mode,
250 const char **rev_ret)
251 {
252 const char *rev = "HEAD";
253 struct object_id unused;
254 /*
255 * Possible arguments are:
256 *
257 * git reset [-opts] [<rev>]
258 * git reset [-opts] <tree> [<paths>...]
259 * git reset [-opts] <tree> -- [<paths>...]
260 * git reset [-opts] -- [<paths>...]
261 * git reset [-opts] <paths>...
262 *
263 * At this point, argv points immediately after [-opts].
264 */
265
266 if (argv[0]) {
267 if (!strcmp(argv[0], "--")) {
268 argv++; /* reset to HEAD, possibly with paths */
269 } else if (argv[1] && !strcmp(argv[1], "--")) {
270 rev = argv[0];
271 argv += 2;
272 }
273 /*
274 * Otherwise, argv[0] could be either <rev> or <paths> and
275 * has to be unambiguous. If there is a single argument, it
276 * can not be a tree
277 */
278 else if ((!argv[1] && !repo_get_oid_committish(the_repository, argv[0], &unused)) ||
279 (argv[1] && !repo_get_oid_treeish(the_repository, argv[0], &unused))) {
280 /*
281 * Ok, argv[0] looks like a commit/tree; it should not
282 * be a filename.
283 */
284 verify_non_filename(the_repository, prefix, argv[0]);
285 rev = *argv++;
286 } else {
287 /* Otherwise we treat this as a filename */
288 verify_filename(the_repository, prefix, argv[0], 1);
289 }
290 }
291
292 /* treat '@' as a shortcut for 'HEAD' */
293 *rev_ret = !strcmp("@", rev) ? "HEAD" : rev;
294
295 parse_pathspec(pathspec, 0,
296 PATHSPEC_PREFER_FULL |
297 (patch_mode ? PATHSPEC_PREFIX_ORIGIN : 0),
298 prefix, argv);
299 }
300
301 static int reset_refs(const char *rev, const struct object_id *oid)
302 {
303 int update_ref_status;
304 struct strbuf msg = STRBUF_INIT;
305 struct object_id *orig = NULL, oid_orig,
306 *old_orig = NULL, oid_old_orig;
307
308 if (!repo_get_oid(the_repository, "ORIG_HEAD", &oid_old_orig))
309 old_orig = &oid_old_orig;
310 if (!repo_get_oid(the_repository, "HEAD", &oid_orig)) {
311 orig = &oid_orig;
312 set_reflog_message(&msg, "updating ORIG_HEAD", NULL);
313 refs_update_ref(get_main_ref_store(the_repository), msg.buf,
314 "ORIG_HEAD", orig, old_orig, 0,
315 UPDATE_REFS_MSG_ON_ERR);
316 } else if (old_orig)
317 refs_delete_ref(get_main_ref_store(the_repository), NULL,
318 "ORIG_HEAD", old_orig, 0);
319 set_reflog_message(&msg, "updating HEAD", rev);
320 update_ref_status = refs_update_ref(get_main_ref_store(the_repository),
321 msg.buf, "HEAD", oid, orig, 0,
322 UPDATE_REFS_MSG_ON_ERR);
323 strbuf_release(&msg);
324 return update_ref_status;
325 }
326
327 static int git_reset_config(const char *var, const char *value,
328 const struct config_context *ctx, void *cb)
329 {
330 if (!strcmp(var, "submodule.recurse"))
331 return git_default_submodule_config(var, value, cb);
332
333 return git_default_config(var, value, ctx, cb);
334 }
335
336 int cmd_reset(int argc,
337 const char **argv,
338 const char *prefix,
339 struct repository *repo UNUSED)
340 {
341 int reset_type = NONE, update_ref_status = 0, quiet = 0;
342 int no_refresh = 0;
343 int patch_mode = 0, pathspec_file_nul = 0, unborn;
344 const char *rev;
345 char *pathspec_from_file = NULL;
346 struct object_id oid;
347 struct pathspec pathspec;
348 int intent_to_add = 0;
349 struct interactive_options interactive_opts = INTERACTIVE_OPTIONS_INIT;
350 const struct option options[] = {
351 OPT__QUIET(&quiet, N_("be quiet, only report errors")),
352 OPT_BOOL(0, "no-refresh", &no_refresh,
353 N_("skip refreshing the index after reset")),
354 OPT_SET_INT_F(0, "mixed", &reset_type,
355 N_("reset HEAD and index"),
356 MIXED, PARSE_OPT_NONEG),
357 OPT_SET_INT_F(0, "soft", &reset_type,
358 N_("reset only HEAD"),
359 SOFT, PARSE_OPT_NONEG),
360 OPT_SET_INT_F(0, "hard", &reset_type,
361 N_("reset HEAD, index and working tree"),
362 HARD, PARSE_OPT_NONEG),
363 OPT_SET_INT_F(0, "merge", &reset_type,
364 N_("reset HEAD, index and working tree"),
365 MERGE, PARSE_OPT_NONEG),
366 OPT_SET_INT_F(0, "keep", &reset_type,
367 N_("reset HEAD but keep local changes"),
368 KEEP, PARSE_OPT_NONEG),
369 OPT_CALLBACK_F(0, "recurse-submodules", NULL,
370 "reset", "control recursive updating of submodules",
371 PARSE_OPT_OPTARG,
372 option_parse_recurse_submodules_worktree_updater),
373 OPT_BOOL('p', "patch", &patch_mode, N_("select hunks interactively")),
374 OPT_BOOL(0, "auto-advance", &interactive_opts.auto_advance,
375 N_("auto advance to the next file when selecting hunks interactively")),
376 OPT_DIFF_UNIFIED(&interactive_opts.context),
377 OPT_DIFF_INTERHUNK_CONTEXT(&interactive_opts.interhunkcontext),
378 OPT_BOOL('N', "intent-to-add", &intent_to_add,
379 N_("record only the fact that removed paths will be added later")),
380 OPT_PATHSPEC_FROM_FILE(&pathspec_from_file),
381 OPT_PATHSPEC_FILE_NUL(&pathspec_file_nul),
382 OPT_END()
383 };
384
385 repo_config(the_repository, git_reset_config, NULL);
386
387 argc = parse_options(argc, argv, prefix, options, git_reset_usage,
388 PARSE_OPT_KEEP_DASHDASH);
389 parse_args(&pathspec, argv, prefix, patch_mode, &rev);
390
391 if (pathspec_from_file) {
392 if (patch_mode)
393 die(_("options '%s' and '%s' cannot be used together"), "--pathspec-from-file", "--patch");
394
395 if (pathspec.nr)
396 die(_("'%s' and pathspec arguments cannot be used together"), "--pathspec-from-file");
397
398 parse_pathspec_file(&pathspec, 0,
399 PATHSPEC_PREFER_FULL,
400 prefix, pathspec_from_file, pathspec_file_nul);
401 } else if (pathspec_file_nul) {
402 die(_("the option '%s' requires '%s'"), "--pathspec-file-nul", "--pathspec-from-file");
403 }
404
405 unborn = !strcmp(rev, "HEAD") && repo_get_oid(the_repository, "HEAD",
406 &oid);
407 if (unborn) {
408 /* reset on unborn branch: treat as reset to empty tree */
409 oidcpy(&oid, the_hash_algo->empty_tree);
410 } else if (!pathspec.nr && !patch_mode) {
411 struct commit *commit;
412 if (repo_get_oid_committish(the_repository, rev, &oid))
413 die(_("Failed to resolve '%s' as a valid revision."), rev);
414 commit = lookup_commit_reference(the_repository, &oid);
415 if (!commit)
416 die(_("Could not parse object '%s'."), rev);
417 oidcpy(&oid, &commit->object.oid);
418 } else {
419 struct tree *tree;
420 if (repo_get_oid_treeish(the_repository, rev, &oid))
421 die(_("Failed to resolve '%s' as a valid tree."), rev);
422 tree = repo_parse_tree_indirect(the_repository, &oid);
423 if (!tree)
424 die(_("Could not parse object '%s'."), rev);
425 oidcpy(&oid, &tree->object.oid);
426 }
427
428 if (interactive_opts.context < -1)
429 die(_("'%s' cannot be negative"), "--unified");
430 if (interactive_opts.interhunkcontext < -1)
431 die(_("'%s' cannot be negative"), "--inter-hunk-context");
432
433 prepare_repo_settings(the_repository);
434 the_repository->settings.command_requires_full_index = 0;
435
436 if (patch_mode) {
437 if (reset_type != NONE)
438 die(_("options '%s' and '%s' cannot be used together"), "--patch", "--{hard,mixed,soft}");
439 trace2_cmd_mode("patch-interactive");
440 update_ref_status = !!run_add_p(the_repository, ADD_P_RESET,
441 &interactive_opts, rev, &pathspec, 0);
442 goto cleanup;
443 } else {
444 if (interactive_opts.context != -1)
445 die(_("the option '%s' requires '%s'"), "--unified", "--patch");
446 if (interactive_opts.interhunkcontext != -1)
447 die(_("the option '%s' requires '%s'"), "--inter-hunk-context", "--patch");
448 if (!interactive_opts.auto_advance)
449 die(_("the option '%s' requires '%s'"), "--no-auto-advance", "--patch");
450 }
451
452 /* git reset tree [--] paths... can be used to
453 * load chosen paths from the tree into the index without
454 * affecting the working tree nor HEAD. */
455 if (pathspec.nr) {
456 if (reset_type == MIXED)
457 warning(_("--mixed with paths is deprecated; use 'git reset -- <paths>' instead."));
458 else if (reset_type != NONE)
459 die(_("Cannot do %s reset with paths."),
460 _(reset_type_names[reset_type]));
461 }
462 if (reset_type == NONE)
463 reset_type = MIXED; /* by default */
464
465 if (pathspec.nr)
466 trace2_cmd_mode("path");
467 else
468 trace2_cmd_mode(reset_type_names[reset_type]);
469
470 if (reset_type != SOFT && (reset_type != MIXED || repo_get_work_tree(the_repository)))
471 setup_work_tree(the_repository);
472
473 if (reset_type == MIXED && is_bare_repository())
474 die(_("%s reset is not allowed in a bare repository"),
475 _(reset_type_names[reset_type]));
476
477 if (intent_to_add && reset_type != MIXED)
478 die(_("the option '%s' requires '%s'"), "-N", "--mixed");
479
480 if (repo_read_index(the_repository) < 0)
481 die(_("index file corrupt"));
482
483 /* Soft reset does not touch the index file nor the working tree
484 * at all, but requires them in a good order. Other resets reset
485 * the index file to the tree object we are switching to. */
486 if (reset_type == SOFT || reset_type == KEEP)
487 die_if_unmerged_cache(reset_type);
488
489 if (reset_type != SOFT) {
490 struct lock_file lock = LOCK_INIT;
491 repo_hold_locked_index(the_repository, &lock,
492 LOCK_DIE_ON_ERROR);
493 if (reset_type == MIXED) {
494 int flags = quiet ? REFRESH_QUIET : REFRESH_IN_PORCELAIN;
495 if (read_from_tree(&pathspec, &oid, intent_to_add)) {
496 update_ref_status = 1;
497 goto cleanup;
498 }
499 the_repository->index->updated_skipworktree = 1;
500 if (!no_refresh && repo_get_work_tree(the_repository)) {
501 uint64_t t_begin, t_delta_in_ms;
502
503 t_begin = getnanotime();
504 refresh_index(the_repository->index, flags, NULL, NULL,
505 _("Unstaged changes after reset:"));
506 t_delta_in_ms = (getnanotime() - t_begin) / 1000000;
507 if (!quiet && advice_enabled(ADVICE_RESET_NO_REFRESH_WARNING) && t_delta_in_ms > REFRESH_INDEX_DELAY_WARNING_IN_MS) {
508 advise(_("It took %.2f seconds to refresh the index after reset. You can use\n"
509 "'--no-refresh' to avoid this."), t_delta_in_ms / 1000.0);
510 }
511 }
512 } else {
513 struct object_id dummy;
514 char *ref = NULL;
515 int err;
516
517 repo_dwim_ref(the_repository, rev, strlen(rev),
518 &dummy, &ref, 0);
519 if (ref && !starts_with(ref, "refs/"))
520 FREE_AND_NULL(ref);
521
522 err = reset_index(ref, &oid, reset_type, quiet);
523 if (reset_type == KEEP && !err)
524 err = reset_index(ref, &oid, MIXED, quiet);
525 if (err)
526 die(_("Could not reset index file to revision '%s'."), rev);
527 free(ref);
528 }
529
530 if (write_locked_index(the_repository->index, &lock, COMMIT_LOCK))
531 die(_("Could not write new index file."));
532 }
533
534 if (!pathspec.nr && !unborn) {
535 /* Any resets without paths update HEAD to the head being
536 * switched to, saving the previous head in ORIG_HEAD before. */
537 update_ref_status = reset_refs(rev, &oid);
538
539 if (reset_type == HARD && !update_ref_status && !quiet)
540 print_new_head_line(lookup_commit_reference(the_repository, &oid));
541 }
542 if (!pathspec.nr)
543 remove_branch_state(the_repository, 0);
544
545 discard_index(the_repository->index);
546
547 cleanup:
548 clear_pathspec(&pathspec);
549 free(pathspec_from_file);
550 return update_ref_status;
551 }