reset.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455
  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. #define REFRESH_INDEX_DELAY_WARNING_IN_MS (2 * 1000)
  29. static const char * const git_reset_usage[] = {
  30. N_("git reset [--mixed | --soft | --hard | --merge | --keep] [-q] [<commit>]"),
  31. N_("git reset [-q] [<tree-ish>] [--] <pathspec>..."),
  32. N_("git reset [-q] [--pathspec-from-file [--pathspec-file-nul]] [<tree-ish>]"),
  33. N_("git reset --patch [<tree-ish>] [--] [<pathspec>...]"),
  34. NULL
  35. };
  36. enum reset_type { MIXED, SOFT, HARD, MERGE, KEEP, NONE };
  37. static const char *reset_type_names[] = {
  38. N_("mixed"), N_("soft"), N_("hard"), N_("merge"), N_("keep"), NULL
  39. };
  40. static inline int is_merge(void)
  41. {
  42. return !access(git_path_merge_head(the_repository), F_OK);
  43. }
  44. static int reset_index(const char *ref, const struct object_id *oid, int reset_type, int quiet)
  45. {
  46. int i, nr = 0;
  47. struct tree_desc desc[2];
  48. struct tree *tree;
  49. struct unpack_trees_options opts;
  50. int ret = -1;
  51. memset(&opts, 0, sizeof(opts));
  52. opts.head_idx = 1;
  53. opts.src_index = &the_index;
  54. opts.dst_index = &the_index;
  55. opts.fn = oneway_merge;
  56. opts.merge = 1;
  57. init_checkout_metadata(&opts.meta, ref, oid, NULL);
  58. if (!quiet)
  59. opts.verbose_update = 1;
  60. switch (reset_type) {
  61. case KEEP:
  62. case MERGE:
  63. opts.update = 1;
  64. break;
  65. case HARD:
  66. opts.update = 1;
  67. /* fallthrough */
  68. default:
  69. opts.reset = 1;
  70. }
  71. read_cache_unmerged();
  72. if (reset_type == KEEP) {
  73. struct object_id head_oid;
  74. if (get_oid("HEAD", &head_oid))
  75. return error(_("You do not have a valid HEAD."));
  76. if (!fill_tree_descriptor(the_repository, desc + nr, &head_oid))
  77. return error(_("Failed to find tree of HEAD."));
  78. nr++;
  79. opts.fn = twoway_merge;
  80. }
  81. if (!fill_tree_descriptor(the_repository, desc + nr, oid)) {
  82. error(_("Failed to find tree of %s."), oid_to_hex(oid));
  83. goto out;
  84. }
  85. nr++;
  86. if (unpack_trees(nr, desc, &opts))
  87. goto out;
  88. if (reset_type == MIXED || reset_type == HARD) {
  89. tree = parse_tree_indirect(oid);
  90. prime_cache_tree(the_repository, the_repository->index, tree);
  91. }
  92. ret = 0;
  93. out:
  94. for (i = 0; i < nr; i++)
  95. free((void *)desc[i].buffer);
  96. return ret;
  97. }
  98. static void print_new_head_line(struct commit *commit)
  99. {
  100. struct strbuf buf = STRBUF_INIT;
  101. printf(_("HEAD is now at %s"),
  102. find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV));
  103. pp_commit_easy(CMIT_FMT_ONELINE, commit, &buf);
  104. if (buf.len > 0)
  105. printf(" %s", buf.buf);
  106. putchar('\n');
  107. strbuf_release(&buf);
  108. }
  109. static void update_index_from_diff(struct diff_queue_struct *q,
  110. struct diff_options *opt, void *data)
  111. {
  112. int i;
  113. int intent_to_add = *(int *)data;
  114. for (i = 0; i < q->nr; i++) {
  115. struct diff_filespec *one = q->queue[i]->one;
  116. int is_missing = !(one->mode && !is_null_oid(&one->oid));
  117. struct cache_entry *ce;
  118. if (is_missing && !intent_to_add) {
  119. remove_file_from_cache(one->path);
  120. continue;
  121. }
  122. ce = make_cache_entry(&the_index, one->mode, &one->oid, one->path,
  123. 0, 0);
  124. if (!ce)
  125. die(_("make_cache_entry failed for path '%s'"),
  126. one->path);
  127. if (is_missing) {
  128. ce->ce_flags |= CE_INTENT_TO_ADD;
  129. set_object_name_for_intent_to_add_entry(ce);
  130. }
  131. add_cache_entry(ce, ADD_CACHE_OK_TO_ADD | ADD_CACHE_OK_TO_REPLACE);
  132. }
  133. }
  134. static int read_from_tree(const struct pathspec *pathspec,
  135. struct object_id *tree_oid,
  136. int intent_to_add)
  137. {
  138. struct diff_options opt;
  139. memset(&opt, 0, sizeof(opt));
  140. copy_pathspec(&opt.pathspec, pathspec);
  141. opt.output_format = DIFF_FORMAT_CALLBACK;
  142. opt.format_callback = update_index_from_diff;
  143. opt.format_callback_data = &intent_to_add;
  144. opt.flags.override_submodule_config = 1;
  145. opt.repo = the_repository;
  146. if (do_diff_cache(tree_oid, &opt))
  147. return 1;
  148. diffcore_std(&opt);
  149. diff_flush(&opt);
  150. clear_pathspec(&opt.pathspec);
  151. return 0;
  152. }
  153. static void set_reflog_message(struct strbuf *sb, const char *action,
  154. const char *rev)
  155. {
  156. const char *rla = getenv("GIT_REFLOG_ACTION");
  157. strbuf_reset(sb);
  158. if (rla)
  159. strbuf_addf(sb, "%s: %s", rla, action);
  160. else if (rev)
  161. strbuf_addf(sb, "reset: moving to %s", rev);
  162. else
  163. strbuf_addf(sb, "reset: %s", action);
  164. }
  165. static void die_if_unmerged_cache(int reset_type)
  166. {
  167. if (is_merge() || unmerged_cache())
  168. die(_("Cannot do a %s reset in the middle of a merge."),
  169. _(reset_type_names[reset_type]));
  170. }
  171. static void parse_args(struct pathspec *pathspec,
  172. const char **argv, const char *prefix,
  173. int patch_mode,
  174. const char **rev_ret)
  175. {
  176. const char *rev = "HEAD";
  177. struct object_id unused;
  178. /*
  179. * Possible arguments are:
  180. *
  181. * git reset [-opts] [<rev>]
  182. * git reset [-opts] <tree> [<paths>...]
  183. * git reset [-opts] <tree> -- [<paths>...]
  184. * git reset [-opts] -- [<paths>...]
  185. * git reset [-opts] <paths>...
  186. *
  187. * At this point, argv points immediately after [-opts].
  188. */
  189. if (argv[0]) {
  190. if (!strcmp(argv[0], "--")) {
  191. argv++; /* reset to HEAD, possibly with paths */
  192. } else if (argv[1] && !strcmp(argv[1], "--")) {
  193. rev = argv[0];
  194. argv += 2;
  195. }
  196. /*
  197. * Otherwise, argv[0] could be either <rev> or <paths> and
  198. * has to be unambiguous. If there is a single argument, it
  199. * can not be a tree
  200. */
  201. else if ((!argv[1] && !get_oid_committish(argv[0], &unused)) ||
  202. (argv[1] && !get_oid_treeish(argv[0], &unused))) {
  203. /*
  204. * Ok, argv[0] looks like a commit/tree; it should not
  205. * be a filename.
  206. */
  207. verify_non_filename(prefix, argv[0]);
  208. rev = *argv++;
  209. } else {
  210. /* Otherwise we treat this as a filename */
  211. verify_filename(prefix, argv[0], 1);
  212. }
  213. }
  214. *rev_ret = rev;
  215. if (read_cache() < 0)
  216. die(_("index file corrupt"));
  217. parse_pathspec(pathspec, 0,
  218. PATHSPEC_PREFER_FULL |
  219. (patch_mode ? PATHSPEC_PREFIX_ORIGIN : 0),
  220. prefix, argv);
  221. }
  222. static int reset_refs(const char *rev, const struct object_id *oid)
  223. {
  224. int update_ref_status;
  225. struct strbuf msg = STRBUF_INIT;
  226. struct object_id *orig = NULL, oid_orig,
  227. *old_orig = NULL, oid_old_orig;
  228. if (!get_oid("ORIG_HEAD", &oid_old_orig))
  229. old_orig = &oid_old_orig;
  230. if (!get_oid("HEAD", &oid_orig)) {
  231. orig = &oid_orig;
  232. set_reflog_message(&msg, "updating ORIG_HEAD", NULL);
  233. update_ref(msg.buf, "ORIG_HEAD", orig, old_orig, 0,
  234. UPDATE_REFS_MSG_ON_ERR);
  235. } else if (old_orig)
  236. delete_ref(NULL, "ORIG_HEAD", old_orig, 0);
  237. set_reflog_message(&msg, "updating HEAD", rev);
  238. update_ref_status = update_ref(msg.buf, "HEAD", oid, orig, 0,
  239. UPDATE_REFS_MSG_ON_ERR);
  240. strbuf_release(&msg);
  241. return update_ref_status;
  242. }
  243. static int git_reset_config(const char *var, const char *value, void *cb)
  244. {
  245. if (!strcmp(var, "submodule.recurse"))
  246. return git_default_submodule_config(var, value, cb);
  247. return git_default_config(var, value, cb);
  248. }
  249. int cmd_reset(int argc, const char **argv, const char *prefix)
  250. {
  251. int reset_type = NONE, update_ref_status = 0, quiet = 0;
  252. int patch_mode = 0, pathspec_file_nul = 0, unborn;
  253. const char *rev, *pathspec_from_file = NULL;
  254. struct object_id oid;
  255. struct pathspec pathspec;
  256. int intent_to_add = 0;
  257. const struct option options[] = {
  258. OPT__QUIET(&quiet, N_("be quiet, only report errors")),
  259. OPT_SET_INT(0, "mixed", &reset_type,
  260. N_("reset HEAD and index"), MIXED),
  261. OPT_SET_INT(0, "soft", &reset_type, N_("reset only HEAD"), SOFT),
  262. OPT_SET_INT(0, "hard", &reset_type,
  263. N_("reset HEAD, index and working tree"), HARD),
  264. OPT_SET_INT(0, "merge", &reset_type,
  265. N_("reset HEAD, index and working tree"), MERGE),
  266. OPT_SET_INT(0, "keep", &reset_type,
  267. N_("reset HEAD but keep local changes"), KEEP),
  268. OPT_CALLBACK_F(0, "recurse-submodules", NULL,
  269. "reset", "control recursive updating of submodules",
  270. PARSE_OPT_OPTARG, option_parse_recurse_submodules_worktree_updater),
  271. OPT_BOOL('p', "patch", &patch_mode, N_("select hunks interactively")),
  272. OPT_BOOL('N', "intent-to-add", &intent_to_add,
  273. N_("record only the fact that removed paths will be added later")),
  274. OPT_PATHSPEC_FROM_FILE(&pathspec_from_file),
  275. OPT_PATHSPEC_FILE_NUL(&pathspec_file_nul),
  276. OPT_END()
  277. };
  278. git_config(git_reset_config, NULL);
  279. git_config_get_bool("reset.quiet", &quiet);
  280. argc = parse_options(argc, argv, prefix, options, git_reset_usage,
  281. PARSE_OPT_KEEP_DASHDASH);
  282. parse_args(&pathspec, argv, prefix, patch_mode, &rev);
  283. if (pathspec_from_file) {
  284. if (patch_mode)
  285. die(_("--pathspec-from-file is incompatible with --patch"));
  286. if (pathspec.nr)
  287. die(_("--pathspec-from-file is incompatible with pathspec arguments"));
  288. parse_pathspec_file(&pathspec, 0,
  289. PATHSPEC_PREFER_FULL,
  290. prefix, pathspec_from_file, pathspec_file_nul);
  291. } else if (pathspec_file_nul) {
  292. die(_("--pathspec-file-nul requires --pathspec-from-file"));
  293. }
  294. unborn = !strcmp(rev, "HEAD") && get_oid("HEAD", &oid);
  295. if (unborn) {
  296. /* reset on unborn branch: treat as reset to empty tree */
  297. oidcpy(&oid, the_hash_algo->empty_tree);
  298. } else if (!pathspec.nr && !patch_mode) {
  299. struct commit *commit;
  300. if (get_oid_committish(rev, &oid))
  301. die(_("Failed to resolve '%s' as a valid revision."), rev);
  302. commit = lookup_commit_reference(the_repository, &oid);
  303. if (!commit)
  304. die(_("Could not parse object '%s'."), rev);
  305. oidcpy(&oid, &commit->object.oid);
  306. } else {
  307. struct tree *tree;
  308. if (get_oid_treeish(rev, &oid))
  309. die(_("Failed to resolve '%s' as a valid tree."), rev);
  310. tree = parse_tree_indirect(&oid);
  311. if (!tree)
  312. die(_("Could not parse object '%s'."), rev);
  313. oidcpy(&oid, &tree->object.oid);
  314. }
  315. if (patch_mode) {
  316. if (reset_type != NONE)
  317. die(_("--patch is incompatible with --{hard,mixed,soft}"));
  318. trace2_cmd_mode("patch-interactive");
  319. return run_add_interactive(rev, "--patch=reset", &pathspec);
  320. }
  321. /* git reset tree [--] paths... can be used to
  322. * load chosen paths from the tree into the index without
  323. * affecting the working tree nor HEAD. */
  324. if (pathspec.nr) {
  325. if (reset_type == MIXED)
  326. warning(_("--mixed with paths is deprecated; use 'git reset -- <paths>' instead."));
  327. else if (reset_type != NONE)
  328. die(_("Cannot do %s reset with paths."),
  329. _(reset_type_names[reset_type]));
  330. }
  331. if (reset_type == NONE)
  332. reset_type = MIXED; /* by default */
  333. if (pathspec.nr)
  334. trace2_cmd_mode("path");
  335. else
  336. trace2_cmd_mode(reset_type_names[reset_type]);
  337. if (reset_type != SOFT && (reset_type != MIXED || get_git_work_tree()))
  338. setup_work_tree();
  339. if (reset_type == MIXED && is_bare_repository())
  340. die(_("%s reset is not allowed in a bare repository"),
  341. _(reset_type_names[reset_type]));
  342. if (intent_to_add && reset_type != MIXED)
  343. die(_("-N can only be used with --mixed"));
  344. /* Soft reset does not touch the index file nor the working tree
  345. * at all, but requires them in a good order. Other resets reset
  346. * the index file to the tree object we are switching to. */
  347. if (reset_type == SOFT || reset_type == KEEP)
  348. die_if_unmerged_cache(reset_type);
  349. if (reset_type != SOFT) {
  350. struct lock_file lock = LOCK_INIT;
  351. hold_locked_index(&lock, LOCK_DIE_ON_ERROR);
  352. if (reset_type == MIXED) {
  353. int flags = quiet ? REFRESH_QUIET : REFRESH_IN_PORCELAIN;
  354. if (read_from_tree(&pathspec, &oid, intent_to_add))
  355. return 1;
  356. the_index.updated_skipworktree = 1;
  357. if (!quiet && get_git_work_tree()) {
  358. uint64_t t_begin, t_delta_in_ms;
  359. t_begin = getnanotime();
  360. refresh_index(&the_index, flags, NULL, NULL,
  361. _("Unstaged changes after reset:"));
  362. t_delta_in_ms = (getnanotime() - t_begin) / 1000000;
  363. if (advice_reset_quiet_warning && t_delta_in_ms > REFRESH_INDEX_DELAY_WARNING_IN_MS) {
  364. printf(_("\nIt took %.2f seconds to enumerate unstaged changes after reset. You can\n"
  365. "use '--quiet' to avoid this. Set the config setting reset.quiet to true\n"
  366. "to make this the default.\n"), t_delta_in_ms / 1000.0);
  367. }
  368. }
  369. } else {
  370. struct object_id dummy;
  371. char *ref = NULL;
  372. int err;
  373. dwim_ref(rev, strlen(rev), &dummy, &ref, 0);
  374. if (ref && !starts_with(ref, "refs/"))
  375. ref = NULL;
  376. err = reset_index(ref, &oid, reset_type, quiet);
  377. if (reset_type == KEEP && !err)
  378. err = reset_index(ref, &oid, MIXED, quiet);
  379. if (err)
  380. die(_("Could not reset index file to revision '%s'."), rev);
  381. free(ref);
  382. }
  383. if (write_locked_index(&the_index, &lock, COMMIT_LOCK))
  384. die(_("Could not write new index file."));
  385. }
  386. if (!pathspec.nr && !unborn) {
  387. /* Any resets without paths update HEAD to the head being
  388. * switched to, saving the previous head in ORIG_HEAD before. */
  389. update_ref_status = reset_refs(rev, &oid);
  390. if (reset_type == HARD && !update_ref_status && !quiet)
  391. print_new_head_line(lookup_commit_reference(the_repository, &oid));
  392. }
  393. if (!pathspec.nr)
  394. remove_branch_state(the_repository, 0);
  395. return update_ref_status;
  396. }