checkout: do not check out unmerged higher stages randomly
[git/git.git] / builtin-checkout.c
CommitLineData
782c2d65
DB
1#include "cache.h"
2#include "builtin.h"
3#include "parse-options.h"
4#include "refs.h"
5#include "commit.h"
6#include "tree.h"
7#include "tree-walk.h"
8#include "unpack-trees.h"
9#include "dir.h"
10#include "run-command.h"
11#include "merge-recursive.h"
12#include "branch.h"
13#include "diff.h"
14#include "revision.h"
79a1e6b4 15#include "remote.h"
782c2d65
DB
16
17static const char * const checkout_usage[] = {
18 "git checkout [options] <branch>",
19 "git checkout [options] [<branch>] -- <file>...",
20 NULL,
21};
22
23static int post_checkout_hook(struct commit *old, struct commit *new,
24 int changed)
25{
26 struct child_process proc;
27 const char *name = git_path("hooks/post-checkout");
28 const char *argv[5];
29
30 if (access(name, X_OK) < 0)
31 return 0;
32
33 memset(&proc, 0, sizeof(proc));
34 argv[0] = name;
35 argv[1] = xstrdup(sha1_to_hex(old->object.sha1));
36 argv[2] = xstrdup(sha1_to_hex(new->object.sha1));
37 argv[3] = changed ? "1" : "0";
38 argv[4] = NULL;
39 proc.argv = argv;
40 proc.no_stdin = 1;
41 proc.stdout_to_stderr = 1;
42 return run_command(&proc);
43}
44
45static int update_some(const unsigned char *sha1, const char *base, int baselen,
671f0707 46 const char *pathname, unsigned mode, int stage, void *context)
782c2d65
DB
47{
48 int len;
49 struct cache_entry *ce;
50
51 if (S_ISGITLINK(mode))
52 return 0;
53
54 if (S_ISDIR(mode))
55 return READ_TREE_RECURSIVE;
56
57 len = baselen + strlen(pathname);
58 ce = xcalloc(1, cache_entry_size(len));
59 hashcpy(ce->sha1, sha1);
60 memcpy(ce->name, base, baselen);
61 memcpy(ce->name + baselen, pathname, len - baselen);
62 ce->ce_flags = create_ce_flags(len, 0);
63 ce->ce_mode = create_ce_mode(mode);
64 add_cache_entry(ce, ADD_CACHE_OK_TO_ADD | ADD_CACHE_OK_TO_REPLACE);
65 return 0;
66}
67
68static int read_tree_some(struct tree *tree, const char **pathspec)
69{
671f0707 70 read_tree_recursive(tree, "", 0, 0, pathspec, update_some, NULL);
782c2d65 71
782c2d65
DB
72 /* update the index with the given tree's info
73 * for all args, expanding wildcards, and exit
74 * with any non-zero return code.
75 */
76 return 0;
77}
78
8fdcf312
JH
79static int skip_same_name(struct cache_entry *ce, int pos)
80{
81 while (++pos < active_nr &&
82 !strcmp(active_cache[pos]->name, ce->name))
83 ; /* skip */
84 return pos;
85}
86
87
75336878 88static int checkout_paths(struct tree *source_tree, const char **pathspec)
782c2d65
DB
89{
90 int pos;
91 struct checkout state;
92 static char *ps_matched;
93 unsigned char rev[20];
94 int flag;
95 struct commit *head;
d2b3691b 96 int errs = 0;
782c2d65 97
75336878
DB
98 int newfd;
99 struct lock_file *lock_file = xcalloc(1, sizeof(struct lock_file));
100
101 newfd = hold_locked_index(lock_file, 1);
102 read_cache();
103
104 if (source_tree)
105 read_tree_some(source_tree, pathspec);
106
782c2d65
DB
107 for (pos = 0; pathspec[pos]; pos++)
108 ;
109 ps_matched = xcalloc(1, pos);
110
111 for (pos = 0; pos < active_nr; pos++) {
112 struct cache_entry *ce = active_cache[pos];
113 pathspec_match(pathspec, ps_matched, ce->name, 0);
114 }
115
116 if (report_path_error(ps_matched, pathspec, 0))
117 return 1;
118
8fdcf312
JH
119 /* Any unmerged paths? */
120 for (pos = 0; pos < active_nr; pos++) {
121 struct cache_entry *ce = active_cache[pos];
122 if (pathspec_match(pathspec, NULL, ce->name, 0)) {
123 if (!ce_stage(ce))
124 continue;
125 errs = 1;
126 error("path '%s' is unmerged", ce->name);
127 pos = skip_same_name(ce, pos) - 1;
128 }
129 }
130 if (errs)
131 return 1;
132
d2b3691b 133 /* Now we are committed to check them out */
782c2d65
DB
134 memset(&state, 0, sizeof(state));
135 state.force = 1;
136 state.refresh_cache = 1;
137 for (pos = 0; pos < active_nr; pos++) {
138 struct cache_entry *ce = active_cache[pos];
139 if (pathspec_match(pathspec, NULL, ce->name, 0)) {
8fdcf312
JH
140 if (!ce_stage(ce)) {
141 errs |= checkout_entry(ce, &state, NULL);
142 continue;
143 }
144 pos = skip_same_name(ce, pos) - 1;
782c2d65
DB
145 }
146 }
147
75336878
DB
148 if (write_cache(newfd, active_cache, active_nr) ||
149 commit_locked_index(lock_file))
150 die("unable to write new index file");
151
782c2d65
DB
152 resolve_ref("HEAD", rev, 0, &flag);
153 head = lookup_commit_reference_gently(rev, 1);
154
d2b3691b
JH
155 errs |= post_checkout_hook(head, head, 0);
156 return errs;
782c2d65
DB
157}
158
159static void show_local_changes(struct object *head)
160{
161 struct rev_info rev;
162 /* I think we want full paths, even if we're in a subdirectory. */
163 init_revisions(&rev, NULL);
164 rev.abbrev = 0;
165 rev.diffopt.output_format |= DIFF_FORMAT_NAME_STATUS;
166 add_pending_object(&rev, head, NULL);
167 run_diff_index(&rev, 0);
168}
169
170static void describe_detached_head(char *msg, struct commit *commit)
171{
172 struct strbuf sb;
173 strbuf_init(&sb, 0);
174 parse_commit(commit);
27886318 175 pretty_print_commit(CMIT_FMT_ONELINE, commit, &sb, 0, NULL, NULL, 0, 0);
782c2d65
DB
176 fprintf(stderr, "%s %s... %s\n", msg,
177 find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV), sb.buf);
178 strbuf_release(&sb);
179}
180
6286a08d
JH
181struct checkout_opts {
182 int quiet;
183 int merge;
184 int force;
291d823e 185 int writeout_error;
bc052d7f 186
6286a08d
JH
187 char *new_branch;
188 int new_branch_log;
189 enum branch_track track;
190};
782c2d65 191
6286a08d 192static int reset_tree(struct tree *tree, struct checkout_opts *o, int worktree)
782c2d65
DB
193{
194 struct unpack_trees_options opts;
195 struct tree_desc tree_desc;
bc052d7f 196
782c2d65
DB
197 memset(&opts, 0, sizeof(opts));
198 opts.head_idx = -1;
6286a08d
JH
199 opts.update = worktree;
200 opts.skip_unmerged = !worktree;
782c2d65
DB
201 opts.reset = 1;
202 opts.merge = 1;
203 opts.fn = oneway_merge;
6286a08d 204 opts.verbose_update = !o->quiet;
34110cd4
LT
205 opts.src_index = &the_index;
206 opts.dst_index = &the_index;
782c2d65
DB
207 parse_tree(tree);
208 init_tree_desc(&tree_desc, tree->buffer, tree->size);
291d823e
JH
209 switch (unpack_trees(1, &tree_desc, &opts)) {
210 case -2:
211 o->writeout_error = 1;
212 /*
213 * We return 0 nevertheless, as the index is all right
214 * and more importantly we have made best efforts to
215 * update paths in the work tree, and we cannot revert
216 * them.
217 */
218 case 0:
219 return 0;
220 default:
84a5750b 221 return 128;
291d823e 222 }
782c2d65
DB
223}
224
782c2d65
DB
225struct branch_info {
226 const char *name; /* The short name used */
227 const char *path; /* The full name of a real branch */
228 struct commit *commit; /* The named commit */
229};
230
231static void setup_branch_path(struct branch_info *branch)
232{
233 struct strbuf buf;
234 strbuf_init(&buf, 0);
235 strbuf_addstr(&buf, "refs/heads/");
236 strbuf_addstr(&buf, branch->name);
237 branch->path = strbuf_detach(&buf, NULL);
238}
239
240static int merge_working_tree(struct checkout_opts *opts,
75ea38df 241 struct branch_info *old, struct branch_info *new)
782c2d65
DB
242{
243 int ret;
244 struct lock_file *lock_file = xcalloc(1, sizeof(struct lock_file));
245 int newfd = hold_locked_index(lock_file, 1);
246 read_cache();
247
248 if (opts->force) {
6286a08d 249 ret = reset_tree(new->commit->tree, opts, 1);
782c2d65
DB
250 if (ret)
251 return ret;
252 } else {
253 struct tree_desc trees[2];
254 struct tree *tree;
255 struct unpack_trees_options topts;
bc052d7f 256
782c2d65
DB
257 memset(&topts, 0, sizeof(topts));
258 topts.head_idx = -1;
34110cd4
LT
259 topts.src_index = &the_index;
260 topts.dst_index = &the_index;
782c2d65 261
8ccba008
JH
262 topts.msgs.not_uptodate_file = "You have local changes to '%s'; cannot switch branches.";
263
782c2d65
DB
264 refresh_cache(REFRESH_QUIET);
265
266 if (unmerged_cache()) {
04c9e11f
JH
267 error("you need to resolve your current index first");
268 return 1;
782c2d65 269 }
04c9e11f
JH
270
271 /* 2-way merge to the new branch */
272 topts.update = 1;
273 topts.merge = 1;
274 topts.gently = opts->merge;
275 topts.verbose_update = !opts->quiet;
276 topts.fn = twoway_merge;
277 topts.dir = xcalloc(1, sizeof(*topts.dir));
278 topts.dir->show_ignored = 1;
279 topts.dir->exclude_per_dir = ".gitignore";
280 tree = parse_tree_indirect(old->commit->object.sha1);
281 init_tree_desc(&trees[0], tree->buffer, tree->size);
282 tree = parse_tree_indirect(new->commit->object.sha1);
283 init_tree_desc(&trees[1], tree->buffer, tree->size);
284
291d823e
JH
285 ret = unpack_trees(2, trees, &topts);
286 if (ret == -1) {
782c2d65
DB
287 /*
288 * Unpack couldn't do a trivial merge; either
289 * give up or do a real merge, depending on
290 * whether the merge flag was used.
291 */
292 struct tree *result;
293 struct tree *work;
294 if (!opts->merge)
295 return 1;
296 parse_commit(old->commit);
297
298 /* Do more real merge */
299
300 /*
301 * We update the index fully, then write the
302 * tree from the index, then merge the new
303 * branch with the current tree, with the old
304 * branch as the base. Then we reset the index
305 * (but not the working tree) to the new
306 * branch, leaving the working tree as the
307 * merged version, but skipping unmerged
308 * entries in the index.
309 */
310
7ae02a30 311 add_files_to_cache(NULL, NULL, 0);
782c2d65
DB
312 work = write_tree_from_memory();
313
6286a08d 314 ret = reset_tree(new->commit->tree, opts, 1);
782c2d65
DB
315 if (ret)
316 return ret;
317 merge_trees(new->commit->tree, work, old->commit->tree,
318 new->name, "local", &result);
6286a08d 319 ret = reset_tree(new->commit->tree, opts, 0);
84a5750b
JH
320 if (ret)
321 return ret;
782c2d65
DB
322 }
323 }
324
325 if (write_cache(newfd, active_cache, active_nr) ||
326 commit_locked_index(lock_file))
327 die("unable to write new index file");
328
329 if (!opts->force)
330 show_local_changes(&new->commit->object);
331
332 return 0;
333}
334
6d21bf96 335static void report_tracking(struct branch_info *new)
79a1e6b4 336{
6d21bf96 337 struct strbuf sb = STRBUF_INIT;
b56fca07 338 struct branch *branch = branch_get(new->name);
79a1e6b4 339
6d21bf96 340 if (!format_tracking_info(branch, &sb))
79a1e6b4 341 return;
6d21bf96
JH
342 fputs(sb.buf, stdout);
343 strbuf_release(&sb);
b0030db3 344}
79a1e6b4 345
782c2d65
DB
346static void update_refs_for_switch(struct checkout_opts *opts,
347 struct branch_info *old,
348 struct branch_info *new)
349{
350 struct strbuf msg;
351 const char *old_desc;
352 if (opts->new_branch) {
353 create_branch(old->name, opts->new_branch, new->name, 0,
354 opts->new_branch_log, opts->track);
355 new->name = opts->new_branch;
356 setup_branch_path(new);
357 }
358
359 strbuf_init(&msg, 0);
360 old_desc = old->name;
361 if (!old_desc)
362 old_desc = sha1_to_hex(old->commit->object.sha1);
363 strbuf_addf(&msg, "checkout: moving from %s to %s",
364 old_desc, new->name);
365
366 if (new->path) {
367 create_symref("HEAD", new->path, msg.buf);
368 if (!opts->quiet) {
369 if (old->path && !strcmp(new->path, old->path))
370 fprintf(stderr, "Already on \"%s\"\n",
371 new->name);
372 else
373 fprintf(stderr, "Switched to%s branch \"%s\"\n",
374 opts->new_branch ? " a new" : "",
375 new->name);
376 }
377 } else if (strcmp(new->name, "HEAD")) {
378 update_ref(msg.buf, "HEAD", new->commit->object.sha1, NULL,
379 REF_NODEREF, DIE_ON_ERR);
380 if (!opts->quiet) {
381 if (old->path)
382 fprintf(stderr, "Note: moving to \"%s\" which isn't a local branch\nIf you want to create a new branch from this checkout, you may do so\n(now or later) by using -b with the checkout command again. Example:\n git checkout -b <new_branch_name>\n", new->name);
383 describe_detached_head("HEAD is now at", new->commit);
384 }
385 }
386 remove_branch_state();
387 strbuf_release(&msg);
b0030db3 388 if (!opts->quiet && (new->path || !strcmp(new->name, "HEAD")))
6d21bf96 389 report_tracking(new);
782c2d65
DB
390}
391
75ea38df 392static int switch_branches(struct checkout_opts *opts, struct branch_info *new)
782c2d65
DB
393{
394 int ret = 0;
395 struct branch_info old;
396 unsigned char rev[20];
397 int flag;
398 memset(&old, 0, sizeof(old));
399 old.path = resolve_ref("HEAD", rev, 0, &flag);
400 old.commit = lookup_commit_reference_gently(rev, 1);
401 if (!(flag & REF_ISSYMREF))
402 old.path = NULL;
403
404 if (old.path && !prefixcmp(old.path, "refs/heads/"))
405 old.name = old.path + strlen("refs/heads/");
406
407 if (!new->name) {
408 new->name = "HEAD";
409 new->commit = old.commit;
410 if (!new->commit)
411 die("You are on a branch yet to be born");
412 parse_commit(new->commit);
413 }
414
415 /*
416 * If the new thing isn't a branch and isn't HEAD and we're
417 * not starting a new branch, and we want messages, and we
418 * weren't on a branch, and we're moving to a new commit,
419 * describe the old commit.
420 */
421 if (!new->path && strcmp(new->name, "HEAD") && !opts->new_branch &&
422 !opts->quiet && !old.path && new->commit != old.commit)
423 describe_detached_head("Previous HEAD position was", old.commit);
424
425 if (!old.commit) {
426 if (!opts->quiet) {
427 fprintf(stderr, "warning: You appear to be on a branch yet to be born.\n");
428 fprintf(stderr, "warning: Forcing checkout of %s.\n", new->name);
429 }
430 opts->force = 1;
431 }
432
75ea38df 433 ret = merge_working_tree(opts, &old, new);
782c2d65
DB
434 if (ret)
435 return ret;
436
437 update_refs_for_switch(opts, &old, new);
438
291d823e
JH
439 ret = post_checkout_hook(old.commit, new->commit, 1);
440 return ret || opts->writeout_error;
782c2d65
DB
441}
442
782c2d65
DB
443int cmd_checkout(int argc, const char **argv, const char *prefix)
444{
445 struct checkout_opts opts;
446 unsigned char rev[20];
447 const char *arg;
448 struct branch_info new;
449 struct tree *source_tree = NULL;
450 struct option options[] = {
451 OPT__QUIET(&opts.quiet),
452 OPT_STRING('b', NULL, &opts.new_branch, "new branch", "branch"),
453 OPT_BOOLEAN('l', NULL, &opts.new_branch_log, "log for new branch"),
498a6e7e 454 OPT_SET_INT('t', "track", &opts.track, "track",
9ed36cfa 455 BRANCH_TRACK_EXPLICIT),
782c2d65
DB
456 OPT_BOOLEAN('f', NULL, &opts.force, "force"),
457 OPT_BOOLEAN('m', NULL, &opts.merge, "merge"),
b249b552 458 OPT_END(),
782c2d65 459 };
859fdaba 460 int has_dash_dash;
782c2d65
DB
461
462 memset(&opts, 0, sizeof(opts));
463 memset(&new, 0, sizeof(new));
464
ef90d6d4 465 git_config(git_default_config, NULL);
782c2d65 466
9ed36cfa 467 opts.track = git_branch_track;
782c2d65 468
f5242ebf
PH
469 argc = parse_options(argc, argv, options, checkout_usage,
470 PARSE_OPT_KEEP_DASHDASH);
859fdaba
PH
471
472 if (!opts.new_branch && (opts.track != git_branch_track))
473 die("git checkout: --track and --no-track require -b");
474
475 if (opts.force && opts.merge)
476 die("git checkout: -f and -m are incompatible");
477
478 /*
479 * case 1: git checkout <ref> -- [<paths>]
480 *
481 * <ref> must be a valid tree, everything after the '--' must be
482 * a path.
483 *
484 * case 2: git checkout -- [<paths>]
485 *
486 * everything after the '--' must be paths.
487 *
488 * case 3: git checkout <something> [<paths>]
489 *
490 * With no paths, if <something> is a commit, that is to
491 * switch to the branch or detach HEAD at it.
492 *
493 * Otherwise <something> shall not be ambiguous.
494 * - If it's *only* a reference, treat it like case (1).
495 * - If it's only a path, treat it like case (2).
496 * - else: fail.
497 *
498 */
782c2d65 499 if (argc) {
859fdaba
PH
500 if (!strcmp(argv[0], "--")) { /* case (2) */
501 argv++;
502 argc--;
503 goto no_reference;
504 }
505
782c2d65 506 arg = argv[0];
859fdaba
PH
507 has_dash_dash = (argc > 1) && !strcmp(argv[1], "--");
508
509 if (get_sha1(arg, rev)) {
510 if (has_dash_dash) /* case (1) */
511 die("invalid reference: %s", arg);
512 goto no_reference; /* case (3 -> 2) */
513 }
514
515 /* we can't end up being in (2) anymore, eat the argument */
516 argv++;
517 argc--;
518
519 if ((new.commit = lookup_commit_reference_gently(rev, 1))) {
782c2d65
DB
520 new.name = arg;
521 setup_branch_path(&new);
522 if (resolve_ref(new.path, rev, 1, NULL))
523 new.commit = lookup_commit_reference(rev);
524 else
525 new.path = NULL;
526 parse_commit(new.commit);
527 source_tree = new.commit->tree;
859fdaba
PH
528 } else
529 source_tree = parse_tree_indirect(rev);
530
531 if (!source_tree) /* case (1): want a tree */
532 die("reference is not a tree: %s", arg);
533 if (!has_dash_dash) {/* case (3 -> 1) */
534 /*
535 * Do not complain the most common case
536 * git checkout branch
537 * even if there happen to be a file called 'branch';
538 * it would be extremely annoying.
539 */
540 if (argc)
541 verify_non_filename(NULL, arg);
542 }
543 else {
782c2d65
DB
544 argv++;
545 argc--;
546 }
547 }
548
859fdaba 549no_reference:
782c2d65
DB
550 if (argc) {
551 const char **pathspec = get_pathspec(prefix, argv);
301e42ed
AR
552
553 if (!pathspec)
554 die("invalid path specification");
555
782c2d65
DB
556 /* Checkout paths */
557 if (opts.new_branch || opts.force || opts.merge) {
558 if (argc == 1) {
559 die("git checkout: updating paths is incompatible with switching branches/forcing\nDid you intend to checkout '%s' which can not be resolved as commit?", argv[0]);
560 } else {
561 die("git checkout: updating paths is incompatible with switching branches/forcing");
562 }
563 }
564
75336878 565 return checkout_paths(source_tree, pathspec);
782c2d65
DB
566 }
567
568 if (new.name && !new.commit) {
569 die("Cannot switch branch to a non-commit.");
570 }
571
75ea38df 572 return switch_branches(&opts, &new);
782c2d65 573}