]> git.ipfire.org Git - thirdparty/git.git/blob - builtin/reset.c
Merge branch 'ab/diff-free-more'
[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_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"
29
30 #define REFRESH_INDEX_DELAY_WARNING_IN_MS (2 * 1000)
31
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
38 };
39
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
43 };
44
45 static inline int is_merge(void)
46 {
47 return !access(git_path_merge_head(the_repository), F_OK);
48 }
49
50 static int reset_index(const char *ref, const struct object_id *oid, int reset_type, int quiet)
51 {
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;
57
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 break;
77 case MIXED:
78 opts.reset = UNPACK_RESET_PROTECT_UNTRACKED;
79 /* but opts.update=0, so working tree not updated */
80 break;
81 default:
82 BUG("invalid reset_type passed to reset_index");
83 }
84
85 read_cache_unmerged();
86
87 if (reset_type == KEEP) {
88 struct object_id head_oid;
89 if (get_oid("HEAD", &head_oid))
90 return error(_("You do not have a valid HEAD."));
91 if (!fill_tree_descriptor(the_repository, desc + nr, &head_oid))
92 return error(_("Failed to find tree of HEAD."));
93 nr++;
94 opts.fn = twoway_merge;
95 }
96
97 if (!fill_tree_descriptor(the_repository, desc + nr, oid)) {
98 error(_("Failed to find tree of %s."), oid_to_hex(oid));
99 goto out;
100 }
101 nr++;
102
103 if (unpack_trees(nr, desc, &opts))
104 goto out;
105
106 if (reset_type == MIXED || reset_type == HARD) {
107 tree = parse_tree_indirect(oid);
108 prime_cache_tree(the_repository, the_repository->index, tree);
109 }
110
111 ret = 0;
112
113 out:
114 for (i = 0; i < nr; i++)
115 free((void *)desc[i].buffer);
116 return ret;
117 }
118
119 static void print_new_head_line(struct commit *commit)
120 {
121 struct strbuf buf = STRBUF_INIT;
122
123 printf(_("HEAD is now at %s"),
124 find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV));
125
126 pp_commit_easy(CMIT_FMT_ONELINE, commit, &buf);
127 if (buf.len > 0)
128 printf(" %s", buf.buf);
129 putchar('\n');
130 strbuf_release(&buf);
131 }
132
133 static void update_index_from_diff(struct diff_queue_struct *q,
134 struct diff_options *opt, void *data)
135 {
136 int i;
137 int intent_to_add = *(int *)data;
138
139 for (i = 0; i < q->nr; i++) {
140 int pos;
141 struct diff_filespec *one = q->queue[i]->one;
142 int is_in_reset_tree = one->mode && !is_null_oid(&one->oid);
143 struct cache_entry *ce;
144
145 if (!is_in_reset_tree && !intent_to_add) {
146 remove_file_from_cache(one->path);
147 continue;
148 }
149
150 ce = make_cache_entry(&the_index, one->mode, &one->oid, one->path,
151 0, 0);
152
153 /*
154 * If the file 1) corresponds to an existing index entry with
155 * skip-worktree set, or 2) does not exist in the index but is
156 * outside the sparse checkout definition, add a skip-worktree bit
157 * to the new index entry. Note that a sparse index will be expanded
158 * if this entry is outside the sparse cone - this is necessary
159 * to properly construct the reset sparse directory.
160 */
161 pos = cache_name_pos(one->path, strlen(one->path));
162 if ((pos >= 0 && ce_skip_worktree(active_cache[pos])) ||
163 (pos < 0 && !path_in_sparse_checkout(one->path, &the_index)))
164 ce->ce_flags |= CE_SKIP_WORKTREE;
165
166 if (!ce)
167 die(_("make_cache_entry failed for path '%s'"),
168 one->path);
169 if (!is_in_reset_tree) {
170 ce->ce_flags |= CE_INTENT_TO_ADD;
171 set_object_name_for_intent_to_add_entry(ce);
172 }
173 add_cache_entry(ce, ADD_CACHE_OK_TO_ADD | ADD_CACHE_OK_TO_REPLACE);
174 }
175 }
176
177 static int pathspec_needs_expanded_index(const struct pathspec *pathspec)
178 {
179 unsigned int i, pos;
180 int res = 0;
181 char *skip_worktree_seen = NULL;
182
183 /*
184 * When using a magic pathspec, assume for the sake of simplicity that
185 * the index needs to be expanded to match all matchable files.
186 */
187 if (pathspec->magic)
188 return 1;
189
190 for (i = 0; i < pathspec->nr; i++) {
191 struct pathspec_item item = pathspec->items[i];
192
193 /*
194 * If the pathspec item has a wildcard, the index should be expanded
195 * if the pathspec has the possibility of matching a subset of entries inside
196 * of a sparse directory (but not the entire directory).
197 *
198 * If the pathspec item is a literal path, the index only needs to be expanded
199 * if a) the pathspec isn't in the sparse checkout cone (to make sure we don't
200 * expand for in-cone files) and b) it doesn't match any sparse directories
201 * (since we can reset whole sparse directories without expanding them).
202 */
203 if (item.nowildcard_len < item.len) {
204 /*
205 * Special case: if the pattern is a path inside the cone
206 * followed by only wildcards, the pattern cannot match
207 * partial sparse directories, so we know we don't need to
208 * expand the index.
209 *
210 * Examples:
211 * - in-cone/foo***: doesn't need expanded index
212 * - not-in-cone/bar*: may need expanded index
213 * - **.c: may need expanded index
214 */
215 if (strspn(item.original + item.nowildcard_len, "*") == item.len - item.nowildcard_len &&
216 path_in_cone_mode_sparse_checkout(item.original, &the_index))
217 continue;
218
219 for (pos = 0; pos < active_nr; pos++) {
220 struct cache_entry *ce = active_cache[pos];
221
222 if (!S_ISSPARSEDIR(ce->ce_mode))
223 continue;
224
225 /*
226 * If the pre-wildcard length is longer than the sparse
227 * directory name and the sparse directory is the first
228 * component of the pathspec, need to expand the index.
229 */
230 if (item.nowildcard_len > ce_namelen(ce) &&
231 !strncmp(item.original, ce->name, ce_namelen(ce))) {
232 res = 1;
233 break;
234 }
235
236 /*
237 * If the pre-wildcard length is shorter than the sparse
238 * directory and the pathspec does not match the whole
239 * directory, need to expand the index.
240 */
241 if (!strncmp(item.original, ce->name, item.nowildcard_len) &&
242 wildmatch(item.original, ce->name, 0)) {
243 res = 1;
244 break;
245 }
246 }
247 } else if (!path_in_cone_mode_sparse_checkout(item.original, &the_index) &&
248 !matches_skip_worktree(pathspec, i, &skip_worktree_seen))
249 res = 1;
250
251 if (res > 0)
252 break;
253 }
254
255 free(skip_worktree_seen);
256 return res;
257 }
258
259 static int read_from_tree(const struct pathspec *pathspec,
260 struct object_id *tree_oid,
261 int intent_to_add)
262 {
263 struct diff_options opt;
264
265 memset(&opt, 0, sizeof(opt));
266 copy_pathspec(&opt.pathspec, pathspec);
267 opt.output_format = DIFF_FORMAT_CALLBACK;
268 opt.format_callback = update_index_from_diff;
269 opt.format_callback_data = &intent_to_add;
270 opt.flags.override_submodule_config = 1;
271 opt.flags.recursive = 1;
272 opt.repo = the_repository;
273 opt.change = diff_change;
274 opt.add_remove = diff_addremove;
275
276 if (pathspec->nr && the_index.sparse_index && pathspec_needs_expanded_index(pathspec))
277 ensure_full_index(&the_index);
278
279 if (do_diff_cache(tree_oid, &opt))
280 return 1;
281 diffcore_std(&opt);
282 diff_flush(&opt);
283
284 return 0;
285 }
286
287 static void set_reflog_message(struct strbuf *sb, const char *action,
288 const char *rev)
289 {
290 const char *rla = getenv("GIT_REFLOG_ACTION");
291
292 strbuf_reset(sb);
293 if (rla)
294 strbuf_addf(sb, "%s: %s", rla, action);
295 else if (rev)
296 strbuf_addf(sb, "reset: moving to %s", rev);
297 else
298 strbuf_addf(sb, "reset: %s", action);
299 }
300
301 static void die_if_unmerged_cache(int reset_type)
302 {
303 if (is_merge() || unmerged_cache())
304 die(_("Cannot do a %s reset in the middle of a merge."),
305 _(reset_type_names[reset_type]));
306
307 }
308
309 static void parse_args(struct pathspec *pathspec,
310 const char **argv, const char *prefix,
311 int patch_mode,
312 const char **rev_ret)
313 {
314 const char *rev = "HEAD";
315 struct object_id unused;
316 /*
317 * Possible arguments are:
318 *
319 * git reset [-opts] [<rev>]
320 * git reset [-opts] <tree> [<paths>...]
321 * git reset [-opts] <tree> -- [<paths>...]
322 * git reset [-opts] -- [<paths>...]
323 * git reset [-opts] <paths>...
324 *
325 * At this point, argv points immediately after [-opts].
326 */
327
328 if (argv[0]) {
329 if (!strcmp(argv[0], "--")) {
330 argv++; /* reset to HEAD, possibly with paths */
331 } else if (argv[1] && !strcmp(argv[1], "--")) {
332 rev = argv[0];
333 argv += 2;
334 }
335 /*
336 * Otherwise, argv[0] could be either <rev> or <paths> and
337 * has to be unambiguous. If there is a single argument, it
338 * can not be a tree
339 */
340 else if ((!argv[1] && !get_oid_committish(argv[0], &unused)) ||
341 (argv[1] && !get_oid_treeish(argv[0], &unused))) {
342 /*
343 * Ok, argv[0] looks like a commit/tree; it should not
344 * be a filename.
345 */
346 verify_non_filename(prefix, argv[0]);
347 rev = *argv++;
348 } else {
349 /* Otherwise we treat this as a filename */
350 verify_filename(prefix, argv[0], 1);
351 }
352 }
353 *rev_ret = rev;
354
355 parse_pathspec(pathspec, 0,
356 PATHSPEC_PREFER_FULL |
357 (patch_mode ? PATHSPEC_PREFIX_ORIGIN : 0),
358 prefix, argv);
359 }
360
361 static int reset_refs(const char *rev, const struct object_id *oid)
362 {
363 int update_ref_status;
364 struct strbuf msg = STRBUF_INIT;
365 struct object_id *orig = NULL, oid_orig,
366 *old_orig = NULL, oid_old_orig;
367
368 if (!get_oid("ORIG_HEAD", &oid_old_orig))
369 old_orig = &oid_old_orig;
370 if (!get_oid("HEAD", &oid_orig)) {
371 orig = &oid_orig;
372 set_reflog_message(&msg, "updating ORIG_HEAD", NULL);
373 update_ref(msg.buf, "ORIG_HEAD", orig, old_orig, 0,
374 UPDATE_REFS_MSG_ON_ERR);
375 } else if (old_orig)
376 delete_ref(NULL, "ORIG_HEAD", old_orig, 0);
377 set_reflog_message(&msg, "updating HEAD", rev);
378 update_ref_status = update_ref(msg.buf, "HEAD", oid, orig, 0,
379 UPDATE_REFS_MSG_ON_ERR);
380 strbuf_release(&msg);
381 return update_ref_status;
382 }
383
384 static int git_reset_config(const char *var, const char *value, void *cb)
385 {
386 if (!strcmp(var, "submodule.recurse"))
387 return git_default_submodule_config(var, value, cb);
388
389 return git_default_config(var, value, cb);
390 }
391
392 int cmd_reset(int argc, const char **argv, const char *prefix)
393 {
394 int reset_type = NONE, update_ref_status = 0, quiet = 0;
395 int patch_mode = 0, pathspec_file_nul = 0, unborn;
396 const char *rev, *pathspec_from_file = NULL;
397 struct object_id oid;
398 struct pathspec pathspec;
399 int intent_to_add = 0;
400 const struct option options[] = {
401 OPT__QUIET(&quiet, N_("be quiet, only report errors")),
402 OPT_SET_INT(0, "mixed", &reset_type,
403 N_("reset HEAD and index"), MIXED),
404 OPT_SET_INT(0, "soft", &reset_type, N_("reset only HEAD"), SOFT),
405 OPT_SET_INT(0, "hard", &reset_type,
406 N_("reset HEAD, index and working tree"), HARD),
407 OPT_SET_INT(0, "merge", &reset_type,
408 N_("reset HEAD, index and working tree"), MERGE),
409 OPT_SET_INT(0, "keep", &reset_type,
410 N_("reset HEAD but keep local changes"), KEEP),
411 OPT_CALLBACK_F(0, "recurse-submodules", NULL,
412 "reset", "control recursive updating of submodules",
413 PARSE_OPT_OPTARG, option_parse_recurse_submodules_worktree_updater),
414 OPT_BOOL('p', "patch", &patch_mode, N_("select hunks interactively")),
415 OPT_BOOL('N', "intent-to-add", &intent_to_add,
416 N_("record only the fact that removed paths will be added later")),
417 OPT_PATHSPEC_FROM_FILE(&pathspec_from_file),
418 OPT_PATHSPEC_FILE_NUL(&pathspec_file_nul),
419 OPT_END()
420 };
421
422 git_config(git_reset_config, NULL);
423 git_config_get_bool("reset.quiet", &quiet);
424
425 argc = parse_options(argc, argv, prefix, options, git_reset_usage,
426 PARSE_OPT_KEEP_DASHDASH);
427 parse_args(&pathspec, argv, prefix, patch_mode, &rev);
428
429 if (pathspec_from_file) {
430 if (patch_mode)
431 die(_("options '%s' and '%s' cannot be used together"), "--pathspec-from-file", "--patch");
432
433 if (pathspec.nr)
434 die(_("'%s' and pathspec arguments cannot be used together"), "--pathspec-from-file");
435
436 parse_pathspec_file(&pathspec, 0,
437 PATHSPEC_PREFER_FULL,
438 prefix, pathspec_from_file, pathspec_file_nul);
439 } else if (pathspec_file_nul) {
440 die(_("the option '%s' requires '%s'"), "--pathspec-file-nul", "--pathspec-from-file");
441 }
442
443 unborn = !strcmp(rev, "HEAD") && get_oid("HEAD", &oid);
444 if (unborn) {
445 /* reset on unborn branch: treat as reset to empty tree */
446 oidcpy(&oid, the_hash_algo->empty_tree);
447 } else if (!pathspec.nr && !patch_mode) {
448 struct commit *commit;
449 if (get_oid_committish(rev, &oid))
450 die(_("Failed to resolve '%s' as a valid revision."), rev);
451 commit = lookup_commit_reference(the_repository, &oid);
452 if (!commit)
453 die(_("Could not parse object '%s'."), rev);
454 oidcpy(&oid, &commit->object.oid);
455 } else {
456 struct tree *tree;
457 if (get_oid_treeish(rev, &oid))
458 die(_("Failed to resolve '%s' as a valid tree."), rev);
459 tree = parse_tree_indirect(&oid);
460 if (!tree)
461 die(_("Could not parse object '%s'."), rev);
462 oidcpy(&oid, &tree->object.oid);
463 }
464
465 if (patch_mode) {
466 if (reset_type != NONE)
467 die(_("options '%s' and '%s' cannot be used together"), "--patch", "--{hard,mixed,soft}");
468 trace2_cmd_mode("patch-interactive");
469 return run_add_interactive(rev, "--patch=reset", &pathspec);
470 }
471
472 /* git reset tree [--] paths... can be used to
473 * load chosen paths from the tree into the index without
474 * affecting the working tree nor HEAD. */
475 if (pathspec.nr) {
476 if (reset_type == MIXED)
477 warning(_("--mixed with paths is deprecated; use 'git reset -- <paths>' instead."));
478 else if (reset_type != NONE)
479 die(_("Cannot do %s reset with paths."),
480 _(reset_type_names[reset_type]));
481 }
482 if (reset_type == NONE)
483 reset_type = MIXED; /* by default */
484
485 if (pathspec.nr)
486 trace2_cmd_mode("path");
487 else
488 trace2_cmd_mode(reset_type_names[reset_type]);
489
490 if (reset_type != SOFT && (reset_type != MIXED || get_git_work_tree()))
491 setup_work_tree();
492
493 if (reset_type == MIXED && is_bare_repository())
494 die(_("%s reset is not allowed in a bare repository"),
495 _(reset_type_names[reset_type]));
496
497 if (intent_to_add && reset_type != MIXED)
498 die(_("the option '%s' requires '%s'"), "-N", "--mixed");
499
500 prepare_repo_settings(the_repository);
501 the_repository->settings.command_requires_full_index = 0;
502
503 if (read_cache() < 0)
504 die(_("index file corrupt"));
505
506 /* Soft reset does not touch the index file nor the working tree
507 * at all, but requires them in a good order. Other resets reset
508 * the index file to the tree object we are switching to. */
509 if (reset_type == SOFT || reset_type == KEEP)
510 die_if_unmerged_cache(reset_type);
511
512 if (reset_type != SOFT) {
513 struct lock_file lock = LOCK_INIT;
514 hold_locked_index(&lock, LOCK_DIE_ON_ERROR);
515 if (reset_type == MIXED) {
516 int flags = quiet ? REFRESH_QUIET : REFRESH_IN_PORCELAIN;
517 if (read_from_tree(&pathspec, &oid, intent_to_add))
518 return 1;
519 the_index.updated_skipworktree = 1;
520 if (!quiet && get_git_work_tree()) {
521 uint64_t t_begin, t_delta_in_ms;
522
523 t_begin = getnanotime();
524 refresh_index(&the_index, flags, NULL, NULL,
525 _("Unstaged changes after reset:"));
526 t_delta_in_ms = (getnanotime() - t_begin) / 1000000;
527 if (advice_enabled(ADVICE_RESET_QUIET_WARNING) && t_delta_in_ms > REFRESH_INDEX_DELAY_WARNING_IN_MS) {
528 printf(_("\nIt took %.2f seconds to enumerate unstaged changes after reset. You can\n"
529 "use '--quiet' to avoid this. Set the config setting reset.quiet to true\n"
530 "to make this the default.\n"), t_delta_in_ms / 1000.0);
531 }
532 }
533 } else {
534 struct object_id dummy;
535 char *ref = NULL;
536 int err;
537
538 dwim_ref(rev, strlen(rev), &dummy, &ref, 0);
539 if (ref && !starts_with(ref, "refs/"))
540 FREE_AND_NULL(ref);
541
542 err = reset_index(ref, &oid, reset_type, quiet);
543 if (reset_type == KEEP && !err)
544 err = reset_index(ref, &oid, MIXED, quiet);
545 if (err)
546 die(_("Could not reset index file to revision '%s'."), rev);
547 free(ref);
548 }
549
550 if (write_locked_index(&the_index, &lock, COMMIT_LOCK))
551 die(_("Could not write new index file."));
552 }
553
554 if (!pathspec.nr && !unborn) {
555 /* Any resets without paths update HEAD to the head being
556 * switched to, saving the previous head in ORIG_HEAD before. */
557 update_ref_status = reset_refs(rev, &oid);
558
559 if (reset_type == HARD && !update_ref_status && !quiet)
560 print_new_head_line(lookup_commit_reference(the_repository, &oid));
561 }
562 if (!pathspec.nr)
563 remove_branch_state(the_repository, 0);
564
565 return update_ref_status;
566 }