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