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