3 #include "parse-options.h"
8 #include "cache-tree.h"
9 #include "unpack-trees.h"
11 #include "run-command.h"
12 #include "merge-recursive.h"
18 #include "xdiff-interface.h"
20 #include "resolve-undo.h"
21 #include "submodule.h"
22 #include "argv-array.h"
25 static const char * const checkout_usage[] = {
26 N_("git checkout [options] <branch>"),
27 N_("git checkout [options] [<branch>] -- <file>..."),
31 struct checkout_opts {
39 int ignore_skipworktree;
41 const char *new_branch;
42 const char *new_branch_force;
43 const char *new_orphan_branch;
45 enum branch_track track;
46 struct diff_options diff_options;
50 struct pathspec pathspec;
51 struct tree *source_tree;
53 const char *new_worktree;
54 const char **saved_argv;
55 int new_worktree_mode;
58 static int post_checkout_hook(struct commit *old, struct commit *new,
61 return run_hook_le(NULL, "post-checkout",
62 sha1_to_hex(old ? old->object.sha1 : null_sha1),
63 sha1_to_hex(new ? new->object.sha1 : null_sha1),
64 changed ? "1" : "0", NULL);
65 /* "new" can be NULL when checking out from the index before
70 static int update_some(const unsigned char *sha1, const char *base, int baselen,
71 const char *pathname, unsigned mode, int stage, void *context)
74 struct cache_entry *ce;
77 return READ_TREE_RECURSIVE;
79 len = baselen + strlen(pathname);
80 ce = xcalloc(1, cache_entry_size(len));
81 hashcpy(ce->sha1, sha1);
82 memcpy(ce->name, base, baselen);
83 memcpy(ce->name + baselen, pathname, len - baselen);
84 ce->ce_flags = create_ce_flags(0) | CE_UPDATE;
86 ce->ce_mode = create_ce_mode(mode);
87 add_cache_entry(ce, ADD_CACHE_OK_TO_ADD | ADD_CACHE_OK_TO_REPLACE);
91 static int read_tree_some(struct tree *tree, const struct pathspec *pathspec)
93 read_tree_recursive(tree, "", 0, 0, pathspec, update_some, NULL);
95 /* update the index with the given tree's info
96 * for all args, expanding wildcards, and exit
97 * with any non-zero return code.
102 static int skip_same_name(const struct cache_entry *ce, int pos)
104 while (++pos < active_nr &&
105 !strcmp(active_cache[pos]->name, ce->name))
110 static int check_stage(int stage, const struct cache_entry *ce, int pos)
112 while (pos < active_nr &&
113 !strcmp(active_cache[pos]->name, ce->name)) {
114 if (ce_stage(active_cache[pos]) == stage)
119 return error(_("path '%s' does not have our version"), ce->name);
121 return error(_("path '%s' does not have their version"), ce->name);
124 static int check_stages(unsigned stages, const struct cache_entry *ce, int pos)
127 const char *name = ce->name;
129 while (pos < active_nr) {
130 ce = active_cache[pos];
131 if (strcmp(name, ce->name))
133 seen |= (1 << ce_stage(ce));
136 if ((stages & seen) != stages)
137 return error(_("path '%s' does not have all necessary versions"),
142 static int checkout_stage(int stage, struct cache_entry *ce, int pos,
143 struct checkout *state)
145 while (pos < active_nr &&
146 !strcmp(active_cache[pos]->name, ce->name)) {
147 if (ce_stage(active_cache[pos]) == stage)
148 return checkout_entry(active_cache[pos], state, NULL);
152 return error(_("path '%s' does not have our version"), ce->name);
154 return error(_("path '%s' does not have their version"), ce->name);
157 static int checkout_merged(int pos, struct checkout *state)
159 struct cache_entry *ce = active_cache[pos];
160 const char *path = ce->name;
161 mmfile_t ancestor, ours, theirs;
163 unsigned char sha1[20];
164 mmbuffer_t result_buf;
165 unsigned char threeway[3][20];
168 memset(threeway, 0, sizeof(threeway));
169 while (pos < active_nr) {
171 stage = ce_stage(ce);
172 if (!stage || strcmp(path, ce->name))
174 hashcpy(threeway[stage - 1], ce->sha1);
176 mode = create_ce_mode(ce->ce_mode);
178 ce = active_cache[pos];
180 if (is_null_sha1(threeway[1]) || is_null_sha1(threeway[2]))
181 return error(_("path '%s' does not have necessary versions"), path);
183 read_mmblob(&ancestor, threeway[0]);
184 read_mmblob(&ours, threeway[1]);
185 read_mmblob(&theirs, threeway[2]);
188 * NEEDSWORK: re-create conflicts from merges with
189 * merge.renormalize set, too
191 status = ll_merge(&result_buf, path, &ancestor, "base",
192 &ours, "ours", &theirs, "theirs", NULL);
196 if (status < 0 || !result_buf.ptr) {
197 free(result_buf.ptr);
198 return error(_("path '%s': cannot merge"), path);
203 * There is absolutely no reason to write this as a blob object
204 * and create a phony cache entry just to leak. This hack is
205 * primarily to get to the write_entry() machinery that massages
206 * the contents to work-tree format and writes out which only
207 * allows it for a cache entry. The code in write_entry() needs
208 * to be refactored to allow us to feed a <buffer, size, mode>
209 * instead of a cache entry. Such a refactoring would help
210 * merge_recursive as well (it also writes the merge result to the
211 * object database even when it may contain conflicts).
213 if (write_sha1_file(result_buf.ptr, result_buf.size,
215 die(_("Unable to add merge result for '%s'"), path);
216 ce = make_cache_entry(mode, sha1, path, 2, 0);
218 die(_("make_cache_entry failed for path '%s'"), path);
219 status = checkout_entry(ce, state, NULL);
223 static int checkout_paths(const struct checkout_opts *opts,
224 const char *revision)
227 struct checkout state;
228 static char *ps_matched;
229 unsigned char rev[20];
233 struct lock_file *lock_file;
235 if (opts->track != BRANCH_TRACK_UNSPECIFIED)
236 die(_("'%s' cannot be used with updating paths"), "--track");
238 if (opts->new_branch_log)
239 die(_("'%s' cannot be used with updating paths"), "-l");
241 if (opts->force && opts->patch_mode)
242 die(_("'%s' cannot be used with updating paths"), "-f");
244 if (opts->force_detach)
245 die(_("'%s' cannot be used with updating paths"), "--detach");
247 if (opts->merge && opts->patch_mode)
248 die(_("'%s' cannot be used with %s"), "--merge", "--patch");
250 if (opts->force && opts->merge)
251 die(_("'%s' cannot be used with %s"), "-f", "-m");
253 if (opts->new_branch)
254 die(_("Cannot update paths and switch to branch '%s' at the same time."),
257 if (opts->new_worktree)
258 die(_("'%s' cannot be used with updating paths"), "--to");
260 if (opts->patch_mode)
261 return run_add_interactive(revision, "--patch=checkout",
264 lock_file = xcalloc(1, sizeof(struct lock_file));
266 hold_locked_index(lock_file, 1);
267 if (read_cache_preload(&opts->pathspec) < 0)
268 return error(_("corrupt index file"));
270 if (opts->source_tree)
271 read_tree_some(opts->source_tree, &opts->pathspec);
273 ps_matched = xcalloc(1, opts->pathspec.nr);
276 * Make sure all pathspecs participated in locating the paths
279 for (pos = 0; pos < active_nr; pos++) {
280 struct cache_entry *ce = active_cache[pos];
281 ce->ce_flags &= ~CE_MATCHED;
282 if (!opts->ignore_skipworktree && ce_skip_worktree(ce))
284 if (opts->source_tree && !(ce->ce_flags & CE_UPDATE))
286 * "git checkout tree-ish -- path", but this entry
287 * is in the original index; it will not be checked
288 * out to the working tree and it does not matter
289 * if pathspec matched this entry. We will not do
290 * anything to this entry at all.
294 * Either this entry came from the tree-ish we are
295 * checking the paths out of, or we are checking out
298 * If it comes from the tree-ish, we already know it
299 * matches the pathspec and could just stamp
300 * CE_MATCHED to it from update_some(). But we still
301 * need ps_matched and read_tree_recursive (and
302 * eventually tree_entry_interesting) cannot fill
303 * ps_matched yet. Once it can, we can avoid calling
304 * match_pathspec() for _all_ entries when
305 * opts->source_tree != NULL.
307 if (ce_path_match(ce, &opts->pathspec, ps_matched))
308 ce->ce_flags |= CE_MATCHED;
311 if (report_path_error(ps_matched, &opts->pathspec, opts->prefix)) {
317 /* "checkout -m path" to recreate conflicted state */
319 unmerge_marked_index(&the_index);
321 /* Any unmerged paths? */
322 for (pos = 0; pos < active_nr; pos++) {
323 const struct cache_entry *ce = active_cache[pos];
324 if (ce->ce_flags & CE_MATCHED) {
328 warning(_("path '%s' is unmerged"), ce->name);
329 } else if (opts->writeout_stage) {
330 errs |= check_stage(opts->writeout_stage, ce, pos);
331 } else if (opts->merge) {
332 errs |= check_stages((1<<2) | (1<<3), ce, pos);
335 error(_("path '%s' is unmerged"), ce->name);
337 pos = skip_same_name(ce, pos) - 1;
343 /* Now we are committed to check them out */
344 memset(&state, 0, sizeof(state));
346 state.refresh_cache = 1;
347 state.istate = &the_index;
348 for (pos = 0; pos < active_nr; pos++) {
349 struct cache_entry *ce = active_cache[pos];
350 if (ce->ce_flags & CE_MATCHED) {
352 errs |= checkout_entry(ce, &state, NULL);
355 if (opts->writeout_stage)
356 errs |= checkout_stage(opts->writeout_stage, ce, pos, &state);
357 else if (opts->merge)
358 errs |= checkout_merged(pos, &state);
359 pos = skip_same_name(ce, pos) - 1;
363 if (write_locked_index(&the_index, lock_file, COMMIT_LOCK))
364 die(_("unable to write new index file"));
366 read_ref_full("HEAD", 0, rev, &flag);
367 head = lookup_commit_reference_gently(rev, 1);
369 errs |= post_checkout_hook(head, head, 0);
373 static void show_local_changes(struct object *head,
374 const struct diff_options *opts)
377 /* I think we want full paths, even if we're in a subdirectory. */
378 init_revisions(&rev, NULL);
379 rev.diffopt.flags = opts->flags;
380 rev.diffopt.output_format |= DIFF_FORMAT_NAME_STATUS;
381 diff_setup_done(&rev.diffopt);
382 add_pending_object(&rev, head, NULL);
383 run_diff_index(&rev, 0);
386 static void describe_detached_head(const char *msg, struct commit *commit)
388 struct strbuf sb = STRBUF_INIT;
389 if (!parse_commit(commit))
390 pp_commit_easy(CMIT_FMT_ONELINE, commit, &sb);
391 fprintf(stderr, "%s %s... %s\n", msg,
392 find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV), sb.buf);
396 static int reset_tree(struct tree *tree, const struct checkout_opts *o,
397 int worktree, int *writeout_error)
399 struct unpack_trees_options opts;
400 struct tree_desc tree_desc;
402 memset(&opts, 0, sizeof(opts));
404 opts.update = worktree;
405 opts.skip_unmerged = !worktree;
408 opts.fn = oneway_merge;
409 opts.verbose_update = !o->quiet && isatty(2);
410 opts.src_index = &the_index;
411 opts.dst_index = &the_index;
413 init_tree_desc(&tree_desc, tree->buffer, tree->size);
414 switch (unpack_trees(1, &tree_desc, &opts)) {
418 * We return 0 nevertheless, as the index is all right
419 * and more importantly we have made best efforts to
420 * update paths in the work tree, and we cannot revert
431 const char *name; /* The short name used */
432 const char *path; /* The full name of a real branch */
433 struct commit *commit; /* The named commit */
435 * if not null the branch is detached because it's already
436 * checked out in this checkout
441 static void setup_branch_path(struct branch_info *branch)
443 struct strbuf buf = STRBUF_INIT;
445 strbuf_branchname(&buf, branch->name);
446 if (strcmp(buf.buf, branch->name))
447 branch->name = xstrdup(buf.buf);
448 strbuf_splice(&buf, 0, 0, "refs/heads/", 11);
449 branch->path = strbuf_detach(&buf, NULL);
452 static int merge_working_tree(const struct checkout_opts *opts,
453 struct branch_info *old,
454 struct branch_info *new,
458 struct lock_file *lock_file = xcalloc(1, sizeof(struct lock_file));
460 hold_locked_index(lock_file, 1);
461 if (read_cache_preload(NULL) < 0)
462 return error(_("corrupt index file"));
464 resolve_undo_clear();
466 ret = reset_tree(new->commit->tree, opts, 1, writeout_error);
470 struct tree_desc trees[2];
472 struct unpack_trees_options topts;
474 memset(&topts, 0, sizeof(topts));
476 topts.src_index = &the_index;
477 topts.dst_index = &the_index;
479 setup_unpack_trees_porcelain(&topts, "checkout");
481 refresh_cache(REFRESH_QUIET);
483 if (unmerged_cache()) {
484 error(_("you need to resolve your current index first"));
488 /* 2-way merge to the new branch */
489 topts.initial_checkout = is_cache_unborn();
492 topts.gently = opts->merge && old->commit;
493 topts.verbose_update = !opts->quiet && isatty(2);
494 topts.fn = twoway_merge;
495 if (opts->overwrite_ignore) {
496 topts.dir = xcalloc(1, sizeof(*topts.dir));
497 topts.dir->flags |= DIR_SHOW_IGNORED;
498 setup_standard_excludes(topts.dir);
500 tree = parse_tree_indirect(old->commit && !opts->new_worktree_mode ?
501 old->commit->object.sha1 :
502 EMPTY_TREE_SHA1_BIN);
503 init_tree_desc(&trees[0], tree->buffer, tree->size);
504 tree = parse_tree_indirect(new->commit->object.sha1);
505 init_tree_desc(&trees[1], tree->buffer, tree->size);
507 ret = unpack_trees(2, trees, &topts);
510 * Unpack couldn't do a trivial merge; either
511 * give up or do a real merge, depending on
512 * whether the merge flag was used.
516 struct merge_options o;
521 * Without old->commit, the below is the same as
522 * the two-tree unpack we already tried and failed.
527 /* Do more real merge */
530 * We update the index fully, then write the
531 * tree from the index, then merge the new
532 * branch with the current tree, with the old
533 * branch as the base. Then we reset the index
534 * (but not the working tree) to the new
535 * branch, leaving the working tree as the
536 * merged version, but skipping unmerged
537 * entries in the index.
540 add_files_to_cache(NULL, NULL, 0);
542 * NEEDSWORK: carrying over local changes
543 * when branches have different end-of-line
544 * normalization (or clean+smudge rules) is
545 * a pain; plumb in an option to set
548 init_merge_options(&o);
550 work = write_tree_from_memory(&o);
552 ret = reset_tree(new->commit->tree, opts, 1,
556 o.ancestor = old->name;
557 o.branch1 = new->name;
559 merge_trees(&o, new->commit->tree, work,
560 old->commit->tree, &result);
561 ret = reset_tree(new->commit->tree, opts, 0,
568 if (!active_cache_tree)
569 active_cache_tree = cache_tree();
571 if (!cache_tree_fully_valid(active_cache_tree))
572 cache_tree_update(&the_index, WRITE_TREE_SILENT | WRITE_TREE_REPAIR);
574 if (write_locked_index(&the_index, lock_file, COMMIT_LOCK))
575 die(_("unable to write new index file"));
577 if (!opts->force && !opts->quiet)
578 show_local_changes(&new->commit->object, &opts->diff_options);
583 static void report_tracking(struct branch_info *new)
585 struct strbuf sb = STRBUF_INIT;
586 struct branch *branch = branch_get(new->name);
588 if (!format_tracking_info(branch, &sb))
590 fputs(sb.buf, stdout);
594 static void update_refs_for_switch(const struct checkout_opts *opts,
595 struct branch_info *old,
596 struct branch_info *new)
598 struct strbuf msg = STRBUF_INIT;
599 const char *old_desc, *reflog_msg;
600 if (opts->new_branch) {
601 if (opts->new_orphan_branch) {
602 if (opts->new_branch_log && !log_all_ref_updates) {
604 struct strbuf log_file = STRBUF_INIT;
606 const char *ref_name;
608 ref_name = mkpath("refs/heads/%s", opts->new_orphan_branch);
609 temp = log_all_ref_updates;
610 log_all_ref_updates = 1;
611 ret = log_ref_setup(ref_name, &log_file);
612 log_all_ref_updates = temp;
613 strbuf_release(&log_file);
615 fprintf(stderr, _("Can not do reflog for '%s'\n"),
616 opts->new_orphan_branch);
622 create_branch(old->name, opts->new_branch, new->name,
623 opts->new_branch_force ? 1 : 0,
624 opts->new_branch_log,
625 opts->new_branch_force ? 1 : 0,
628 new->name = opts->new_branch;
629 setup_branch_path(new);
632 old_desc = old->name;
633 if (!old_desc && old->commit)
634 old_desc = sha1_to_hex(old->commit->object.sha1);
636 reflog_msg = getenv("GIT_REFLOG_ACTION");
638 strbuf_addf(&msg, "checkout: moving from %s to %s",
639 old_desc ? old_desc : "(invalid)", new->name);
641 strbuf_insert(&msg, 0, reflog_msg, strlen(reflog_msg));
643 if (!strcmp(new->name, "HEAD") && !new->path && !opts->force_detach) {
645 } else if (opts->force_detach || !new->path) { /* No longer on any branch. */
646 update_ref(msg.buf, "HEAD", new->commit->object.sha1, NULL,
647 REF_NODEREF, UPDATE_REFS_DIE_ON_ERR);
649 if (old->path && advice_detached_head)
650 detach_advice(new->name);
651 describe_detached_head(_("HEAD is now at"), new->commit);
653 } else if (new->path) { /* Switch branches. */
654 create_symref("HEAD", new->path, msg.buf);
656 if (old->path && !strcmp(new->path, old->path)) {
657 if (opts->new_branch_force)
658 fprintf(stderr, _("Reset branch '%s'\n"),
661 fprintf(stderr, _("Already on '%s'\n"),
663 } else if (opts->new_branch) {
664 if (opts->branch_exists)
665 fprintf(stderr, _("Switched to and reset branch '%s'\n"), new->name);
667 fprintf(stderr, _("Switched to a new branch '%s'\n"), new->name);
669 fprintf(stderr, _("Switched to branch '%s'\n"),
673 if (old->path && old->name) {
674 if (!ref_exists(old->path) && reflog_exists(old->path))
675 delete_reflog(old->path);
678 remove_branch_state();
679 strbuf_release(&msg);
681 (new->path || (!opts->force_detach && !strcmp(new->name, "HEAD"))))
682 report_tracking(new);
685 static int add_pending_uninteresting_ref(const char *refname,
686 const unsigned char *sha1,
687 int flags, void *cb_data)
689 add_pending_sha1(cb_data, refname, sha1, UNINTERESTING);
693 static void describe_one_orphan(struct strbuf *sb, struct commit *commit)
695 strbuf_addstr(sb, " ");
697 find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV));
698 strbuf_addch(sb, ' ');
699 if (!parse_commit(commit))
700 pp_commit_easy(CMIT_FMT_ONELINE, commit, sb);
701 strbuf_addch(sb, '\n');
704 #define ORPHAN_CUTOFF 4
705 static void suggest_reattach(struct commit *commit, struct rev_info *revs)
707 struct commit *c, *last = NULL;
708 struct strbuf sb = STRBUF_INIT;
710 while ((c = get_revision(revs)) != NULL) {
711 if (lost < ORPHAN_CUTOFF)
712 describe_one_orphan(&sb, c);
716 if (ORPHAN_CUTOFF < lost) {
717 int more = lost - ORPHAN_CUTOFF;
719 describe_one_orphan(&sb, last);
721 strbuf_addf(&sb, _(" ... and %d more.\n"), more);
726 /* The singular version */
727 "Warning: you are leaving %d commit behind, "
729 "any of your branches:\n\n"
731 /* The plural version */
732 "Warning: you are leaving %d commits behind, "
734 "any of your branches:\n\n"
736 /* Give ngettext() the count */
742 if (advice_detached_head)
745 "If you want to keep them by creating a new branch, "
746 "this may be a good time\nto do so with:\n\n"
747 " git branch new_branch_name %s\n\n"),
748 find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV));
752 * We are about to leave commit that was at the tip of a detached
753 * HEAD. If it is not reachable from any ref, this is the last chance
754 * for the user to do so without resorting to reflog.
756 static void orphaned_commit_warning(struct commit *old, struct commit *new)
758 struct rev_info revs;
759 struct object *object = &old->object;
760 struct object_array refs;
762 init_revisions(&revs, NULL);
763 setup_revisions(0, NULL, &revs, NULL);
765 object->flags &= ~UNINTERESTING;
766 add_pending_object(&revs, object, sha1_to_hex(object->sha1));
768 for_each_ref(add_pending_uninteresting_ref, &revs);
769 add_pending_sha1(&revs, "HEAD", new->object.sha1, UNINTERESTING);
772 revs.leak_pending = 1;
774 if (prepare_revision_walk(&revs))
775 die(_("internal error in revision walk"));
776 if (!(old->object.flags & UNINTERESTING))
777 suggest_reattach(old, &revs);
779 describe_detached_head(_("Previous HEAD position was"), old);
781 clear_commit_marks_for_object_array(&refs, ALL_REV_FLAGS);
785 static int switch_branches(const struct checkout_opts *opts,
786 struct branch_info *new)
789 struct branch_info old;
791 unsigned char rev[20];
792 int flag, writeout_error = 0;
793 memset(&old, 0, sizeof(old));
794 old.path = path_to_free = resolve_refdup("HEAD", 0, rev, &flag);
795 old.commit = lookup_commit_reference_gently(rev, 1);
796 if (!(flag & REF_ISSYMREF))
800 skip_prefix(old.path, "refs/heads/", &old.name);
804 new->commit = old.commit;
806 die(_("You are on a branch yet to be born"));
807 parse_commit_or_die(new->commit);
810 ret = merge_working_tree(opts, &old, new, &writeout_error);
816 if (!opts->quiet && !old.path && old.commit &&
817 new->commit != old.commit && !opts->new_worktree_mode)
818 orphaned_commit_warning(old.commit, new->commit);
820 update_refs_for_switch(opts, &old, new);
822 ret = post_checkout_hook(old.commit, new->commit, 1);
824 return ret || writeout_error;
827 static char *junk_work_tree;
828 static char *junk_git_dir;
830 static pid_t junk_pid;
832 static void remove_junk(void)
834 struct strbuf sb = STRBUF_INIT;
835 if (!is_junk || getpid() != junk_pid)
838 strbuf_addstr(&sb, junk_git_dir);
839 remove_dir_recursively(&sb, 0);
842 if (junk_work_tree) {
843 strbuf_addstr(&sb, junk_work_tree);
844 remove_dir_recursively(&sb, 0);
849 static void remove_junk_on_signal(int signo)
856 static int prepare_linked_checkout(const struct checkout_opts *opts,
857 struct branch_info *new)
859 struct strbuf sb_git = STRBUF_INIT, sb_repo = STRBUF_INIT;
860 struct strbuf sb = STRBUF_INIT;
861 const char *path = opts->new_worktree, *name;
863 struct child_process cp;
864 int counter = 0, len, ret;
867 die(_("no branch specified"));
868 if (file_exists(path) && !is_empty_dir(path))
869 die(_("'%s' already exists"), path);
872 while (len && is_dir_sep(path[len - 1]))
875 for (name = path + len - 1; name > path; name--)
876 if (is_dir_sep(*name)) {
880 strbuf_addstr(&sb_repo,
881 git_path("worktrees/%.*s", (int)(path + len - name), name));
883 if (safe_create_leading_directories_const(sb_repo.buf))
884 die_errno(_("could not create leading directories of '%s'"),
886 while (!stat(sb_repo.buf, &st)) {
888 strbuf_setlen(&sb_repo, len);
889 strbuf_addf(&sb_repo, "%d", counter);
891 name = strrchr(sb_repo.buf, '/') + 1;
895 sigchain_push_common(remove_junk_on_signal);
897 if (mkdir(sb_repo.buf, 0777))
898 die_errno(_("could not create directory of '%s'"), sb_repo.buf);
899 junk_git_dir = xstrdup(sb_repo.buf);
903 * lock the incomplete repo so prune won't delete it, unlock
904 * after the preparation is over.
906 strbuf_addf(&sb, "%s/locked", sb_repo.buf);
907 write_file(sb.buf, 1, "initializing\n");
909 strbuf_addf(&sb_git, "%s/.git", path);
910 if (safe_create_leading_directories_const(sb_git.buf))
911 die_errno(_("could not create leading directories of '%s'"),
913 junk_work_tree = xstrdup(path);
916 strbuf_addf(&sb, "%s/gitdir", sb_repo.buf);
917 write_file(sb.buf, 1, "%s\n", real_path(sb_git.buf));
918 write_file(sb_git.buf, 1, "gitdir: %s/worktrees/%s\n",
919 real_path(get_git_common_dir()), name);
921 * This is to keep resolve_ref() happy. We need a valid HEAD
922 * or is_git_directory() will reject the directory. Any valid
923 * value would do because this value will be ignored and
924 * replaced at the next (real) checkout.
927 strbuf_addf(&sb, "%s/HEAD", sb_repo.buf);
928 write_file(sb.buf, 1, "%s\n", sha1_to_hex(new->commit->object.sha1));
930 strbuf_addf(&sb, "%s/commondir", sb_repo.buf);
931 write_file(sb.buf, 1, "../..\n");
934 fprintf_ln(stderr, _("Enter %s (identifier %s)"), path, name);
936 setenv("GIT_CHECKOUT_NEW_WORKTREE", "1", 1);
937 setenv(GIT_DIR_ENVIRONMENT, sb_git.buf, 1);
938 setenv(GIT_WORK_TREE_ENVIRONMENT, path, 1);
939 memset(&cp, 0, sizeof(cp));
941 cp.argv = opts->saved_argv;
942 ret = run_command(&cp);
945 free(junk_work_tree);
947 junk_work_tree = NULL;
951 strbuf_addf(&sb, "%s/locked", sb_repo.buf);
952 unlink_or_warn(sb.buf);
954 strbuf_release(&sb_repo);
955 strbuf_release(&sb_git);
959 static int git_checkout_config(const char *var, const char *value, void *cb)
961 if (!strcmp(var, "diff.ignoresubmodules")) {
962 struct checkout_opts *opts = cb;
963 handle_ignore_submodules_arg(&opts->diff_options, value);
967 if (starts_with(var, "submodule."))
968 return parse_submodule_config_option(var, value);
970 return git_xmerge_config(var, value, NULL);
973 struct tracking_name_data {
974 /* const */ char *src_ref;
976 unsigned char *dst_sha1;
980 static int check_tracking_name(struct remote *remote, void *cb_data)
982 struct tracking_name_data *cb = cb_data;
983 struct refspec query;
984 memset(&query, 0, sizeof(struct refspec));
985 query.src = cb->src_ref;
986 if (remote_find_tracking(remote, &query) ||
987 get_sha1(query.dst, cb->dst_sha1)) {
996 cb->dst_ref = query.dst;
1000 static const char *unique_tracking_name(const char *name, unsigned char *sha1)
1002 struct tracking_name_data cb_data = { NULL, NULL, NULL, 1 };
1003 char src_ref[PATH_MAX];
1004 snprintf(src_ref, PATH_MAX, "refs/heads/%s", name);
1005 cb_data.src_ref = src_ref;
1006 cb_data.dst_sha1 = sha1;
1007 for_each_remote(check_tracking_name, &cb_data);
1009 return cb_data.dst_ref;
1010 free(cb_data.dst_ref);
1014 static void check_linked_checkout(struct branch_info *new, const char *id)
1016 struct strbuf sb = STRBUF_INIT;
1017 struct strbuf path = STRBUF_INIT;
1018 struct strbuf gitdir = STRBUF_INIT;
1019 const char *start, *end;
1022 strbuf_addf(&path, "%s/worktrees/%s/HEAD", get_git_common_dir(), id);
1024 strbuf_addf(&path, "%s/HEAD", get_git_common_dir());
1026 if (strbuf_read_file(&sb, path.buf, 0) < 0 ||
1027 !skip_prefix(sb.buf, "ref:", &start))
1029 while (isspace(*start))
1032 while (*end && !isspace(*end))
1034 if (strncmp(start, new->path, end - start) || new->path[end - start] != '\0')
1037 strbuf_reset(&path);
1038 strbuf_addf(&path, "%s/worktrees/%s/gitdir", get_git_common_dir(), id);
1039 if (strbuf_read_file(&gitdir, path.buf, 0) <= 0)
1041 strbuf_rtrim(&gitdir);
1043 strbuf_addstr(&gitdir, get_git_common_dir());
1044 die(_("'%s' is already checked out at '%s'"), new->name, gitdir.buf);
1046 strbuf_release(&path);
1047 strbuf_release(&sb);
1048 strbuf_release(&gitdir);
1051 static void check_linked_checkouts(struct branch_info *new)
1053 struct strbuf path = STRBUF_INIT;
1057 strbuf_addf(&path, "%s/worktrees", get_git_common_dir());
1058 if ((dir = opendir(path.buf)) == NULL) {
1059 strbuf_release(&path);
1064 * $GIT_COMMON_DIR/HEAD is practically outside
1065 * $GIT_DIR so resolve_ref_unsafe() won't work (it
1066 * uses git_path). Parse the ref ourselves.
1068 check_linked_checkout(new, NULL);
1070 while ((d = readdir(dir)) != NULL) {
1071 if (!strcmp(d->d_name, ".") || !strcmp(d->d_name, ".."))
1073 check_linked_checkout(new, d->d_name);
1075 strbuf_release(&path);
1079 static int parse_branchname_arg(int argc, const char **argv,
1080 int dwim_new_local_branch_ok,
1081 struct branch_info *new,
1082 struct tree **source_tree,
1083 unsigned char rev[20],
1084 const char **new_branch,
1088 unsigned char branch_rev[20];
1091 int has_dash_dash = 0;
1095 * case 1: git checkout <ref> -- [<paths>]
1097 * <ref> must be a valid tree, everything after the '--' must be
1100 * case 2: git checkout -- [<paths>]
1102 * everything after the '--' must be paths.
1104 * case 3: git checkout <something> [--]
1106 * (a) If <something> is a commit, that is to
1107 * switch to the branch or detach HEAD at it. As a special case,
1108 * if <something> is A...B (missing A or B means HEAD but you can
1109 * omit at most one side), and if there is a unique merge base
1110 * between A and B, A...B names that merge base.
1112 * (b) If <something> is _not_ a commit, either "--" is present
1113 * or <something> is not a path, no -t or -b was given, and
1114 * and there is a tracking branch whose name is <something>
1115 * in one and only one remote, then this is a short-hand to
1116 * fork local <something> from that remote-tracking branch.
1118 * (c) Otherwise, if "--" is present, treat it like case (1).
1121 * - if it's a reference, treat it like case (1)
1122 * - else if it's a path, treat it like case (2)
1125 * case 4: git checkout <something> <paths>
1127 * The first argument must not be ambiguous.
1128 * - If it's *only* a reference, treat it like case (1).
1129 * - If it's only a path, treat it like case (2).
1138 for (i = 0; i < argc; i++) {
1139 if (!strcmp(argv[i], "--")) {
1144 if (dash_dash_pos == 0)
1145 return 1; /* case (2) */
1146 else if (dash_dash_pos == 1)
1147 has_dash_dash = 1; /* case (3) or (1) */
1148 else if (dash_dash_pos >= 2)
1149 die(_("only one reference expected, %d given."), dash_dash_pos);
1151 if (!strcmp(arg, "-"))
1154 if (get_sha1_mb(arg, rev)) {
1156 * Either case (3) or (4), with <something> not being
1157 * a commit, or an attempt to use case (1) with an
1160 * It's likely an error, but we need to find out if
1161 * we should auto-create the branch, case (3).(b).
1163 int recover_with_dwim = dwim_new_local_branch_ok;
1165 if (check_filename(NULL, arg) && !has_dash_dash)
1166 recover_with_dwim = 0;
1168 * Accept "git checkout foo" and "git checkout foo --"
1169 * as candidates for dwim.
1171 if (!(argc == 1 && !has_dash_dash) &&
1172 !(argc == 2 && has_dash_dash))
1173 recover_with_dwim = 0;
1175 if (recover_with_dwim) {
1176 const char *remote = unique_tracking_name(arg, rev);
1180 /* DWIMmed to create local branch, case (3).(b) */
1182 recover_with_dwim = 0;
1186 if (!recover_with_dwim) {
1188 die(_("invalid reference: %s"), arg);
1193 /* we can't end up being in (2) anymore, eat the argument */
1199 setup_branch_path(new);
1201 if (!check_refname_format(new->path, 0) &&
1202 !read_ref(new->path, branch_rev))
1203 hashcpy(rev, branch_rev);
1205 new->path = NULL; /* not an existing branch */
1207 if (new->path && !force_detach && !*new_branch) {
1208 unsigned char sha1[20];
1210 char *head_ref = resolve_refdup("HEAD", 0, sha1, &flag);
1212 (!(flag & REF_ISSYMREF) || strcmp(head_ref, new->path)))
1213 check_linked_checkouts(new);
1217 new->commit = lookup_commit_reference_gently(rev, 1);
1220 *source_tree = parse_tree_indirect(rev);
1222 parse_commit_or_die(new->commit);
1223 *source_tree = new->commit->tree;
1226 if (!*source_tree) /* case (1): want a tree */
1227 die(_("reference is not a tree: %s"), arg);
1228 if (!has_dash_dash) {/* case (3).(d) -> (1) */
1230 * Do not complain the most common case
1231 * git checkout branch
1232 * even if there happen to be a file called 'branch';
1233 * it would be extremely annoying.
1236 verify_non_filename(NULL, arg);
1246 static int switch_unborn_to_new_branch(const struct checkout_opts *opts)
1249 struct strbuf branch_ref = STRBUF_INIT;
1251 if (!opts->new_branch)
1252 die(_("You are on a branch yet to be born"));
1253 strbuf_addf(&branch_ref, "refs/heads/%s", opts->new_branch);
1254 status = create_symref("HEAD", branch_ref.buf, "checkout -b");
1255 strbuf_release(&branch_ref);
1257 fprintf(stderr, _("Switched to a new branch '%s'\n"),
1262 static int checkout_branch(struct checkout_opts *opts,
1263 struct branch_info *new)
1265 if (opts->pathspec.nr)
1266 die(_("paths cannot be used with switching branches"));
1268 if (opts->patch_mode)
1269 die(_("'%s' cannot be used with switching branches"),
1272 if (opts->writeout_stage)
1273 die(_("'%s' cannot be used with switching branches"),
1276 if (opts->force && opts->merge)
1277 die(_("'%s' cannot be used with '%s'"), "-f", "-m");
1279 if (opts->force_detach && opts->new_branch)
1280 die(_("'%s' cannot be used with '%s'"),
1281 "--detach", "-b/-B/--orphan");
1283 if (opts->new_orphan_branch) {
1284 if (opts->track != BRANCH_TRACK_UNSPECIFIED)
1285 die(_("'%s' cannot be used with '%s'"), "--orphan", "-t");
1286 } else if (opts->force_detach) {
1287 if (opts->track != BRANCH_TRACK_UNSPECIFIED)
1288 die(_("'%s' cannot be used with '%s'"), "--detach", "-t");
1289 } else if (opts->track == BRANCH_TRACK_UNSPECIFIED)
1290 opts->track = git_branch_track;
1292 if (new->name && !new->commit)
1293 die(_("Cannot switch branch to a non-commit '%s'"),
1296 if (opts->new_worktree)
1297 return prepare_linked_checkout(opts, new);
1299 if (!new->commit && opts->new_branch) {
1300 unsigned char rev[20];
1303 if (!read_ref_full("HEAD", 0, rev, &flag) &&
1304 (flag & REF_ISSYMREF) && is_null_sha1(rev))
1305 return switch_unborn_to_new_branch(opts);
1307 return switch_branches(opts, new);
1310 int cmd_checkout(int argc, const char **argv, const char *prefix)
1312 struct checkout_opts opts;
1313 struct branch_info new;
1314 char *conflict_style = NULL;
1315 int dwim_new_local_branch = 1;
1316 struct option options[] = {
1317 OPT__QUIET(&opts.quiet, N_("suppress progress reporting")),
1318 OPT_STRING('b', NULL, &opts.new_branch, N_("branch"),
1319 N_("create and checkout a new branch")),
1320 OPT_STRING('B', NULL, &opts.new_branch_force, N_("branch"),
1321 N_("create/reset and checkout a branch")),
1322 OPT_BOOL('l', NULL, &opts.new_branch_log, N_("create reflog for new branch")),
1323 OPT_BOOL(0, "detach", &opts.force_detach, N_("detach the HEAD at named commit")),
1324 OPT_SET_INT('t', "track", &opts.track, N_("set upstream info for new branch"),
1325 BRANCH_TRACK_EXPLICIT),
1326 OPT_STRING(0, "orphan", &opts.new_orphan_branch, N_("new-branch"), N_("new unparented branch")),
1327 OPT_SET_INT('2', "ours", &opts.writeout_stage, N_("checkout our version for unmerged files"),
1329 OPT_SET_INT('3', "theirs", &opts.writeout_stage, N_("checkout their version for unmerged files"),
1331 OPT__FORCE(&opts.force, N_("force checkout (throw away local modifications)")),
1332 OPT_BOOL('m', "merge", &opts.merge, N_("perform a 3-way merge with the new branch")),
1333 OPT_BOOL(0, "overwrite-ignore", &opts.overwrite_ignore, N_("update ignored files (default)")),
1334 OPT_STRING(0, "conflict", &conflict_style, N_("style"),
1335 N_("conflict style (merge or diff3)")),
1336 OPT_BOOL('p', "patch", &opts.patch_mode, N_("select hunks interactively")),
1337 OPT_BOOL(0, "ignore-skip-worktree-bits", &opts.ignore_skipworktree,
1338 N_("do not limit pathspecs to sparse entries only")),
1339 OPT_HIDDEN_BOOL(0, "guess", &dwim_new_local_branch,
1340 N_("second guess 'git checkout no-such-branch'")),
1341 OPT_FILENAME(0, "to", &opts.new_worktree,
1342 N_("check a branch out in a separate working directory")),
1346 memset(&opts, 0, sizeof(opts));
1347 memset(&new, 0, sizeof(new));
1348 opts.overwrite_ignore = 1;
1349 opts.prefix = prefix;
1351 opts.saved_argv = xmalloc(sizeof(const char *) * (argc + 2));
1352 memcpy(opts.saved_argv, argv, sizeof(const char *) * (argc + 1));
1354 gitmodules_config();
1355 git_config(git_checkout_config, &opts);
1357 opts.track = BRANCH_TRACK_UNSPECIFIED;
1359 argc = parse_options(argc, argv, prefix, options, checkout_usage,
1360 PARSE_OPT_KEEP_DASHDASH);
1362 /* recursive execution from checkout_new_worktree() */
1363 opts.new_worktree_mode = getenv("GIT_CHECKOUT_NEW_WORKTREE") != NULL;
1364 if (opts.new_worktree_mode)
1365 opts.new_worktree = NULL;
1367 if (!opts.new_worktree)
1370 if (conflict_style) {
1371 opts.merge = 1; /* implied */
1372 git_xmerge_config("merge.conflictstyle", conflict_style, NULL);
1375 if ((!!opts.new_branch + !!opts.new_branch_force + !!opts.new_orphan_branch) > 1)
1376 die(_("-b, -B and --orphan are mutually exclusive"));
1379 * From here on, new_branch will contain the branch to be checked out,
1380 * and new_branch_force and new_orphan_branch will tell us which one of
1381 * -b/-B/--orphan is being used.
1383 if (opts.new_branch_force)
1384 opts.new_branch = opts.new_branch_force;
1386 if (opts.new_orphan_branch)
1387 opts.new_branch = opts.new_orphan_branch;
1389 /* --track without -b/-B/--orphan should DWIM */
1390 if (opts.track != BRANCH_TRACK_UNSPECIFIED && !opts.new_branch) {
1391 const char *argv0 = argv[0];
1392 if (!argc || !strcmp(argv0, "--"))
1393 die (_("--track needs a branch name"));
1394 skip_prefix(argv0, "refs/", &argv0);
1395 skip_prefix(argv0, "remotes/", &argv0);
1396 argv0 = strchr(argv0, '/');
1397 if (!argv0 || !argv0[1])
1398 die (_("Missing branch name; try -b"));
1399 opts.new_branch = argv0 + 1;
1403 * Extract branch name from command line arguments, so
1404 * all that is left is pathspecs.
1408 * 1) git checkout <tree> -- [<paths>]
1409 * 2) git checkout -- [<paths>]
1410 * 3) git checkout <something> [<paths>]
1412 * including "last branch" syntax and DWIM-ery for names of
1413 * remote branches, erroring out for invalid or ambiguous cases.
1416 unsigned char rev[20];
1419 dwim_new_local_branch &&
1420 opts.track == BRANCH_TRACK_UNSPECIFIED &&
1422 int n = parse_branchname_arg(argc, argv, dwim_ok,
1423 &new, &opts.source_tree,
1424 rev, &opts.new_branch,
1431 parse_pathspec(&opts.pathspec, 0,
1432 opts.patch_mode ? PATHSPEC_PREFIX_ORIGIN : 0,
1435 if (!opts.pathspec.nr)
1436 die(_("invalid path specification"));
1439 * Try to give more helpful suggestion.
1440 * new_branch && argc > 1 will be caught later.
1442 if (opts.new_branch && argc == 1)
1443 die(_("Cannot update paths and switch to branch '%s' at the same time.\n"
1444 "Did you intend to checkout '%s' which can not be resolved as commit?"),
1445 opts.new_branch, argv[0]);
1447 if (opts.force_detach)
1448 die(_("git checkout: --detach does not take a path argument '%s'"),
1451 if (1 < !!opts.writeout_stage + !!opts.force + !!opts.merge)
1452 die(_("git checkout: --ours/--theirs, --force and --merge are incompatible when\n"
1453 "checking out of the index."));
1456 if (opts.new_branch) {
1457 struct strbuf buf = STRBUF_INIT;
1459 opts.branch_exists =
1460 validate_new_branchname(opts.new_branch, &buf,
1461 !!opts.new_branch_force,
1462 !!opts.new_branch_force);
1464 strbuf_release(&buf);
1467 if (opts.patch_mode || opts.pathspec.nr)
1468 return checkout_paths(&opts, new.name);
1470 return checkout_branch(&opts, &new);