checkout: reject if the branch is already checked out elsewhere
[alt-git.git] / builtin / checkout.c
blob01a28b4864683118c665743cf956b05bbd2b625c
1 #include "builtin.h"
2 #include "lockfile.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 "cache-tree.h"
9 #include "unpack-trees.h"
10 #include "dir.h"
11 #include "run-command.h"
12 #include "merge-recursive.h"
13 #include "branch.h"
14 #include "diff.h"
15 #include "revision.h"
16 #include "remote.h"
17 #include "blob.h"
18 #include "xdiff-interface.h"
19 #include "ll-merge.h"
20 #include "resolve-undo.h"
21 #include "submodule.h"
22 #include "argv-array.h"
24 static const char * const checkout_usage[] = {
25 N_("git checkout [options] <branch>"),
26 N_("git checkout [options] [<branch>] -- <file>..."),
27 NULL,
30 struct checkout_opts {
31 int patch_mode;
32 int quiet;
33 int merge;
34 int force;
35 int force_detach;
36 int writeout_stage;
37 int overwrite_ignore;
38 int ignore_skipworktree;
40 const char *new_branch;
41 const char *new_branch_force;
42 const char *new_orphan_branch;
43 int new_branch_log;
44 enum branch_track track;
45 struct diff_options diff_options;
47 int branch_exists;
48 const char *prefix;
49 struct pathspec pathspec;
50 struct tree *source_tree;
52 const char *new_worktree;
53 const char **saved_argv;
54 int new_worktree_mode;
57 static int post_checkout_hook(struct commit *old, struct commit *new,
58 int changed)
60 return run_hook_le(NULL, "post-checkout",
61 sha1_to_hex(old ? old->object.sha1 : null_sha1),
62 sha1_to_hex(new ? new->object.sha1 : null_sha1),
63 changed ? "1" : "0", NULL);
64 /* "new" can be NULL when checking out from the index before
65 a commit exists. */
69 static int update_some(const unsigned char *sha1, const char *base, int baselen,
70 const char *pathname, unsigned mode, int stage, void *context)
72 int len;
73 struct cache_entry *ce;
75 if (S_ISDIR(mode))
76 return READ_TREE_RECURSIVE;
78 len = baselen + strlen(pathname);
79 ce = xcalloc(1, cache_entry_size(len));
80 hashcpy(ce->sha1, sha1);
81 memcpy(ce->name, base, baselen);
82 memcpy(ce->name + baselen, pathname, len - baselen);
83 ce->ce_flags = create_ce_flags(0) | CE_UPDATE;
84 ce->ce_namelen = len;
85 ce->ce_mode = create_ce_mode(mode);
86 add_cache_entry(ce, ADD_CACHE_OK_TO_ADD | ADD_CACHE_OK_TO_REPLACE);
87 return 0;
90 static int read_tree_some(struct tree *tree, const struct pathspec *pathspec)
92 read_tree_recursive(tree, "", 0, 0, pathspec, update_some, NULL);
94 /* update the index with the given tree's info
95 * for all args, expanding wildcards, and exit
96 * with any non-zero return code.
98 return 0;
101 static int skip_same_name(const struct cache_entry *ce, int pos)
103 while (++pos < active_nr &&
104 !strcmp(active_cache[pos]->name, ce->name))
105 ; /* skip */
106 return pos;
109 static int check_stage(int stage, const struct cache_entry *ce, int pos)
111 while (pos < active_nr &&
112 !strcmp(active_cache[pos]->name, ce->name)) {
113 if (ce_stage(active_cache[pos]) == stage)
114 return 0;
115 pos++;
117 if (stage == 2)
118 return error(_("path '%s' does not have our version"), ce->name);
119 else
120 return error(_("path '%s' does not have their version"), ce->name);
123 static int check_stages(unsigned stages, const struct cache_entry *ce, int pos)
125 unsigned seen = 0;
126 const char *name = ce->name;
128 while (pos < active_nr) {
129 ce = active_cache[pos];
130 if (strcmp(name, ce->name))
131 break;
132 seen |= (1 << ce_stage(ce));
133 pos++;
135 if ((stages & seen) != stages)
136 return error(_("path '%s' does not have all necessary versions"),
137 name);
138 return 0;
141 static int checkout_stage(int stage, struct cache_entry *ce, int pos,
142 struct checkout *state)
144 while (pos < active_nr &&
145 !strcmp(active_cache[pos]->name, ce->name)) {
146 if (ce_stage(active_cache[pos]) == stage)
147 return checkout_entry(active_cache[pos], state, NULL);
148 pos++;
150 if (stage == 2)
151 return error(_("path '%s' does not have our version"), ce->name);
152 else
153 return error(_("path '%s' does not have their version"), ce->name);
156 static int checkout_merged(int pos, struct checkout *state)
158 struct cache_entry *ce = active_cache[pos];
159 const char *path = ce->name;
160 mmfile_t ancestor, ours, theirs;
161 int status;
162 unsigned char sha1[20];
163 mmbuffer_t result_buf;
164 unsigned char threeway[3][20];
165 unsigned mode = 0;
167 memset(threeway, 0, sizeof(threeway));
168 while (pos < active_nr) {
169 int stage;
170 stage = ce_stage(ce);
171 if (!stage || strcmp(path, ce->name))
172 break;
173 hashcpy(threeway[stage - 1], ce->sha1);
174 if (stage == 2)
175 mode = create_ce_mode(ce->ce_mode);
176 pos++;
177 ce = active_cache[pos];
179 if (is_null_sha1(threeway[1]) || is_null_sha1(threeway[2]))
180 return error(_("path '%s' does not have necessary versions"), path);
182 read_mmblob(&ancestor, threeway[0]);
183 read_mmblob(&ours, threeway[1]);
184 read_mmblob(&theirs, threeway[2]);
187 * NEEDSWORK: re-create conflicts from merges with
188 * merge.renormalize set, too
190 status = ll_merge(&result_buf, path, &ancestor, "base",
191 &ours, "ours", &theirs, "theirs", NULL);
192 free(ancestor.ptr);
193 free(ours.ptr);
194 free(theirs.ptr);
195 if (status < 0 || !result_buf.ptr) {
196 free(result_buf.ptr);
197 return error(_("path '%s': cannot merge"), path);
201 * NEEDSWORK:
202 * There is absolutely no reason to write this as a blob object
203 * and create a phony cache entry just to leak. This hack is
204 * primarily to get to the write_entry() machinery that massages
205 * the contents to work-tree format and writes out which only
206 * allows it for a cache entry. The code in write_entry() needs
207 * to be refactored to allow us to feed a <buffer, size, mode>
208 * instead of a cache entry. Such a refactoring would help
209 * merge_recursive as well (it also writes the merge result to the
210 * object database even when it may contain conflicts).
212 if (write_sha1_file(result_buf.ptr, result_buf.size,
213 blob_type, sha1))
214 die(_("Unable to add merge result for '%s'"), path);
215 ce = make_cache_entry(mode, sha1, path, 2, 0);
216 if (!ce)
217 die(_("make_cache_entry failed for path '%s'"), path);
218 status = checkout_entry(ce, state, NULL);
219 return status;
222 static int checkout_paths(const struct checkout_opts *opts,
223 const char *revision)
225 int pos;
226 struct checkout state;
227 static char *ps_matched;
228 unsigned char rev[20];
229 int flag;
230 struct commit *head;
231 int errs = 0;
232 struct lock_file *lock_file;
234 if (opts->track != BRANCH_TRACK_UNSPECIFIED)
235 die(_("'%s' cannot be used with updating paths"), "--track");
237 if (opts->new_branch_log)
238 die(_("'%s' cannot be used with updating paths"), "-l");
240 if (opts->force && opts->patch_mode)
241 die(_("'%s' cannot be used with updating paths"), "-f");
243 if (opts->force_detach)
244 die(_("'%s' cannot be used with updating paths"), "--detach");
246 if (opts->merge && opts->patch_mode)
247 die(_("'%s' cannot be used with %s"), "--merge", "--patch");
249 if (opts->force && opts->merge)
250 die(_("'%s' cannot be used with %s"), "-f", "-m");
252 if (opts->new_branch)
253 die(_("Cannot update paths and switch to branch '%s' at the same time."),
254 opts->new_branch);
256 if (opts->new_worktree)
257 die(_("'%s' cannot be used with updating paths"), "--to");
259 if (opts->patch_mode)
260 return run_add_interactive(revision, "--patch=checkout",
261 &opts->pathspec);
263 lock_file = xcalloc(1, sizeof(struct lock_file));
265 hold_locked_index(lock_file, 1);
266 if (read_cache_preload(&opts->pathspec) < 0)
267 return error(_("corrupt index file"));
269 if (opts->source_tree)
270 read_tree_some(opts->source_tree, &opts->pathspec);
272 ps_matched = xcalloc(1, opts->pathspec.nr);
275 * Make sure all pathspecs participated in locating the paths
276 * to be checked out.
278 for (pos = 0; pos < active_nr; pos++) {
279 struct cache_entry *ce = active_cache[pos];
280 ce->ce_flags &= ~CE_MATCHED;
281 if (!opts->ignore_skipworktree && ce_skip_worktree(ce))
282 continue;
283 if (opts->source_tree && !(ce->ce_flags & CE_UPDATE))
285 * "git checkout tree-ish -- path", but this entry
286 * is in the original index; it will not be checked
287 * out to the working tree and it does not matter
288 * if pathspec matched this entry. We will not do
289 * anything to this entry at all.
291 continue;
293 * Either this entry came from the tree-ish we are
294 * checking the paths out of, or we are checking out
295 * of the index.
297 * If it comes from the tree-ish, we already know it
298 * matches the pathspec and could just stamp
299 * CE_MATCHED to it from update_some(). But we still
300 * need ps_matched and read_tree_recursive (and
301 * eventually tree_entry_interesting) cannot fill
302 * ps_matched yet. Once it can, we can avoid calling
303 * match_pathspec() for _all_ entries when
304 * opts->source_tree != NULL.
306 if (ce_path_match(ce, &opts->pathspec, ps_matched))
307 ce->ce_flags |= CE_MATCHED;
310 if (report_path_error(ps_matched, &opts->pathspec, opts->prefix)) {
311 free(ps_matched);
312 return 1;
314 free(ps_matched);
316 /* "checkout -m path" to recreate conflicted state */
317 if (opts->merge)
318 unmerge_marked_index(&the_index);
320 /* Any unmerged paths? */
321 for (pos = 0; pos < active_nr; pos++) {
322 const struct cache_entry *ce = active_cache[pos];
323 if (ce->ce_flags & CE_MATCHED) {
324 if (!ce_stage(ce))
325 continue;
326 if (opts->force) {
327 warning(_("path '%s' is unmerged"), ce->name);
328 } else if (opts->writeout_stage) {
329 errs |= check_stage(opts->writeout_stage, ce, pos);
330 } else if (opts->merge) {
331 errs |= check_stages((1<<2) | (1<<3), ce, pos);
332 } else {
333 errs = 1;
334 error(_("path '%s' is unmerged"), ce->name);
336 pos = skip_same_name(ce, pos) - 1;
339 if (errs)
340 return 1;
342 /* Now we are committed to check them out */
343 memset(&state, 0, sizeof(state));
344 state.force = 1;
345 state.refresh_cache = 1;
346 state.istate = &the_index;
347 for (pos = 0; pos < active_nr; pos++) {
348 struct cache_entry *ce = active_cache[pos];
349 if (ce->ce_flags & CE_MATCHED) {
350 if (!ce_stage(ce)) {
351 errs |= checkout_entry(ce, &state, NULL);
352 continue;
354 if (opts->writeout_stage)
355 errs |= checkout_stage(opts->writeout_stage, ce, pos, &state);
356 else if (opts->merge)
357 errs |= checkout_merged(pos, &state);
358 pos = skip_same_name(ce, pos) - 1;
362 if (write_locked_index(&the_index, lock_file, COMMIT_LOCK))
363 die(_("unable to write new index file"));
365 read_ref_full("HEAD", 0, rev, &flag);
366 head = lookup_commit_reference_gently(rev, 1);
368 errs |= post_checkout_hook(head, head, 0);
369 return errs;
372 static void show_local_changes(struct object *head,
373 const struct diff_options *opts)
375 struct rev_info rev;
376 /* I think we want full paths, even if we're in a subdirectory. */
377 init_revisions(&rev, NULL);
378 rev.diffopt.flags = opts->flags;
379 rev.diffopt.output_format |= DIFF_FORMAT_NAME_STATUS;
380 diff_setup_done(&rev.diffopt);
381 add_pending_object(&rev, head, NULL);
382 run_diff_index(&rev, 0);
385 static void describe_detached_head(const char *msg, struct commit *commit)
387 struct strbuf sb = STRBUF_INIT;
388 if (!parse_commit(commit))
389 pp_commit_easy(CMIT_FMT_ONELINE, commit, &sb);
390 fprintf(stderr, "%s %s... %s\n", msg,
391 find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV), sb.buf);
392 strbuf_release(&sb);
395 static int reset_tree(struct tree *tree, const struct checkout_opts *o,
396 int worktree, int *writeout_error)
398 struct unpack_trees_options opts;
399 struct tree_desc tree_desc;
401 memset(&opts, 0, sizeof(opts));
402 opts.head_idx = -1;
403 opts.update = worktree;
404 opts.skip_unmerged = !worktree;
405 opts.reset = 1;
406 opts.merge = 1;
407 opts.fn = oneway_merge;
408 opts.verbose_update = !o->quiet && isatty(2);
409 opts.src_index = &the_index;
410 opts.dst_index = &the_index;
411 parse_tree(tree);
412 init_tree_desc(&tree_desc, tree->buffer, tree->size);
413 switch (unpack_trees(1, &tree_desc, &opts)) {
414 case -2:
415 *writeout_error = 1;
417 * We return 0 nevertheless, as the index is all right
418 * and more importantly we have made best efforts to
419 * update paths in the work tree, and we cannot revert
420 * them.
422 case 0:
423 return 0;
424 default:
425 return 128;
429 struct branch_info {
430 const char *name; /* The short name used */
431 const char *path; /* The full name of a real branch */
432 struct commit *commit; /* The named commit */
434 * if not null the branch is detached because it's already
435 * checked out in this checkout
437 char *checkout;
440 static void setup_branch_path(struct branch_info *branch)
442 struct strbuf buf = STRBUF_INIT;
444 strbuf_branchname(&buf, branch->name);
445 if (strcmp(buf.buf, branch->name))
446 branch->name = xstrdup(buf.buf);
447 strbuf_splice(&buf, 0, 0, "refs/heads/", 11);
448 branch->path = strbuf_detach(&buf, NULL);
451 static int merge_working_tree(const struct checkout_opts *opts,
452 struct branch_info *old,
453 struct branch_info *new,
454 int *writeout_error)
456 int ret;
457 struct lock_file *lock_file = xcalloc(1, sizeof(struct lock_file));
459 hold_locked_index(lock_file, 1);
460 if (read_cache_preload(NULL) < 0)
461 return error(_("corrupt index file"));
463 resolve_undo_clear();
464 if (opts->force) {
465 ret = reset_tree(new->commit->tree, opts, 1, writeout_error);
466 if (ret)
467 return ret;
468 } else {
469 struct tree_desc trees[2];
470 struct tree *tree;
471 struct unpack_trees_options topts;
473 memset(&topts, 0, sizeof(topts));
474 topts.head_idx = -1;
475 topts.src_index = &the_index;
476 topts.dst_index = &the_index;
478 setup_unpack_trees_porcelain(&topts, "checkout");
480 refresh_cache(REFRESH_QUIET);
482 if (unmerged_cache()) {
483 error(_("you need to resolve your current index first"));
484 return 1;
487 /* 2-way merge to the new branch */
488 topts.initial_checkout = is_cache_unborn();
489 topts.update = 1;
490 topts.merge = 1;
491 topts.gently = opts->merge && old->commit;
492 topts.verbose_update = !opts->quiet && isatty(2);
493 topts.fn = twoway_merge;
494 if (opts->overwrite_ignore) {
495 topts.dir = xcalloc(1, sizeof(*topts.dir));
496 topts.dir->flags |= DIR_SHOW_IGNORED;
497 setup_standard_excludes(topts.dir);
499 tree = parse_tree_indirect(old->commit && !opts->new_worktree_mode ?
500 old->commit->object.sha1 :
501 EMPTY_TREE_SHA1_BIN);
502 init_tree_desc(&trees[0], tree->buffer, tree->size);
503 tree = parse_tree_indirect(new->commit->object.sha1);
504 init_tree_desc(&trees[1], tree->buffer, tree->size);
506 ret = unpack_trees(2, trees, &topts);
507 if (ret == -1) {
509 * Unpack couldn't do a trivial merge; either
510 * give up or do a real merge, depending on
511 * whether the merge flag was used.
513 struct tree *result;
514 struct tree *work;
515 struct merge_options o;
516 if (!opts->merge)
517 return 1;
520 * Without old->commit, the below is the same as
521 * the two-tree unpack we already tried and failed.
523 if (!old->commit)
524 return 1;
526 /* Do more real merge */
529 * We update the index fully, then write the
530 * tree from the index, then merge the new
531 * branch with the current tree, with the old
532 * branch as the base. Then we reset the index
533 * (but not the working tree) to the new
534 * branch, leaving the working tree as the
535 * merged version, but skipping unmerged
536 * entries in the index.
539 add_files_to_cache(NULL, NULL, 0);
541 * NEEDSWORK: carrying over local changes
542 * when branches have different end-of-line
543 * normalization (or clean+smudge rules) is
544 * a pain; plumb in an option to set
545 * o.renormalize?
547 init_merge_options(&o);
548 o.verbosity = 0;
549 work = write_tree_from_memory(&o);
551 ret = reset_tree(new->commit->tree, opts, 1,
552 writeout_error);
553 if (ret)
554 return ret;
555 o.ancestor = old->name;
556 o.branch1 = new->name;
557 o.branch2 = "local";
558 merge_trees(&o, new->commit->tree, work,
559 old->commit->tree, &result);
560 ret = reset_tree(new->commit->tree, opts, 0,
561 writeout_error);
562 if (ret)
563 return ret;
567 if (!active_cache_tree)
568 active_cache_tree = cache_tree();
570 if (!cache_tree_fully_valid(active_cache_tree))
571 cache_tree_update(&the_index, WRITE_TREE_SILENT | WRITE_TREE_REPAIR);
573 if (write_locked_index(&the_index, lock_file, COMMIT_LOCK))
574 die(_("unable to write new index file"));
576 if (!opts->force && !opts->quiet)
577 show_local_changes(&new->commit->object, &opts->diff_options);
579 return 0;
582 static void report_tracking(struct branch_info *new)
584 struct strbuf sb = STRBUF_INIT;
585 struct branch *branch = branch_get(new->name);
587 if (!format_tracking_info(branch, &sb))
588 return;
589 fputs(sb.buf, stdout);
590 strbuf_release(&sb);
593 static void update_refs_for_switch(const struct checkout_opts *opts,
594 struct branch_info *old,
595 struct branch_info *new)
597 struct strbuf msg = STRBUF_INIT;
598 const char *old_desc, *reflog_msg;
599 if (opts->new_branch) {
600 if (opts->new_orphan_branch) {
601 if (opts->new_branch_log && !log_all_ref_updates) {
602 int temp;
603 struct strbuf log_file = STRBUF_INIT;
604 int ret;
605 const char *ref_name;
607 ref_name = mkpath("refs/heads/%s", opts->new_orphan_branch);
608 temp = log_all_ref_updates;
609 log_all_ref_updates = 1;
610 ret = log_ref_setup(ref_name, &log_file);
611 log_all_ref_updates = temp;
612 strbuf_release(&log_file);
613 if (ret) {
614 fprintf(stderr, _("Can not do reflog for '%s'\n"),
615 opts->new_orphan_branch);
616 return;
620 else
621 create_branch(old->name, opts->new_branch, new->name,
622 opts->new_branch_force ? 1 : 0,
623 opts->new_branch_log,
624 opts->new_branch_force ? 1 : 0,
625 opts->quiet,
626 opts->track);
627 new->name = opts->new_branch;
628 setup_branch_path(new);
631 old_desc = old->name;
632 if (!old_desc && old->commit)
633 old_desc = sha1_to_hex(old->commit->object.sha1);
635 reflog_msg = getenv("GIT_REFLOG_ACTION");
636 if (!reflog_msg)
637 strbuf_addf(&msg, "checkout: moving from %s to %s",
638 old_desc ? old_desc : "(invalid)", new->name);
639 else
640 strbuf_insert(&msg, 0, reflog_msg, strlen(reflog_msg));
642 if (!strcmp(new->name, "HEAD") && !new->path && !opts->force_detach) {
643 /* Nothing to do. */
644 } else if (opts->force_detach || !new->path) { /* No longer on any branch. */
645 update_ref(msg.buf, "HEAD", new->commit->object.sha1, NULL,
646 REF_NODEREF, UPDATE_REFS_DIE_ON_ERR);
647 if (!opts->quiet) {
648 if (old->path && advice_detached_head)
649 detach_advice(new->name);
650 describe_detached_head(_("HEAD is now at"), new->commit);
652 } else if (new->path) { /* Switch branches. */
653 create_symref("HEAD", new->path, msg.buf);
654 if (!opts->quiet) {
655 if (old->path && !strcmp(new->path, old->path)) {
656 if (opts->new_branch_force)
657 fprintf(stderr, _("Reset branch '%s'\n"),
658 new->name);
659 else
660 fprintf(stderr, _("Already on '%s'\n"),
661 new->name);
662 } else if (opts->new_branch) {
663 if (opts->branch_exists)
664 fprintf(stderr, _("Switched to and reset branch '%s'\n"), new->name);
665 else
666 fprintf(stderr, _("Switched to a new branch '%s'\n"), new->name);
667 } else {
668 fprintf(stderr, _("Switched to branch '%s'\n"),
669 new->name);
672 if (old->path && old->name) {
673 if (!ref_exists(old->path) && reflog_exists(old->path))
674 delete_reflog(old->path);
677 remove_branch_state();
678 strbuf_release(&msg);
679 if (!opts->quiet &&
680 (new->path || (!opts->force_detach && !strcmp(new->name, "HEAD"))))
681 report_tracking(new);
684 static int add_pending_uninteresting_ref(const char *refname,
685 const unsigned char *sha1,
686 int flags, void *cb_data)
688 add_pending_sha1(cb_data, refname, sha1, UNINTERESTING);
689 return 0;
692 static void describe_one_orphan(struct strbuf *sb, struct commit *commit)
694 strbuf_addstr(sb, " ");
695 strbuf_addstr(sb,
696 find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV));
697 strbuf_addch(sb, ' ');
698 if (!parse_commit(commit))
699 pp_commit_easy(CMIT_FMT_ONELINE, commit, sb);
700 strbuf_addch(sb, '\n');
703 #define ORPHAN_CUTOFF 4
704 static void suggest_reattach(struct commit *commit, struct rev_info *revs)
706 struct commit *c, *last = NULL;
707 struct strbuf sb = STRBUF_INIT;
708 int lost = 0;
709 while ((c = get_revision(revs)) != NULL) {
710 if (lost < ORPHAN_CUTOFF)
711 describe_one_orphan(&sb, c);
712 last = c;
713 lost++;
715 if (ORPHAN_CUTOFF < lost) {
716 int more = lost - ORPHAN_CUTOFF;
717 if (more == 1)
718 describe_one_orphan(&sb, last);
719 else
720 strbuf_addf(&sb, _(" ... and %d more.\n"), more);
723 fprintf(stderr,
725 /* The singular version */
726 "Warning: you are leaving %d commit behind, "
727 "not connected to\n"
728 "any of your branches:\n\n"
729 "%s\n",
730 /* The plural version */
731 "Warning: you are leaving %d commits behind, "
732 "not connected to\n"
733 "any of your branches:\n\n"
734 "%s\n",
735 /* Give ngettext() the count */
736 lost),
737 lost,
738 sb.buf);
739 strbuf_release(&sb);
741 if (advice_detached_head)
742 fprintf(stderr,
744 "If you want to keep them by creating a new branch, "
745 "this may be a good time\nto do so with:\n\n"
746 " git branch new_branch_name %s\n\n"),
747 find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV));
751 * We are about to leave commit that was at the tip of a detached
752 * HEAD. If it is not reachable from any ref, this is the last chance
753 * for the user to do so without resorting to reflog.
755 static void orphaned_commit_warning(struct commit *old, struct commit *new)
757 struct rev_info revs;
758 struct object *object = &old->object;
759 struct object_array refs;
761 init_revisions(&revs, NULL);
762 setup_revisions(0, NULL, &revs, NULL);
764 object->flags &= ~UNINTERESTING;
765 add_pending_object(&revs, object, sha1_to_hex(object->sha1));
767 for_each_ref(add_pending_uninteresting_ref, &revs);
768 add_pending_sha1(&revs, "HEAD", new->object.sha1, UNINTERESTING);
770 refs = revs.pending;
771 revs.leak_pending = 1;
773 if (prepare_revision_walk(&revs))
774 die(_("internal error in revision walk"));
775 if (!(old->object.flags & UNINTERESTING))
776 suggest_reattach(old, &revs);
777 else
778 describe_detached_head(_("Previous HEAD position was"), old);
780 clear_commit_marks_for_object_array(&refs, ALL_REV_FLAGS);
781 free(refs.objects);
784 static int switch_branches(const struct checkout_opts *opts,
785 struct branch_info *new)
787 int ret = 0;
788 struct branch_info old;
789 void *path_to_free;
790 unsigned char rev[20];
791 int flag, writeout_error = 0;
792 memset(&old, 0, sizeof(old));
793 old.path = path_to_free = resolve_refdup("HEAD", 0, rev, &flag);
794 old.commit = lookup_commit_reference_gently(rev, 1);
795 if (!(flag & REF_ISSYMREF))
796 old.path = NULL;
798 if (old.path)
799 skip_prefix(old.path, "refs/heads/", &old.name);
801 if (!new->name) {
802 new->name = "HEAD";
803 new->commit = old.commit;
804 if (!new->commit)
805 die(_("You are on a branch yet to be born"));
806 parse_commit_or_die(new->commit);
809 ret = merge_working_tree(opts, &old, new, &writeout_error);
810 if (ret) {
811 free(path_to_free);
812 return ret;
815 if (!opts->quiet && !old.path && old.commit &&
816 new->commit != old.commit && !opts->new_worktree_mode)
817 orphaned_commit_warning(old.commit, new->commit);
819 update_refs_for_switch(opts, &old, new);
821 ret = post_checkout_hook(old.commit, new->commit, 1);
822 free(path_to_free);
823 return ret || writeout_error;
826 static int prepare_linked_checkout(const struct checkout_opts *opts,
827 struct branch_info *new)
829 struct strbuf sb_git = STRBUF_INIT, sb_repo = STRBUF_INIT;
830 struct strbuf sb = STRBUF_INIT;
831 const char *path = opts->new_worktree, *name;
832 struct stat st;
833 struct child_process cp;
834 int counter = 0, len, ret;
836 if (!new->commit)
837 die(_("no branch specified"));
838 if (file_exists(path))
839 die(_("'%s' already exists"), path);
841 len = strlen(path);
842 while (len && is_dir_sep(path[len - 1]))
843 len--;
845 for (name = path + len - 1; name > path; name--)
846 if (is_dir_sep(*name)) {
847 name++;
848 break;
850 strbuf_addstr(&sb_repo,
851 git_path("worktrees/%.*s", (int)(path + len - name), name));
852 len = sb_repo.len;
853 if (safe_create_leading_directories_const(sb_repo.buf))
854 die_errno(_("could not create leading directories of '%s'"),
855 sb_repo.buf);
856 while (!stat(sb_repo.buf, &st)) {
857 counter++;
858 strbuf_setlen(&sb_repo, len);
859 strbuf_addf(&sb_repo, "%d", counter);
861 name = strrchr(sb_repo.buf, '/') + 1;
862 if (mkdir(sb_repo.buf, 0777))
863 die_errno(_("could not create directory of '%s'"), sb_repo.buf);
866 * lock the incomplete repo so prune won't delete it, unlock
867 * after the preparation is over.
869 strbuf_addf(&sb, "%s/locked", sb_repo.buf);
870 write_file(sb.buf, 1, "initializing\n");
872 strbuf_addf(&sb_git, "%s/.git", path);
873 if (safe_create_leading_directories_const(sb_git.buf))
874 die_errno(_("could not create leading directories of '%s'"),
875 sb_git.buf);
877 strbuf_reset(&sb);
878 strbuf_addf(&sb, "%s/gitdir", sb_repo.buf);
879 write_file(sb.buf, 1, "%s\n", real_path(sb_git.buf));
880 write_file(sb_git.buf, 1, "gitdir: %s/worktrees/%s\n",
881 real_path(get_git_common_dir()), name);
883 * This is to keep resolve_ref() happy. We need a valid HEAD
884 * or is_git_directory() will reject the directory. Any valid
885 * value would do because this value will be ignored and
886 * replaced at the next (real) checkout.
888 strbuf_reset(&sb);
889 strbuf_addf(&sb, "%s/HEAD", sb_repo.buf);
890 write_file(sb.buf, 1, "%s\n", sha1_to_hex(new->commit->object.sha1));
891 strbuf_reset(&sb);
892 strbuf_addf(&sb, "%s/commondir", sb_repo.buf);
893 write_file(sb.buf, 1, "../..\n");
895 if (!opts->quiet)
896 fprintf_ln(stderr, _("Enter %s (identifier %s)"), path, name);
898 setenv("GIT_CHECKOUT_NEW_WORKTREE", "1", 1);
899 setenv(GIT_DIR_ENVIRONMENT, sb_git.buf, 1);
900 setenv(GIT_WORK_TREE_ENVIRONMENT, path, 1);
901 memset(&cp, 0, sizeof(cp));
902 cp.git_cmd = 1;
903 cp.argv = opts->saved_argv;
904 ret = run_command(&cp);
905 strbuf_reset(&sb);
906 strbuf_addf(&sb, "%s/locked", sb_repo.buf);
907 unlink_or_warn(sb.buf);
908 return ret;
911 static int git_checkout_config(const char *var, const char *value, void *cb)
913 if (!strcmp(var, "diff.ignoresubmodules")) {
914 struct checkout_opts *opts = cb;
915 handle_ignore_submodules_arg(&opts->diff_options, value);
916 return 0;
919 if (starts_with(var, "submodule."))
920 return parse_submodule_config_option(var, value);
922 return git_xmerge_config(var, value, NULL);
925 struct tracking_name_data {
926 /* const */ char *src_ref;
927 char *dst_ref;
928 unsigned char *dst_sha1;
929 int unique;
932 static int check_tracking_name(struct remote *remote, void *cb_data)
934 struct tracking_name_data *cb = cb_data;
935 struct refspec query;
936 memset(&query, 0, sizeof(struct refspec));
937 query.src = cb->src_ref;
938 if (remote_find_tracking(remote, &query) ||
939 get_sha1(query.dst, cb->dst_sha1)) {
940 free(query.dst);
941 return 0;
943 if (cb->dst_ref) {
944 free(query.dst);
945 cb->unique = 0;
946 return 0;
948 cb->dst_ref = query.dst;
949 return 0;
952 static const char *unique_tracking_name(const char *name, unsigned char *sha1)
954 struct tracking_name_data cb_data = { NULL, NULL, NULL, 1 };
955 char src_ref[PATH_MAX];
956 snprintf(src_ref, PATH_MAX, "refs/heads/%s", name);
957 cb_data.src_ref = src_ref;
958 cb_data.dst_sha1 = sha1;
959 for_each_remote(check_tracking_name, &cb_data);
960 if (cb_data.unique)
961 return cb_data.dst_ref;
962 free(cb_data.dst_ref);
963 return NULL;
966 static void check_linked_checkout(struct branch_info *new, const char *id)
968 struct strbuf sb = STRBUF_INIT;
969 struct strbuf path = STRBUF_INIT;
970 struct strbuf gitdir = STRBUF_INIT;
971 const char *start, *end;
973 if (id)
974 strbuf_addf(&path, "%s/worktrees/%s/HEAD", get_git_common_dir(), id);
975 else
976 strbuf_addf(&path, "%s/HEAD", get_git_common_dir());
978 if (strbuf_read_file(&sb, path.buf, 0) < 0 ||
979 !skip_prefix(sb.buf, "ref:", &start))
980 goto done;
981 while (isspace(*start))
982 start++;
983 end = start;
984 while (*end && !isspace(*end))
985 end++;
986 if (strncmp(start, new->path, end - start) || new->path[end - start] != '\0')
987 goto done;
988 if (id) {
989 strbuf_reset(&path);
990 strbuf_addf(&path, "%s/worktrees/%s/gitdir", get_git_common_dir(), id);
991 if (strbuf_read_file(&gitdir, path.buf, 0) <= 0)
992 goto done;
993 strbuf_rtrim(&gitdir);
994 } else
995 strbuf_addstr(&gitdir, get_git_common_dir());
996 die(_("'%s' is already checked out at '%s'"), new->name, gitdir.buf);
997 done:
998 strbuf_release(&path);
999 strbuf_release(&sb);
1000 strbuf_release(&gitdir);
1003 static void check_linked_checkouts(struct branch_info *new)
1005 struct strbuf path = STRBUF_INIT;
1006 DIR *dir;
1007 struct dirent *d;
1009 strbuf_addf(&path, "%s/worktrees", get_git_common_dir());
1010 if ((dir = opendir(path.buf)) == NULL) {
1011 strbuf_release(&path);
1012 return;
1016 * $GIT_COMMON_DIR/HEAD is practically outside
1017 * $GIT_DIR so resolve_ref_unsafe() won't work (it
1018 * uses git_path). Parse the ref ourselves.
1020 check_linked_checkout(new, NULL);
1022 while ((d = readdir(dir)) != NULL) {
1023 if (!strcmp(d->d_name, ".") || !strcmp(d->d_name, ".."))
1024 continue;
1025 check_linked_checkout(new, d->d_name);
1027 strbuf_release(&path);
1028 closedir(dir);
1031 static int parse_branchname_arg(int argc, const char **argv,
1032 int dwim_new_local_branch_ok,
1033 struct branch_info *new,
1034 struct tree **source_tree,
1035 unsigned char rev[20],
1036 const char **new_branch,
1037 int force_detach)
1039 int argcount = 0;
1040 unsigned char branch_rev[20];
1041 const char *arg;
1042 int dash_dash_pos;
1043 int has_dash_dash = 0;
1044 int i;
1047 * case 1: git checkout <ref> -- [<paths>]
1049 * <ref> must be a valid tree, everything after the '--' must be
1050 * a path.
1052 * case 2: git checkout -- [<paths>]
1054 * everything after the '--' must be paths.
1056 * case 3: git checkout <something> [--]
1058 * (a) If <something> is a commit, that is to
1059 * switch to the branch or detach HEAD at it. As a special case,
1060 * if <something> is A...B (missing A or B means HEAD but you can
1061 * omit at most one side), and if there is a unique merge base
1062 * between A and B, A...B names that merge base.
1064 * (b) If <something> is _not_ a commit, either "--" is present
1065 * or <something> is not a path, no -t or -b was given, and
1066 * and there is a tracking branch whose name is <something>
1067 * in one and only one remote, then this is a short-hand to
1068 * fork local <something> from that remote-tracking branch.
1070 * (c) Otherwise, if "--" is present, treat it like case (1).
1072 * (d) Otherwise :
1073 * - if it's a reference, treat it like case (1)
1074 * - else if it's a path, treat it like case (2)
1075 * - else: fail.
1077 * case 4: git checkout <something> <paths>
1079 * The first argument must not be ambiguous.
1080 * - If it's *only* a reference, treat it like case (1).
1081 * - If it's only a path, treat it like case (2).
1082 * - else: fail.
1085 if (!argc)
1086 return 0;
1088 arg = argv[0];
1089 dash_dash_pos = -1;
1090 for (i = 0; i < argc; i++) {
1091 if (!strcmp(argv[i], "--")) {
1092 dash_dash_pos = i;
1093 break;
1096 if (dash_dash_pos == 0)
1097 return 1; /* case (2) */
1098 else if (dash_dash_pos == 1)
1099 has_dash_dash = 1; /* case (3) or (1) */
1100 else if (dash_dash_pos >= 2)
1101 die(_("only one reference expected, %d given."), dash_dash_pos);
1103 if (!strcmp(arg, "-"))
1104 arg = "@{-1}";
1106 if (get_sha1_mb(arg, rev)) {
1108 * Either case (3) or (4), with <something> not being
1109 * a commit, or an attempt to use case (1) with an
1110 * invalid ref.
1112 * It's likely an error, but we need to find out if
1113 * we should auto-create the branch, case (3).(b).
1115 int recover_with_dwim = dwim_new_local_branch_ok;
1117 if (check_filename(NULL, arg) && !has_dash_dash)
1118 recover_with_dwim = 0;
1120 * Accept "git checkout foo" and "git checkout foo --"
1121 * as candidates for dwim.
1123 if (!(argc == 1 && !has_dash_dash) &&
1124 !(argc == 2 && has_dash_dash))
1125 recover_with_dwim = 0;
1127 if (recover_with_dwim) {
1128 const char *remote = unique_tracking_name(arg, rev);
1129 if (remote) {
1130 *new_branch = arg;
1131 arg = remote;
1132 /* DWIMmed to create local branch, case (3).(b) */
1133 } else {
1134 recover_with_dwim = 0;
1138 if (!recover_with_dwim) {
1139 if (has_dash_dash)
1140 die(_("invalid reference: %s"), arg);
1141 return argcount;
1145 /* we can't end up being in (2) anymore, eat the argument */
1146 argcount++;
1147 argv++;
1148 argc--;
1150 new->name = arg;
1151 setup_branch_path(new);
1153 if (!check_refname_format(new->path, 0) &&
1154 !read_ref(new->path, branch_rev))
1155 hashcpy(rev, branch_rev);
1156 else
1157 new->path = NULL; /* not an existing branch */
1159 if (new->path && !force_detach && !*new_branch) {
1160 unsigned char sha1[20];
1161 int flag;
1162 char *head_ref = resolve_refdup("HEAD", 0, sha1, &flag);
1163 if (head_ref &&
1164 (!(flag & REF_ISSYMREF) || strcmp(head_ref, new->path)))
1165 check_linked_checkouts(new);
1166 free(head_ref);
1169 new->commit = lookup_commit_reference_gently(rev, 1);
1170 if (!new->commit) {
1171 /* not a commit */
1172 *source_tree = parse_tree_indirect(rev);
1173 } else {
1174 parse_commit_or_die(new->commit);
1175 *source_tree = new->commit->tree;
1178 if (!*source_tree) /* case (1): want a tree */
1179 die(_("reference is not a tree: %s"), arg);
1180 if (!has_dash_dash) {/* case (3).(d) -> (1) */
1182 * Do not complain the most common case
1183 * git checkout branch
1184 * even if there happen to be a file called 'branch';
1185 * it would be extremely annoying.
1187 if (argc)
1188 verify_non_filename(NULL, arg);
1189 } else {
1190 argcount++;
1191 argv++;
1192 argc--;
1195 return argcount;
1198 static int switch_unborn_to_new_branch(const struct checkout_opts *opts)
1200 int status;
1201 struct strbuf branch_ref = STRBUF_INIT;
1203 if (!opts->new_branch)
1204 die(_("You are on a branch yet to be born"));
1205 strbuf_addf(&branch_ref, "refs/heads/%s", opts->new_branch);
1206 status = create_symref("HEAD", branch_ref.buf, "checkout -b");
1207 strbuf_release(&branch_ref);
1208 if (!opts->quiet)
1209 fprintf(stderr, _("Switched to a new branch '%s'\n"),
1210 opts->new_branch);
1211 return status;
1214 static int checkout_branch(struct checkout_opts *opts,
1215 struct branch_info *new)
1217 if (opts->pathspec.nr)
1218 die(_("paths cannot be used with switching branches"));
1220 if (opts->patch_mode)
1221 die(_("'%s' cannot be used with switching branches"),
1222 "--patch");
1224 if (opts->writeout_stage)
1225 die(_("'%s' cannot be used with switching branches"),
1226 "--ours/--theirs");
1228 if (opts->force && opts->merge)
1229 die(_("'%s' cannot be used with '%s'"), "-f", "-m");
1231 if (opts->force_detach && opts->new_branch)
1232 die(_("'%s' cannot be used with '%s'"),
1233 "--detach", "-b/-B/--orphan");
1235 if (opts->new_orphan_branch) {
1236 if (opts->track != BRANCH_TRACK_UNSPECIFIED)
1237 die(_("'%s' cannot be used with '%s'"), "--orphan", "-t");
1238 } else if (opts->force_detach) {
1239 if (opts->track != BRANCH_TRACK_UNSPECIFIED)
1240 die(_("'%s' cannot be used with '%s'"), "--detach", "-t");
1241 } else if (opts->track == BRANCH_TRACK_UNSPECIFIED)
1242 opts->track = git_branch_track;
1244 if (new->name && !new->commit)
1245 die(_("Cannot switch branch to a non-commit '%s'"),
1246 new->name);
1248 if (opts->new_worktree)
1249 return prepare_linked_checkout(opts, new);
1251 if (!new->commit && opts->new_branch) {
1252 unsigned char rev[20];
1253 int flag;
1255 if (!read_ref_full("HEAD", 0, rev, &flag) &&
1256 (flag & REF_ISSYMREF) && is_null_sha1(rev))
1257 return switch_unborn_to_new_branch(opts);
1259 return switch_branches(opts, new);
1262 int cmd_checkout(int argc, const char **argv, const char *prefix)
1264 struct checkout_opts opts;
1265 struct branch_info new;
1266 char *conflict_style = NULL;
1267 int dwim_new_local_branch = 1;
1268 struct option options[] = {
1269 OPT__QUIET(&opts.quiet, N_("suppress progress reporting")),
1270 OPT_STRING('b', NULL, &opts.new_branch, N_("branch"),
1271 N_("create and checkout a new branch")),
1272 OPT_STRING('B', NULL, &opts.new_branch_force, N_("branch"),
1273 N_("create/reset and checkout a branch")),
1274 OPT_BOOL('l', NULL, &opts.new_branch_log, N_("create reflog for new branch")),
1275 OPT_BOOL(0, "detach", &opts.force_detach, N_("detach the HEAD at named commit")),
1276 OPT_SET_INT('t', "track", &opts.track, N_("set upstream info for new branch"),
1277 BRANCH_TRACK_EXPLICIT),
1278 OPT_STRING(0, "orphan", &opts.new_orphan_branch, N_("new-branch"), N_("new unparented branch")),
1279 OPT_SET_INT('2', "ours", &opts.writeout_stage, N_("checkout our version for unmerged files"),
1281 OPT_SET_INT('3', "theirs", &opts.writeout_stage, N_("checkout their version for unmerged files"),
1283 OPT__FORCE(&opts.force, N_("force checkout (throw away local modifications)")),
1284 OPT_BOOL('m', "merge", &opts.merge, N_("perform a 3-way merge with the new branch")),
1285 OPT_BOOL(0, "overwrite-ignore", &opts.overwrite_ignore, N_("update ignored files (default)")),
1286 OPT_STRING(0, "conflict", &conflict_style, N_("style"),
1287 N_("conflict style (merge or diff3)")),
1288 OPT_BOOL('p', "patch", &opts.patch_mode, N_("select hunks interactively")),
1289 OPT_BOOL(0, "ignore-skip-worktree-bits", &opts.ignore_skipworktree,
1290 N_("do not limit pathspecs to sparse entries only")),
1291 OPT_HIDDEN_BOOL(0, "guess", &dwim_new_local_branch,
1292 N_("second guess 'git checkout no-such-branch'")),
1293 OPT_FILENAME(0, "to", &opts.new_worktree,
1294 N_("check a branch out in a separate working directory")),
1295 OPT_END(),
1298 memset(&opts, 0, sizeof(opts));
1299 memset(&new, 0, sizeof(new));
1300 opts.overwrite_ignore = 1;
1301 opts.prefix = prefix;
1303 opts.saved_argv = xmalloc(sizeof(const char *) * (argc + 2));
1304 memcpy(opts.saved_argv, argv, sizeof(const char *) * (argc + 1));
1306 gitmodules_config();
1307 git_config(git_checkout_config, &opts);
1309 opts.track = BRANCH_TRACK_UNSPECIFIED;
1311 argc = parse_options(argc, argv, prefix, options, checkout_usage,
1312 PARSE_OPT_KEEP_DASHDASH);
1314 /* recursive execution from checkout_new_worktree() */
1315 opts.new_worktree_mode = getenv("GIT_CHECKOUT_NEW_WORKTREE") != NULL;
1316 if (opts.new_worktree_mode)
1317 opts.new_worktree = NULL;
1319 if (conflict_style) {
1320 opts.merge = 1; /* implied */
1321 git_xmerge_config("merge.conflictstyle", conflict_style, NULL);
1324 if ((!!opts.new_branch + !!opts.new_branch_force + !!opts.new_orphan_branch) > 1)
1325 die(_("-b, -B and --orphan are mutually exclusive"));
1328 * From here on, new_branch will contain the branch to be checked out,
1329 * and new_branch_force and new_orphan_branch will tell us which one of
1330 * -b/-B/--orphan is being used.
1332 if (opts.new_branch_force)
1333 opts.new_branch = opts.new_branch_force;
1335 if (opts.new_orphan_branch)
1336 opts.new_branch = opts.new_orphan_branch;
1338 /* --track without -b/-B/--orphan should DWIM */
1339 if (opts.track != BRANCH_TRACK_UNSPECIFIED && !opts.new_branch) {
1340 const char *argv0 = argv[0];
1341 if (!argc || !strcmp(argv0, "--"))
1342 die (_("--track needs a branch name"));
1343 skip_prefix(argv0, "refs/", &argv0);
1344 skip_prefix(argv0, "remotes/", &argv0);
1345 argv0 = strchr(argv0, '/');
1346 if (!argv0 || !argv0[1])
1347 die (_("Missing branch name; try -b"));
1348 opts.new_branch = argv0 + 1;
1352 * Extract branch name from command line arguments, so
1353 * all that is left is pathspecs.
1355 * Handle
1357 * 1) git checkout <tree> -- [<paths>]
1358 * 2) git checkout -- [<paths>]
1359 * 3) git checkout <something> [<paths>]
1361 * including "last branch" syntax and DWIM-ery for names of
1362 * remote branches, erroring out for invalid or ambiguous cases.
1364 if (argc) {
1365 unsigned char rev[20];
1366 int dwim_ok =
1367 !opts.patch_mode &&
1368 dwim_new_local_branch &&
1369 opts.track == BRANCH_TRACK_UNSPECIFIED &&
1370 !opts.new_branch;
1371 int n = parse_branchname_arg(argc, argv, dwim_ok,
1372 &new, &opts.source_tree,
1373 rev, &opts.new_branch,
1374 opts.force_detach);
1375 argv += n;
1376 argc -= n;
1379 if (argc) {
1380 parse_pathspec(&opts.pathspec, 0,
1381 opts.patch_mode ? PATHSPEC_PREFIX_ORIGIN : 0,
1382 prefix, argv);
1384 if (!opts.pathspec.nr)
1385 die(_("invalid path specification"));
1388 * Try to give more helpful suggestion.
1389 * new_branch && argc > 1 will be caught later.
1391 if (opts.new_branch && argc == 1)
1392 die(_("Cannot update paths and switch to branch '%s' at the same time.\n"
1393 "Did you intend to checkout '%s' which can not be resolved as commit?"),
1394 opts.new_branch, argv[0]);
1396 if (opts.force_detach)
1397 die(_("git checkout: --detach does not take a path argument '%s'"),
1398 argv[0]);
1400 if (1 < !!opts.writeout_stage + !!opts.force + !!opts.merge)
1401 die(_("git checkout: --ours/--theirs, --force and --merge are incompatible when\n"
1402 "checking out of the index."));
1405 if (opts.new_branch) {
1406 struct strbuf buf = STRBUF_INIT;
1408 opts.branch_exists =
1409 validate_new_branchname(opts.new_branch, &buf,
1410 !!opts.new_branch_force,
1411 !!opts.new_branch_force);
1413 strbuf_release(&buf);
1416 if (opts.patch_mode || opts.pathspec.nr)
1417 return checkout_paths(&opts, new.name);
1418 else
1419 return checkout_branch(&opts, &new);