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