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