1 #define USE_THE_INDEX_COMPATIBILITY_MACROS
6 #include "cache-tree.h"
14 #include "merge-recursive.h"
15 #include "object-store.h"
16 #include "parse-options.h"
19 #include "resolve-undo.h"
21 #include "run-command.h"
22 #include "submodule.h"
23 #include "submodule-config.h"
25 #include "tree-walk.h"
26 #include "unpack-trees.h"
27 #include "wt-status.h"
28 #include "xdiff-interface.h"
30 static const char * const checkout_usage[] = {
31 N_("git checkout [<options>] <branch>"),
32 N_("git checkout [<options>] [<branch>] -- <file>..."),
36 static const char * const switch_branch_usage[] = {
37 N_("git switch [<options>] [<branch>]"),
41 static const char * const restore_usage[] = {
42 N_("git restore [<options>] [--source=<branch>] <file>..."),
46 struct checkout_opts {
55 int ignore_skipworktree;
56 int ignore_other_worktrees;
58 int count_checkout_paths;
60 int dwim_new_local_branch;
64 int switch_branch_doing_nothing_is_ok;
65 int only_merge_on_switching_branches;
66 int can_switch_when_in_progress;
67 int orphan_from_empty_tree;
68 int empty_pathspec_ok;
70 int checkout_worktree;
71 const char *ignore_unmerged_opt;
73 int pathspec_file_nul;
74 const char *pathspec_from_file;
76 const char *new_branch;
77 const char *new_branch_force;
78 const char *new_orphan_branch;
80 enum branch_track track;
81 struct diff_options diff_options;
86 struct pathspec pathspec;
87 const char *from_treeish;
88 struct tree *source_tree;
92 const char *name; /* The short name used */
93 const char *path; /* The full name of a real branch */
94 struct commit *commit; /* The named commit */
96 * if not null the branch is detached because it's already
97 * checked out in this checkout
102 static int post_checkout_hook(struct commit *old_commit, struct commit *new_commit,
105 return run_hook_le(NULL, "post-checkout",
106 oid_to_hex(old_commit ? &old_commit->object.oid : &null_oid),
107 oid_to_hex(new_commit ? &new_commit->object.oid : &null_oid),
108 changed ? "1" : "0", NULL);
109 /* "new_commit" can be NULL when checking out from the index before
114 static int update_some(const struct object_id *oid, struct strbuf *base,
115 const char *pathname, unsigned mode, int stage, void *context)
118 struct cache_entry *ce;
122 return READ_TREE_RECURSIVE;
124 len = base->len + strlen(pathname);
125 ce = make_empty_cache_entry(&the_index, len);
126 oidcpy(&ce->oid, oid);
127 memcpy(ce->name, base->buf, base->len);
128 memcpy(ce->name + base->len, pathname, len - base->len);
129 ce->ce_flags = create_ce_flags(0) | CE_UPDATE;
130 ce->ce_namelen = len;
131 ce->ce_mode = create_ce_mode(mode);
134 * If the entry is the same as the current index, we can leave the old
135 * entry in place. Whether it is UPTODATE or not, checkout_entry will
136 * do the right thing.
138 pos = cache_name_pos(ce->name, ce->ce_namelen);
140 struct cache_entry *old = active_cache[pos];
141 if (ce->ce_mode == old->ce_mode &&
142 !ce_intent_to_add(old) &&
143 oideq(&ce->oid, &old->oid)) {
144 old->ce_flags |= CE_UPDATE;
145 discard_cache_entry(ce);
150 add_cache_entry(ce, ADD_CACHE_OK_TO_ADD | ADD_CACHE_OK_TO_REPLACE);
154 static int read_tree_some(struct tree *tree, const struct pathspec *pathspec)
156 read_tree_recursive(the_repository, tree, "", 0, 0,
157 pathspec, update_some, NULL);
159 /* update the index with the given tree's info
160 * for all args, expanding wildcards, and exit
161 * with any non-zero return code.
166 static int skip_same_name(const struct cache_entry *ce, int pos)
168 while (++pos < active_nr &&
169 !strcmp(active_cache[pos]->name, ce->name))
174 static int check_stage(int stage, const struct cache_entry *ce, int pos,
177 while (pos < active_nr &&
178 !strcmp(active_cache[pos]->name, ce->name)) {
179 if (ce_stage(active_cache[pos]) == stage)
186 return error(_("path '%s' does not have our version"), ce->name);
188 return error(_("path '%s' does not have their version"), ce->name);
191 static int check_stages(unsigned stages, const struct cache_entry *ce, int pos)
194 const char *name = ce->name;
196 while (pos < active_nr) {
197 ce = active_cache[pos];
198 if (strcmp(name, ce->name))
200 seen |= (1 << ce_stage(ce));
203 if ((stages & seen) != stages)
204 return error(_("path '%s' does not have all necessary versions"),
209 static int checkout_stage(int stage, const struct cache_entry *ce, int pos,
210 const struct checkout *state, int *nr_checkouts,
213 while (pos < active_nr &&
214 !strcmp(active_cache[pos]->name, ce->name)) {
215 if (ce_stage(active_cache[pos]) == stage)
216 return checkout_entry(active_cache[pos], state,
225 return error(_("path '%s' does not have our version"), ce->name);
227 return error(_("path '%s' does not have their version"), ce->name);
230 static int checkout_merged(int pos, const struct checkout *state, int *nr_checkouts)
232 struct cache_entry *ce = active_cache[pos];
233 const char *path = ce->name;
234 mmfile_t ancestor, ours, theirs;
236 struct object_id oid;
237 mmbuffer_t result_buf;
238 struct object_id threeway[3];
241 memset(threeway, 0, sizeof(threeway));
242 while (pos < active_nr) {
244 stage = ce_stage(ce);
245 if (!stage || strcmp(path, ce->name))
247 oidcpy(&threeway[stage - 1], &ce->oid);
249 mode = create_ce_mode(ce->ce_mode);
251 ce = active_cache[pos];
253 if (is_null_oid(&threeway[1]) || is_null_oid(&threeway[2]))
254 return error(_("path '%s' does not have necessary versions"), path);
256 read_mmblob(&ancestor, &threeway[0]);
257 read_mmblob(&ours, &threeway[1]);
258 read_mmblob(&theirs, &threeway[2]);
261 * NEEDSWORK: re-create conflicts from merges with
262 * merge.renormalize set, too
264 status = ll_merge(&result_buf, path, &ancestor, "base",
265 &ours, "ours", &theirs, "theirs",
266 state->istate, NULL);
270 if (status < 0 || !result_buf.ptr) {
271 free(result_buf.ptr);
272 return error(_("path '%s': cannot merge"), path);
277 * There is absolutely no reason to write this as a blob object
278 * and create a phony cache entry. This hack is primarily to get
279 * to the write_entry() machinery that massages the contents to
280 * work-tree format and writes out which only allows it for a
281 * cache entry. The code in write_entry() needs to be refactored
282 * to allow us to feed a <buffer, size, mode> instead of a cache
283 * entry. Such a refactoring would help merge_recursive as well
284 * (it also writes the merge result to the object database even
285 * when it may contain conflicts).
287 if (write_object_file(result_buf.ptr, result_buf.size, blob_type, &oid))
288 die(_("Unable to add merge result for '%s'"), path);
289 free(result_buf.ptr);
290 ce = make_transient_cache_entry(mode, &oid, path, 2);
292 die(_("make_cache_entry failed for path '%s'"), path);
293 status = checkout_entry(ce, state, NULL, nr_checkouts);
294 discard_cache_entry(ce);
298 static void mark_ce_for_checkout_overlay(struct cache_entry *ce,
300 const struct checkout_opts *opts)
302 ce->ce_flags &= ~CE_MATCHED;
303 if (!opts->ignore_skipworktree && ce_skip_worktree(ce))
305 if (opts->source_tree && !(ce->ce_flags & CE_UPDATE))
307 * "git checkout tree-ish -- path", but this entry
308 * is in the original index but is not in tree-ish
309 * or does not match the pathspec; it will not be
310 * checked out to the working tree. We will not do
311 * anything to this entry at all.
315 * Either this entry came from the tree-ish we are
316 * checking the paths out of, or we are checking out
319 * If it comes from the tree-ish, we already know it
320 * matches the pathspec and could just stamp
321 * CE_MATCHED to it from update_some(). But we still
322 * need ps_matched and read_tree_recursive (and
323 * eventually tree_entry_interesting) cannot fill
324 * ps_matched yet. Once it can, we can avoid calling
325 * match_pathspec() for _all_ entries when
326 * opts->source_tree != NULL.
328 if (ce_path_match(&the_index, ce, &opts->pathspec, ps_matched))
329 ce->ce_flags |= CE_MATCHED;
332 static void mark_ce_for_checkout_no_overlay(struct cache_entry *ce,
334 const struct checkout_opts *opts)
336 ce->ce_flags &= ~CE_MATCHED;
337 if (!opts->ignore_skipworktree && ce_skip_worktree(ce))
339 if (ce_path_match(&the_index, ce, &opts->pathspec, ps_matched)) {
340 ce->ce_flags |= CE_MATCHED;
341 if (opts->source_tree && !(ce->ce_flags & CE_UPDATE))
343 * In overlay mode, but the path is not in
344 * tree-ish, which means we should remove it
345 * from the index and the working tree.
347 ce->ce_flags |= CE_REMOVE | CE_WT_REMOVE;
351 static int checkout_worktree(const struct checkout_opts *opts,
352 const struct branch_info *info)
354 struct checkout state = CHECKOUT_INIT;
355 int nr_checkouts = 0, nr_unmerged = 0;
360 state.refresh_cache = 1;
361 state.istate = &the_index;
363 enable_delayed_checkout(&state);
364 for (pos = 0; pos < active_nr; pos++) {
365 struct cache_entry *ce = active_cache[pos];
366 if (ce->ce_flags & CE_MATCHED) {
368 errs |= checkout_entry(ce, &state,
369 NULL, &nr_checkouts);
372 if (opts->writeout_stage)
373 errs |= checkout_stage(opts->writeout_stage,
376 &nr_checkouts, opts->overlay_mode);
377 else if (opts->merge)
378 errs |= checkout_merged(pos, &state,
380 pos = skip_same_name(ce, pos) - 1;
383 remove_marked_cache_entries(&the_index, 1);
384 remove_scheduled_dirs();
385 errs |= finish_delayed_checkout(&state, &nr_checkouts);
387 if (opts->count_checkout_paths) {
389 fprintf_ln(stderr, Q_("Recreated %d merge conflict",
390 "Recreated %d merge conflicts",
393 if (opts->source_tree)
394 fprintf_ln(stderr, Q_("Updated %d path from %s",
395 "Updated %d paths from %s",
398 find_unique_abbrev(&opts->source_tree->object.oid,
400 else if (!nr_unmerged || nr_checkouts)
401 fprintf_ln(stderr, Q_("Updated %d path from the index",
402 "Updated %d paths from the index",
410 static int checkout_paths(const struct checkout_opts *opts,
411 const struct branch_info *new_branch_info)
414 static char *ps_matched;
415 struct object_id rev;
418 struct lock_file lock_file = LOCK_INIT;
421 trace2_cmd_mode(opts->patch_mode ? "patch" : "path");
423 if (opts->track != BRANCH_TRACK_UNSPECIFIED)
424 die(_("'%s' cannot be used with updating paths"), "--track");
426 if (opts->new_branch_log)
427 die(_("'%s' cannot be used with updating paths"), "-l");
429 if (opts->ignore_unmerged && opts->patch_mode)
430 die(_("'%s' cannot be used with updating paths"),
431 opts->ignore_unmerged_opt);
433 if (opts->force_detach)
434 die(_("'%s' cannot be used with updating paths"), "--detach");
436 if (opts->merge && opts->patch_mode)
437 die(_("'%s' cannot be used with %s"), "--merge", "--patch");
439 if (opts->ignore_unmerged && opts->merge)
440 die(_("'%s' cannot be used with %s"),
441 opts->ignore_unmerged_opt, "-m");
443 if (opts->new_branch)
444 die(_("Cannot update paths and switch to branch '%s' at the same time."),
447 if (!opts->checkout_worktree && !opts->checkout_index)
448 die(_("neither '%s' or '%s' is specified"),
449 "--staged", "--worktree");
451 if (!opts->checkout_worktree && !opts->from_treeish)
452 die(_("'%s' must be used when '%s' is not specified"),
453 "--worktree", "--source");
455 if (opts->checkout_index && !opts->checkout_worktree &&
456 opts->writeout_stage)
457 die(_("'%s' or '%s' cannot be used with %s"),
458 "--ours", "--theirs", "--staged");
460 if (opts->checkout_index && !opts->checkout_worktree &&
462 die(_("'%s' or '%s' cannot be used with %s"),
463 "--merge", "--conflict", "--staged");
465 if (opts->patch_mode) {
466 const char *patch_mode;
468 if (opts->checkout_index && opts->checkout_worktree)
469 patch_mode = "--patch=checkout";
470 else if (opts->checkout_index && !opts->checkout_worktree)
471 patch_mode = "--patch=reset";
472 else if (!opts->checkout_index && opts->checkout_worktree)
473 patch_mode = "--patch=worktree";
475 BUG("either flag must have been set, worktree=%d, index=%d",
476 opts->checkout_worktree, opts->checkout_index);
477 return run_add_interactive(new_branch_info->name, patch_mode, &opts->pathspec);
480 repo_hold_locked_index(the_repository, &lock_file, LOCK_DIE_ON_ERROR);
481 if (read_cache_preload(&opts->pathspec) < 0)
482 return error(_("index file corrupt"));
484 if (opts->source_tree)
485 read_tree_some(opts->source_tree, &opts->pathspec);
487 ps_matched = xcalloc(opts->pathspec.nr, 1);
490 * Make sure all pathspecs participated in locating the paths
493 for (pos = 0; pos < active_nr; pos++)
494 if (opts->overlay_mode)
495 mark_ce_for_checkout_overlay(active_cache[pos],
499 mark_ce_for_checkout_no_overlay(active_cache[pos],
503 if (report_path_error(ps_matched, &opts->pathspec)) {
509 /* "checkout -m path" to recreate conflicted state */
511 unmerge_marked_index(&the_index);
513 /* Any unmerged paths? */
514 for (pos = 0; pos < active_nr; pos++) {
515 const struct cache_entry *ce = active_cache[pos];
516 if (ce->ce_flags & CE_MATCHED) {
519 if (opts->ignore_unmerged) {
521 warning(_("path '%s' is unmerged"), ce->name);
522 } else if (opts->writeout_stage) {
523 errs |= check_stage(opts->writeout_stage, ce, pos, opts->overlay_mode);
524 } else if (opts->merge) {
525 errs |= check_stages((1<<2) | (1<<3), ce, pos);
528 error(_("path '%s' is unmerged"), ce->name);
530 pos = skip_same_name(ce, pos) - 1;
536 /* Now we are committed to check them out */
537 if (opts->checkout_worktree)
538 errs |= checkout_worktree(opts, new_branch_info);
540 remove_marked_cache_entries(&the_index, 1);
543 * Allow updating the index when checking out from the index.
544 * This is to save new stat info.
546 if (opts->checkout_worktree && !opts->checkout_index && !opts->source_tree)
549 checkout_index = opts->checkout_index;
551 if (checkout_index) {
552 if (write_locked_index(&the_index, &lock_file, COMMIT_LOCK))
553 die(_("unable to write new index file"));
556 * NEEDSWORK: if --worktree is not specified, we
557 * should save stat info of checked out files in the
558 * index to avoid the next (potentially costly)
559 * refresh. But it's a bit tricker to do...
561 rollback_lock_file(&lock_file);
564 read_ref_full("HEAD", 0, &rev, NULL);
565 head = lookup_commit_reference_gently(the_repository, &rev, 1);
567 errs |= post_checkout_hook(head, head, 0);
571 static void show_local_changes(struct object *head,
572 const struct diff_options *opts)
575 /* I think we want full paths, even if we're in a subdirectory. */
576 repo_init_revisions(the_repository, &rev, NULL);
577 rev.diffopt.flags = opts->flags;
578 rev.diffopt.output_format |= DIFF_FORMAT_NAME_STATUS;
579 diff_setup_done(&rev.diffopt);
580 add_pending_object(&rev, head, NULL);
581 run_diff_index(&rev, 0);
584 static void describe_detached_head(const char *msg, struct commit *commit)
586 struct strbuf sb = STRBUF_INIT;
588 if (!parse_commit(commit))
589 pp_commit_easy(CMIT_FMT_ONELINE, commit, &sb);
590 if (print_sha1_ellipsis()) {
591 fprintf(stderr, "%s %s... %s\n", msg,
592 find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV), sb.buf);
594 fprintf(stderr, "%s %s %s\n", msg,
595 find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV), sb.buf);
600 static int reset_tree(struct tree *tree, const struct checkout_opts *o,
601 int worktree, int *writeout_error)
603 struct unpack_trees_options opts;
604 struct tree_desc tree_desc;
606 memset(&opts, 0, sizeof(opts));
608 opts.update = worktree;
609 opts.skip_unmerged = !worktree;
612 opts.fn = oneway_merge;
613 opts.verbose_update = o->show_progress;
614 opts.src_index = &the_index;
615 opts.dst_index = &the_index;
617 init_tree_desc(&tree_desc, tree->buffer, tree->size);
618 switch (unpack_trees(1, &tree_desc, &opts)) {
622 * We return 0 nevertheless, as the index is all right
623 * and more importantly we have made best efforts to
624 * update paths in the work tree, and we cannot revert
635 static void setup_branch_path(struct branch_info *branch)
637 struct strbuf buf = STRBUF_INIT;
639 strbuf_branchname(&buf, branch->name, INTERPRET_BRANCH_LOCAL);
640 if (strcmp(buf.buf, branch->name))
641 branch->name = xstrdup(buf.buf);
642 strbuf_splice(&buf, 0, 0, "refs/heads/", 11);
643 branch->path = strbuf_detach(&buf, NULL);
646 static int merge_working_tree(const struct checkout_opts *opts,
647 struct branch_info *old_branch_info,
648 struct branch_info *new_branch_info,
652 struct lock_file lock_file = LOCK_INIT;
653 struct tree *new_tree;
655 hold_locked_index(&lock_file, LOCK_DIE_ON_ERROR);
656 if (read_cache_preload(NULL) < 0)
657 return error(_("index file corrupt"));
659 resolve_undo_clear();
660 if (opts->new_orphan_branch && opts->orphan_from_empty_tree) {
661 if (new_branch_info->commit)
662 BUG("'switch --orphan' should never accept a commit as starting point");
663 new_tree = parse_tree_indirect(the_hash_algo->empty_tree);
665 new_tree = get_commit_tree(new_branch_info->commit);
666 if (opts->discard_changes) {
667 ret = reset_tree(new_tree, opts, 1, writeout_error);
671 struct tree_desc trees[2];
673 struct unpack_trees_options topts;
675 memset(&topts, 0, sizeof(topts));
677 topts.src_index = &the_index;
678 topts.dst_index = &the_index;
680 setup_unpack_trees_porcelain(&topts, "checkout");
682 refresh_cache(REFRESH_QUIET);
684 if (unmerged_cache()) {
685 error(_("you need to resolve your current index first"));
689 /* 2-way merge to the new branch */
690 topts.initial_checkout = is_cache_unborn();
693 topts.quiet = opts->merge && old_branch_info->commit;
694 topts.verbose_update = opts->show_progress;
695 topts.fn = twoway_merge;
696 if (opts->overwrite_ignore) {
697 topts.dir = xcalloc(1, sizeof(*topts.dir));
698 topts.dir->flags |= DIR_SHOW_IGNORED;
699 setup_standard_excludes(topts.dir);
701 tree = parse_tree_indirect(old_branch_info->commit ?
702 &old_branch_info->commit->object.oid :
703 the_hash_algo->empty_tree);
704 init_tree_desc(&trees[0], tree->buffer, tree->size);
705 parse_tree(new_tree);
707 init_tree_desc(&trees[1], tree->buffer, tree->size);
709 ret = unpack_trees(2, trees, &topts);
710 clear_unpack_trees_porcelain(&topts);
713 * Unpack couldn't do a trivial merge; either
714 * give up or do a real merge, depending on
715 * whether the merge flag was used.
718 struct tree *old_tree;
719 struct merge_options o;
720 struct strbuf sb = STRBUF_INIT;
721 struct strbuf old_commit_shortname = STRBUF_INIT;
727 * Without old_branch_info->commit, the below is the same as
728 * the two-tree unpack we already tried and failed.
730 if (!old_branch_info->commit)
732 old_tree = get_commit_tree(old_branch_info->commit);
734 if (repo_index_has_changes(the_repository, old_tree, &sb))
735 die(_("cannot continue with staged changes in "
736 "the following files:\n%s"), sb.buf);
739 /* Do more real merge */
742 * We update the index fully, then write the
743 * tree from the index, then merge the new
744 * branch with the current tree, with the old
745 * branch as the base. Then we reset the index
746 * (but not the working tree) to the new
747 * branch, leaving the working tree as the
748 * merged version, but skipping unmerged
749 * entries in the index.
752 add_files_to_cache(NULL, NULL, 0);
754 * NEEDSWORK: carrying over local changes
755 * when branches have different end-of-line
756 * normalization (or clean+smudge rules) is
757 * a pain; plumb in an option to set
760 init_merge_options(&o, the_repository);
762 work = write_in_core_index_as_tree(the_repository);
764 ret = reset_tree(new_tree,
769 o.ancestor = old_branch_info->name;
770 if (old_branch_info->name == NULL) {
771 strbuf_add_unique_abbrev(&old_commit_shortname,
772 &old_branch_info->commit->object.oid,
774 o.ancestor = old_commit_shortname.buf;
776 o.branch1 = new_branch_info->name;
778 ret = merge_trees(&o,
784 ret = reset_tree(new_tree,
787 strbuf_release(&o.obuf);
788 strbuf_release(&old_commit_shortname);
794 if (!active_cache_tree)
795 active_cache_tree = cache_tree();
797 if (!cache_tree_fully_valid(active_cache_tree))
798 cache_tree_update(&the_index, WRITE_TREE_SILENT | WRITE_TREE_REPAIR);
800 if (write_locked_index(&the_index, &lock_file, COMMIT_LOCK))
801 die(_("unable to write new index file"));
803 if (!opts->discard_changes && !opts->quiet && new_branch_info->commit)
804 show_local_changes(&new_branch_info->commit->object, &opts->diff_options);
809 static void report_tracking(struct branch_info *new_branch_info)
811 struct strbuf sb = STRBUF_INIT;
812 struct branch *branch = branch_get(new_branch_info->name);
814 if (!format_tracking_info(branch, &sb, AHEAD_BEHIND_FULL))
816 fputs(sb.buf, stdout);
820 static void update_refs_for_switch(const struct checkout_opts *opts,
821 struct branch_info *old_branch_info,
822 struct branch_info *new_branch_info)
824 struct strbuf msg = STRBUF_INIT;
825 const char *old_desc, *reflog_msg;
826 if (opts->new_branch) {
827 if (opts->new_orphan_branch) {
830 refname = mkpathdup("refs/heads/%s", opts->new_orphan_branch);
831 if (opts->new_branch_log &&
832 !should_autocreate_reflog(refname)) {
834 struct strbuf err = STRBUF_INIT;
836 ret = safe_create_reflog(refname, 1, &err);
838 fprintf(stderr, _("Can not do reflog for '%s': %s\n"),
839 opts->new_orphan_branch, err.buf);
840 strbuf_release(&err);
844 strbuf_release(&err);
849 create_branch(the_repository,
850 opts->new_branch, new_branch_info->name,
851 opts->new_branch_force ? 1 : 0,
852 opts->new_branch_force ? 1 : 0,
853 opts->new_branch_log,
856 new_branch_info->name = opts->new_branch;
857 setup_branch_path(new_branch_info);
860 old_desc = old_branch_info->name;
861 if (!old_desc && old_branch_info->commit)
862 old_desc = oid_to_hex(&old_branch_info->commit->object.oid);
864 reflog_msg = getenv("GIT_REFLOG_ACTION");
866 strbuf_addf(&msg, "checkout: moving from %s to %s",
867 old_desc ? old_desc : "(invalid)", new_branch_info->name);
869 strbuf_insertstr(&msg, 0, reflog_msg);
871 if (!strcmp(new_branch_info->name, "HEAD") && !new_branch_info->path && !opts->force_detach) {
873 } else if (opts->force_detach || !new_branch_info->path) { /* No longer on any branch. */
874 update_ref(msg.buf, "HEAD", &new_branch_info->commit->object.oid, NULL,
875 REF_NO_DEREF, UPDATE_REFS_DIE_ON_ERR);
877 if (old_branch_info->path &&
878 advice_detached_head && !opts->force_detach)
879 detach_advice(new_branch_info->name);
880 describe_detached_head(_("HEAD is now at"), new_branch_info->commit);
882 } else if (new_branch_info->path) { /* Switch branches. */
883 if (create_symref("HEAD", new_branch_info->path, msg.buf) < 0)
884 die(_("unable to update HEAD"));
886 if (old_branch_info->path && !strcmp(new_branch_info->path, old_branch_info->path)) {
887 if (opts->new_branch_force)
888 fprintf(stderr, _("Reset branch '%s'\n"),
889 new_branch_info->name);
891 fprintf(stderr, _("Already on '%s'\n"),
892 new_branch_info->name);
893 } else if (opts->new_branch) {
894 if (opts->branch_exists)
895 fprintf(stderr, _("Switched to and reset branch '%s'\n"), new_branch_info->name);
897 fprintf(stderr, _("Switched to a new branch '%s'\n"), new_branch_info->name);
899 fprintf(stderr, _("Switched to branch '%s'\n"),
900 new_branch_info->name);
903 if (old_branch_info->path && old_branch_info->name) {
904 if (!ref_exists(old_branch_info->path) && reflog_exists(old_branch_info->path))
905 delete_reflog(old_branch_info->path);
908 remove_branch_state(the_repository, !opts->quiet);
909 strbuf_release(&msg);
911 (new_branch_info->path || (!opts->force_detach && !strcmp(new_branch_info->name, "HEAD"))))
912 report_tracking(new_branch_info);
915 static int add_pending_uninteresting_ref(const char *refname,
916 const struct object_id *oid,
917 int flags, void *cb_data)
919 add_pending_oid(cb_data, refname, oid, UNINTERESTING);
923 static void describe_one_orphan(struct strbuf *sb, struct commit *commit)
925 strbuf_addstr(sb, " ");
926 strbuf_add_unique_abbrev(sb, &commit->object.oid, DEFAULT_ABBREV);
927 strbuf_addch(sb, ' ');
928 if (!parse_commit(commit))
929 pp_commit_easy(CMIT_FMT_ONELINE, commit, sb);
930 strbuf_addch(sb, '\n');
933 #define ORPHAN_CUTOFF 4
934 static void suggest_reattach(struct commit *commit, struct rev_info *revs)
936 struct commit *c, *last = NULL;
937 struct strbuf sb = STRBUF_INIT;
939 while ((c = get_revision(revs)) != NULL) {
940 if (lost < ORPHAN_CUTOFF)
941 describe_one_orphan(&sb, c);
945 if (ORPHAN_CUTOFF < lost) {
946 int more = lost - ORPHAN_CUTOFF;
948 describe_one_orphan(&sb, last);
950 strbuf_addf(&sb, _(" ... and %d more.\n"), more);
955 /* The singular version */
956 "Warning: you are leaving %d commit behind, "
958 "any of your branches:\n\n"
960 /* The plural version */
961 "Warning: you are leaving %d commits behind, "
963 "any of your branches:\n\n"
965 /* Give ngettext() the count */
971 if (advice_detached_head)
974 /* The singular version */
975 "If you want to keep it by creating a new branch, "
976 "this may be a good time\nto do so with:\n\n"
977 " git branch <new-branch-name> %s\n\n",
978 /* The plural version */
979 "If you want to keep them by creating a new branch, "
980 "this may be a good time\nto do so with:\n\n"
981 " git branch <new-branch-name> %s\n\n",
982 /* Give ngettext() the count */
984 find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV));
988 * We are about to leave commit that was at the tip of a detached
989 * HEAD. If it is not reachable from any ref, this is the last chance
990 * for the user to do so without resorting to reflog.
992 static void orphaned_commit_warning(struct commit *old_commit, struct commit *new_commit)
994 struct rev_info revs;
995 struct object *object = &old_commit->object;
997 repo_init_revisions(the_repository, &revs, NULL);
998 setup_revisions(0, NULL, &revs, NULL);
1000 object->flags &= ~UNINTERESTING;
1001 add_pending_object(&revs, object, oid_to_hex(&object->oid));
1003 for_each_ref(add_pending_uninteresting_ref, &revs);
1005 add_pending_oid(&revs, "HEAD",
1006 &new_commit->object.oid,
1009 if (prepare_revision_walk(&revs))
1010 die(_("internal error in revision walk"));
1011 if (!(old_commit->object.flags & UNINTERESTING))
1012 suggest_reattach(old_commit, &revs);
1014 describe_detached_head(_("Previous HEAD position was"), old_commit);
1016 /* Clean up objects used, as they will be reused. */
1017 clear_commit_marks_all(ALL_REV_FLAGS);
1020 static int switch_branches(const struct checkout_opts *opts,
1021 struct branch_info *new_branch_info)
1024 struct branch_info old_branch_info;
1026 struct object_id rev;
1027 int flag, writeout_error = 0;
1030 trace2_cmd_mode("branch");
1032 memset(&old_branch_info, 0, sizeof(old_branch_info));
1033 old_branch_info.path = path_to_free = resolve_refdup("HEAD", 0, &rev, &flag);
1034 if (old_branch_info.path)
1035 old_branch_info.commit = lookup_commit_reference_gently(the_repository, &rev, 1);
1036 if (!(flag & REF_ISSYMREF))
1037 old_branch_info.path = NULL;
1039 if (old_branch_info.path)
1040 skip_prefix(old_branch_info.path, "refs/heads/", &old_branch_info.name);
1042 if (opts->new_orphan_branch && opts->orphan_from_empty_tree) {
1043 if (new_branch_info->name)
1044 BUG("'switch --orphan' should never accept a commit as starting point");
1045 new_branch_info->commit = NULL;
1046 new_branch_info->name = "(empty)";
1050 if (!new_branch_info->name) {
1051 new_branch_info->name = "HEAD";
1052 new_branch_info->commit = old_branch_info.commit;
1053 if (!new_branch_info->commit)
1054 die(_("You are on a branch yet to be born"));
1055 parse_commit_or_die(new_branch_info->commit);
1057 if (opts->only_merge_on_switching_branches)
1062 ret = merge_working_tree(opts, &old_branch_info, new_branch_info, &writeout_error);
1069 if (!opts->quiet && !old_branch_info.path && old_branch_info.commit && new_branch_info->commit != old_branch_info.commit)
1070 orphaned_commit_warning(old_branch_info.commit, new_branch_info->commit);
1072 update_refs_for_switch(opts, &old_branch_info, new_branch_info);
1074 ret = post_checkout_hook(old_branch_info.commit, new_branch_info->commit, 1);
1076 return ret || writeout_error;
1079 static int git_checkout_config(const char *var, const char *value, void *cb)
1081 if (!strcmp(var, "diff.ignoresubmodules")) {
1082 struct checkout_opts *opts = cb;
1083 handle_ignore_submodules_arg(&opts->diff_options, value);
1087 if (starts_with(var, "submodule."))
1088 return git_default_submodule_config(var, value, NULL);
1090 return git_xmerge_config(var, value, NULL);
1093 static void setup_new_branch_info_and_source_tree(
1094 struct branch_info *new_branch_info,
1095 struct checkout_opts *opts,
1096 struct object_id *rev,
1099 struct tree **source_tree = &opts->source_tree;
1100 struct object_id branch_rev;
1102 new_branch_info->name = arg;
1103 setup_branch_path(new_branch_info);
1105 if (!check_refname_format(new_branch_info->path, 0) &&
1106 !read_ref(new_branch_info->path, &branch_rev))
1107 oidcpy(rev, &branch_rev);
1109 new_branch_info->path = NULL; /* not an existing branch */
1111 new_branch_info->commit = lookup_commit_reference_gently(the_repository, rev, 1);
1112 if (!new_branch_info->commit) {
1114 *source_tree = parse_tree_indirect(rev);
1116 parse_commit_or_die(new_branch_info->commit);
1117 *source_tree = get_commit_tree(new_branch_info->commit);
1121 static const char *parse_remote_branch(const char *arg,
1122 struct object_id *rev,
1123 int could_be_checkout_paths)
1125 int num_matches = 0;
1126 const char *remote = unique_tracking_name(arg, rev, &num_matches);
1128 if (remote && could_be_checkout_paths) {
1129 die(_("'%s' could be both a local file and a tracking branch.\n"
1130 "Please use -- (and optionally --no-guess) to disambiguate"),
1134 if (!remote && num_matches > 1) {
1135 if (advice_checkout_ambiguous_remote_branch_name) {
1136 advise(_("If you meant to check out a remote tracking branch on, e.g. 'origin',\n"
1137 "you can do so by fully qualifying the name with the --track option:\n"
1139 " git checkout --track origin/<name>\n"
1141 "If you'd like to always have checkouts of an ambiguous <name> prefer\n"
1142 "one remote, e.g. the 'origin' remote, consider setting\n"
1143 "checkout.defaultRemote=origin in your config."));
1146 die(_("'%s' matched multiple (%d) remote tracking branches"),
1153 static int parse_branchname_arg(int argc, const char **argv,
1154 int dwim_new_local_branch_ok,
1155 struct branch_info *new_branch_info,
1156 struct checkout_opts *opts,
1157 struct object_id *rev)
1159 const char **new_branch = &opts->new_branch;
1163 int has_dash_dash = 0;
1167 * case 1: git checkout <ref> -- [<paths>]
1169 * <ref> must be a valid tree, everything after the '--' must be
1172 * case 2: git checkout -- [<paths>]
1174 * everything after the '--' must be paths.
1176 * case 3: git checkout <something> [--]
1178 * (a) If <something> is a commit, that is to
1179 * switch to the branch or detach HEAD at it. As a special case,
1180 * if <something> is A...B (missing A or B means HEAD but you can
1181 * omit at most one side), and if there is a unique merge base
1182 * between A and B, A...B names that merge base.
1184 * (b) If <something> is _not_ a commit, either "--" is present
1185 * or <something> is not a path, no -t or -b was given, and
1186 * and there is a tracking branch whose name is <something>
1187 * in one and only one remote (or if the branch exists on the
1188 * remote named in checkout.defaultRemote), then this is a
1189 * short-hand to fork local <something> from that
1190 * remote-tracking branch.
1192 * (c) Otherwise, if "--" is present, treat it like case (1).
1195 * - if it's a reference, treat it like case (1)
1196 * - else if it's a path, treat it like case (2)
1199 * case 4: git checkout <something> <paths>
1201 * The first argument must not be ambiguous.
1202 * - If it's *only* a reference, treat it like case (1).
1203 * - If it's only a path, treat it like case (2).
1210 if (!opts->accept_pathspec) {
1212 die(_("only one reference expected"));
1213 has_dash_dash = 1; /* helps disambiguate */
1218 for (i = 0; i < argc; i++) {
1219 if (opts->accept_pathspec && !strcmp(argv[i], "--")) {
1224 if (dash_dash_pos == 0)
1225 return 1; /* case (2) */
1226 else if (dash_dash_pos == 1)
1227 has_dash_dash = 1; /* case (3) or (1) */
1228 else if (dash_dash_pos >= 2)
1229 die(_("only one reference expected, %d given."), dash_dash_pos);
1230 opts->count_checkout_paths = !opts->quiet && !has_dash_dash;
1232 if (!strcmp(arg, "-"))
1235 if (get_oid_mb(arg, rev)) {
1237 * Either case (3) or (4), with <something> not being
1238 * a commit, or an attempt to use case (1) with an
1241 * It's likely an error, but we need to find out if
1242 * we should auto-create the branch, case (3).(b).
1244 int recover_with_dwim = dwim_new_local_branch_ok;
1246 int could_be_checkout_paths = !has_dash_dash &&
1247 check_filename(opts->prefix, arg);
1249 if (!has_dash_dash && !no_wildcard(arg))
1250 recover_with_dwim = 0;
1253 * Accept "git checkout foo", "git checkout foo --"
1254 * and "git switch foo" as candidates for dwim.
1256 if (!(argc == 1 && !has_dash_dash) &&
1257 !(argc == 2 && has_dash_dash) &&
1258 opts->accept_pathspec)
1259 recover_with_dwim = 0;
1261 if (recover_with_dwim) {
1262 const char *remote = parse_remote_branch(arg, rev,
1263 could_be_checkout_paths);
1267 /* DWIMmed to create local branch, case (3).(b) */
1269 recover_with_dwim = 0;
1273 if (!recover_with_dwim) {
1275 die(_("invalid reference: %s"), arg);
1280 /* we can't end up being in (2) anymore, eat the argument */
1285 setup_new_branch_info_and_source_tree(new_branch_info, opts, rev, arg);
1287 if (!opts->source_tree) /* case (1): want a tree */
1288 die(_("reference is not a tree: %s"), arg);
1290 if (!has_dash_dash) { /* case (3).(d) -> (1) */
1292 * Do not complain the most common case
1293 * git checkout branch
1294 * even if there happen to be a file called 'branch';
1295 * it would be extremely annoying.
1298 verify_non_filename(opts->prefix, arg);
1299 } else if (opts->accept_pathspec) {
1308 static int switch_unborn_to_new_branch(const struct checkout_opts *opts)
1311 struct strbuf branch_ref = STRBUF_INIT;
1313 trace2_cmd_mode("unborn");
1315 if (!opts->new_branch)
1316 die(_("You are on a branch yet to be born"));
1317 strbuf_addf(&branch_ref, "refs/heads/%s", opts->new_branch);
1318 status = create_symref("HEAD", branch_ref.buf, "checkout -b");
1319 strbuf_release(&branch_ref);
1321 fprintf(stderr, _("Switched to a new branch '%s'\n"),
1326 static void die_expecting_a_branch(const struct branch_info *branch_info)
1328 struct object_id oid;
1331 if (dwim_ref(branch_info->name, strlen(branch_info->name), &oid, &to_free) == 1) {
1332 const char *ref = to_free;
1334 if (skip_prefix(ref, "refs/tags/", &ref))
1335 die(_("a branch is expected, got tag '%s'"), ref);
1336 if (skip_prefix(ref, "refs/remotes/", &ref))
1337 die(_("a branch is expected, got remote branch '%s'"), ref);
1338 die(_("a branch is expected, got '%s'"), ref);
1340 if (branch_info->commit)
1341 die(_("a branch is expected, got commit '%s'"), branch_info->name);
1343 * This case should never happen because we already die() on
1344 * non-commit, but just in case.
1346 die(_("a branch is expected, got '%s'"), branch_info->name);
1349 static void die_if_some_operation_in_progress(void)
1351 struct wt_status_state state;
1353 memset(&state, 0, sizeof(state));
1354 wt_status_get_state(the_repository, &state, 0);
1356 if (state.merge_in_progress)
1357 die(_("cannot switch branch while merging\n"
1358 "Consider \"git merge --quit\" "
1359 "or \"git worktree add\"."));
1360 if (state.am_in_progress)
1361 die(_("cannot switch branch in the middle of an am session\n"
1362 "Consider \"git am --quit\" "
1363 "or \"git worktree add\"."));
1364 if (state.rebase_interactive_in_progress || state.rebase_in_progress)
1365 die(_("cannot switch branch while rebasing\n"
1366 "Consider \"git rebase --quit\" "
1367 "or \"git worktree add\"."));
1368 if (state.cherry_pick_in_progress)
1369 die(_("cannot switch branch while cherry-picking\n"
1370 "Consider \"git cherry-pick --quit\" "
1371 "or \"git worktree add\"."));
1372 if (state.revert_in_progress)
1373 die(_("cannot switch branch while reverting\n"
1374 "Consider \"git revert --quit\" "
1375 "or \"git worktree add\"."));
1376 if (state.bisect_in_progress)
1377 warning(_("you are switching branch while bisecting"));
1380 static int checkout_branch(struct checkout_opts *opts,
1381 struct branch_info *new_branch_info)
1383 if (opts->pathspec.nr)
1384 die(_("paths cannot be used with switching branches"));
1386 if (opts->patch_mode)
1387 die(_("'%s' cannot be used with switching branches"),
1390 if (opts->overlay_mode != -1)
1391 die(_("'%s' cannot be used with switching branches"),
1394 if (opts->writeout_stage)
1395 die(_("'%s' cannot be used with switching branches"),
1398 if (opts->force && opts->merge)
1399 die(_("'%s' cannot be used with '%s'"), "-f", "-m");
1401 if (opts->discard_changes && opts->merge)
1402 die(_("'%s' cannot be used with '%s'"), "--discard-changes", "--merge");
1404 if (opts->force_detach && opts->new_branch)
1405 die(_("'%s' cannot be used with '%s'"),
1406 "--detach", "-b/-B/--orphan");
1408 if (opts->new_orphan_branch) {
1409 if (opts->track != BRANCH_TRACK_UNSPECIFIED)
1410 die(_("'%s' cannot be used with '%s'"), "--orphan", "-t");
1411 if (opts->orphan_from_empty_tree && new_branch_info->name)
1412 die(_("'%s' cannot take <start-point>"), "--orphan");
1413 } else if (opts->force_detach) {
1414 if (opts->track != BRANCH_TRACK_UNSPECIFIED)
1415 die(_("'%s' cannot be used with '%s'"), "--detach", "-t");
1416 } else if (opts->track == BRANCH_TRACK_UNSPECIFIED)
1417 opts->track = git_branch_track;
1419 if (new_branch_info->name && !new_branch_info->commit)
1420 die(_("Cannot switch branch to a non-commit '%s'"),
1421 new_branch_info->name);
1423 if (!opts->switch_branch_doing_nothing_is_ok &&
1424 !new_branch_info->name &&
1425 !opts->new_branch &&
1426 !opts->force_detach)
1427 die(_("missing branch or commit argument"));
1429 if (!opts->implicit_detach &&
1430 !opts->force_detach &&
1431 !opts->new_branch &&
1432 !opts->new_branch_force &&
1433 new_branch_info->name &&
1434 !new_branch_info->path)
1435 die_expecting_a_branch(new_branch_info);
1437 if (!opts->can_switch_when_in_progress)
1438 die_if_some_operation_in_progress();
1440 if (new_branch_info->path && !opts->force_detach && !opts->new_branch &&
1441 !opts->ignore_other_worktrees) {
1443 char *head_ref = resolve_refdup("HEAD", 0, NULL, &flag);
1445 (!(flag & REF_ISSYMREF) || strcmp(head_ref, new_branch_info->path)))
1446 die_if_checked_out(new_branch_info->path, 1);
1450 if (!new_branch_info->commit && opts->new_branch) {
1451 struct object_id rev;
1454 if (!read_ref_full("HEAD", 0, &rev, &flag) &&
1455 (flag & REF_ISSYMREF) && is_null_oid(&rev))
1456 return switch_unborn_to_new_branch(opts);
1458 return switch_branches(opts, new_branch_info);
1461 static struct option *add_common_options(struct checkout_opts *opts,
1462 struct option *prevopts)
1464 struct option options[] = {
1465 OPT__QUIET(&opts->quiet, N_("suppress progress reporting")),
1466 { OPTION_CALLBACK, 0, "recurse-submodules", NULL,
1467 "checkout", "control recursive updating of submodules",
1468 PARSE_OPT_OPTARG, option_parse_recurse_submodules_worktree_updater },
1469 OPT_BOOL(0, "progress", &opts->show_progress, N_("force progress reporting")),
1470 OPT_BOOL('m', "merge", &opts->merge, N_("perform a 3-way merge with the new branch")),
1471 OPT_STRING(0, "conflict", &opts->conflict_style, N_("style"),
1472 N_("conflict style (merge or diff3)")),
1475 struct option *newopts = parse_options_concat(prevopts, options);
1480 static struct option *add_common_switch_branch_options(
1481 struct checkout_opts *opts, struct option *prevopts)
1483 struct option options[] = {
1484 OPT_BOOL('d', "detach", &opts->force_detach, N_("detach HEAD at named commit")),
1485 OPT_SET_INT('t', "track", &opts->track, N_("set upstream info for new branch"),
1486 BRANCH_TRACK_EXPLICIT),
1487 OPT__FORCE(&opts->force, N_("force checkout (throw away local modifications)"),
1488 PARSE_OPT_NOCOMPLETE),
1489 OPT_STRING(0, "orphan", &opts->new_orphan_branch, N_("new-branch"), N_("new unparented branch")),
1490 OPT_BOOL_F(0, "overwrite-ignore", &opts->overwrite_ignore,
1491 N_("update ignored files (default)"),
1492 PARSE_OPT_NOCOMPLETE),
1493 OPT_BOOL(0, "ignore-other-worktrees", &opts->ignore_other_worktrees,
1494 N_("do not check if another worktree is holding the given ref")),
1497 struct option *newopts = parse_options_concat(prevopts, options);
1502 static struct option *add_checkout_path_options(struct checkout_opts *opts,
1503 struct option *prevopts)
1505 struct option options[] = {
1506 OPT_SET_INT_F('2', "ours", &opts->writeout_stage,
1507 N_("checkout our version for unmerged files"),
1508 2, PARSE_OPT_NONEG),
1509 OPT_SET_INT_F('3', "theirs", &opts->writeout_stage,
1510 N_("checkout their version for unmerged files"),
1511 3, PARSE_OPT_NONEG),
1512 OPT_BOOL('p', "patch", &opts->patch_mode, N_("select hunks interactively")),
1513 OPT_BOOL(0, "ignore-skip-worktree-bits", &opts->ignore_skipworktree,
1514 N_("do not limit pathspecs to sparse entries only")),
1515 OPT_PATHSPEC_FROM_FILE(&opts->pathspec_from_file),
1516 OPT_PATHSPEC_FILE_NUL(&opts->pathspec_file_nul),
1519 struct option *newopts = parse_options_concat(prevopts, options);
1524 static int checkout_main(int argc, const char **argv, const char *prefix,
1525 struct checkout_opts *opts, struct option *options,
1526 const char * const usagestr[])
1528 struct branch_info new_branch_info;
1529 int parseopt_flags = 0;
1531 memset(&new_branch_info, 0, sizeof(new_branch_info));
1532 opts->overwrite_ignore = 1;
1533 opts->prefix = prefix;
1534 opts->show_progress = -1;
1536 git_config(git_checkout_config, opts);
1538 opts->track = BRANCH_TRACK_UNSPECIFIED;
1540 if (!opts->accept_pathspec && !opts->accept_ref)
1541 BUG("make up your mind, you need to take _something_");
1542 if (opts->accept_pathspec && opts->accept_ref)
1543 parseopt_flags = PARSE_OPT_KEEP_DASHDASH;
1545 argc = parse_options(argc, argv, prefix, options,
1546 usagestr, parseopt_flags);
1548 if (opts->show_progress < 0) {
1550 opts->show_progress = 0;
1552 opts->show_progress = isatty(2);
1555 if (opts->conflict_style) {
1556 opts->merge = 1; /* implied */
1557 git_xmerge_config("merge.conflictstyle", opts->conflict_style, NULL);
1560 opts->discard_changes = 1;
1561 opts->ignore_unmerged_opt = "--force";
1562 opts->ignore_unmerged = 1;
1565 if ((!!opts->new_branch + !!opts->new_branch_force + !!opts->new_orphan_branch) > 1)
1566 die(_("-b, -B and --orphan are mutually exclusive"));
1568 if (opts->overlay_mode == 1 && opts->patch_mode)
1569 die(_("-p and --overlay are mutually exclusive"));
1571 if (opts->checkout_index >= 0 || opts->checkout_worktree >= 0) {
1572 if (opts->checkout_index < 0)
1573 opts->checkout_index = 0;
1574 if (opts->checkout_worktree < 0)
1575 opts->checkout_worktree = 0;
1577 if (opts->checkout_index < 0)
1578 opts->checkout_index = -opts->checkout_index - 1;
1579 if (opts->checkout_worktree < 0)
1580 opts->checkout_worktree = -opts->checkout_worktree - 1;
1582 if (opts->checkout_index < 0 || opts->checkout_worktree < 0)
1583 BUG("these flags should be non-negative by now");
1585 * convenient shortcut: "git restore --staged" equals
1586 * "git restore --staged --source HEAD"
1588 if (!opts->from_treeish && opts->checkout_index && !opts->checkout_worktree)
1589 opts->from_treeish = "HEAD";
1592 * From here on, new_branch will contain the branch to be checked out,
1593 * and new_branch_force and new_orphan_branch will tell us which one of
1594 * -b/-B/--orphan is being used.
1596 if (opts->new_branch_force)
1597 opts->new_branch = opts->new_branch_force;
1599 if (opts->new_orphan_branch)
1600 opts->new_branch = opts->new_orphan_branch;
1602 /* --track without -b/-B/--orphan should DWIM */
1603 if (opts->track != BRANCH_TRACK_UNSPECIFIED && !opts->new_branch) {
1604 const char *argv0 = argv[0];
1605 if (!argc || !strcmp(argv0, "--"))
1606 die(_("--track needs a branch name"));
1607 skip_prefix(argv0, "refs/", &argv0);
1608 skip_prefix(argv0, "remotes/", &argv0);
1609 argv0 = strchr(argv0, '/');
1610 if (!argv0 || !argv0[1])
1611 die(_("missing branch name; try -b"));
1612 opts->new_branch = argv0 + 1;
1616 * Extract branch name from command line arguments, so
1617 * all that is left is pathspecs.
1621 * 1) git checkout <tree> -- [<paths>]
1622 * 2) git checkout -- [<paths>]
1623 * 3) git checkout <something> [<paths>]
1625 * including "last branch" syntax and DWIM-ery for names of
1626 * remote branches, erroring out for invalid or ambiguous cases.
1628 if (argc && opts->accept_ref) {
1629 struct object_id rev;
1631 !opts->patch_mode &&
1632 opts->dwim_new_local_branch &&
1633 opts->track == BRANCH_TRACK_UNSPECIFIED &&
1635 int n = parse_branchname_arg(argc, argv, dwim_ok,
1636 &new_branch_info, opts, &rev);
1639 } else if (!opts->accept_ref && opts->from_treeish) {
1640 struct object_id rev;
1642 if (get_oid_mb(opts->from_treeish, &rev))
1643 die(_("could not resolve %s"), opts->from_treeish);
1645 setup_new_branch_info_and_source_tree(&new_branch_info,
1647 opts->from_treeish);
1649 if (!opts->source_tree)
1650 die(_("reference is not a tree: %s"), opts->from_treeish);
1654 parse_pathspec(&opts->pathspec, 0,
1655 opts->patch_mode ? PATHSPEC_PREFIX_ORIGIN : 0,
1658 if (!opts->pathspec.nr)
1659 die(_("invalid path specification"));
1662 * Try to give more helpful suggestion.
1663 * new_branch && argc > 1 will be caught later.
1665 if (opts->new_branch && argc == 1)
1666 die(_("'%s' is not a commit and a branch '%s' cannot be created from it"),
1667 argv[0], opts->new_branch);
1669 if (opts->force_detach)
1670 die(_("git checkout: --detach does not take a path argument '%s'"),
1674 if (opts->pathspec_from_file) {
1675 if (opts->pathspec.nr)
1676 die(_("--pathspec-from-file is incompatible with pathspec arguments"));
1678 if (opts->force_detach)
1679 die(_("--pathspec-from-file is incompatible with --detach"));
1681 if (opts->patch_mode)
1682 die(_("--pathspec-from-file is incompatible with --patch"));
1684 parse_pathspec_file(&opts->pathspec, 0,
1686 prefix, opts->pathspec_from_file, opts->pathspec_file_nul);
1687 } else if (opts->pathspec_file_nul) {
1688 die(_("--pathspec-file-nul requires --pathspec-from-file"));
1691 if (opts->pathspec.nr) {
1692 if (1 < !!opts->writeout_stage + !!opts->force + !!opts->merge)
1693 die(_("git checkout: --ours/--theirs, --force and --merge are incompatible when\n"
1694 "checking out of the index."));
1696 if (opts->accept_pathspec && !opts->empty_pathspec_ok &&
1697 !opts->patch_mode) /* patch mode is special */
1698 die(_("you must specify path(s) to restore"));
1701 if (opts->new_branch) {
1702 struct strbuf buf = STRBUF_INIT;
1704 if (opts->new_branch_force)
1705 opts->branch_exists = validate_branchname(opts->new_branch, &buf);
1707 opts->branch_exists =
1708 validate_new_branchname(opts->new_branch, &buf, 0);
1709 strbuf_release(&buf);
1713 if (opts->patch_mode || opts->pathspec.nr)
1714 return checkout_paths(opts, &new_branch_info);
1716 return checkout_branch(opts, &new_branch_info);
1719 int cmd_checkout(int argc, const char **argv, const char *prefix)
1721 struct checkout_opts opts;
1722 struct option *options;
1723 struct option checkout_options[] = {
1724 OPT_STRING('b', NULL, &opts.new_branch, N_("branch"),
1725 N_("create and checkout a new branch")),
1726 OPT_STRING('B', NULL, &opts.new_branch_force, N_("branch"),
1727 N_("create/reset and checkout a branch")),
1728 OPT_BOOL('l', NULL, &opts.new_branch_log, N_("create reflog for new branch")),
1729 OPT_BOOL(0, "guess", &opts.dwim_new_local_branch,
1730 N_("second guess 'git checkout <no-such-branch>' (default)")),
1731 OPT_BOOL(0, "overlay", &opts.overlay_mode, N_("use overlay mode (default)")),
1736 memset(&opts, 0, sizeof(opts));
1737 opts.dwim_new_local_branch = 1;
1738 opts.switch_branch_doing_nothing_is_ok = 1;
1739 opts.only_merge_on_switching_branches = 0;
1740 opts.accept_ref = 1;
1741 opts.accept_pathspec = 1;
1742 opts.implicit_detach = 1;
1743 opts.can_switch_when_in_progress = 1;
1744 opts.orphan_from_empty_tree = 0;
1745 opts.empty_pathspec_ok = 1;
1746 opts.overlay_mode = -1;
1747 opts.checkout_index = -2; /* default on */
1748 opts.checkout_worktree = -2; /* default on */
1750 if (argc == 3 && !strcmp(argv[1], "-b")) {
1752 * User ran 'git checkout -b <branch>' and expects
1753 * the same behavior as 'git switch -c <branch>'.
1755 opts.switch_branch_doing_nothing_is_ok = 0;
1756 opts.only_merge_on_switching_branches = 1;
1759 options = parse_options_dup(checkout_options);
1760 options = add_common_options(&opts, options);
1761 options = add_common_switch_branch_options(&opts, options);
1762 options = add_checkout_path_options(&opts, options);
1764 ret = checkout_main(argc, argv, prefix, &opts,
1765 options, checkout_usage);
1766 FREE_AND_NULL(options);
1770 int cmd_switch(int argc, const char **argv, const char *prefix)
1772 struct checkout_opts opts;
1773 struct option *options = NULL;
1774 struct option switch_options[] = {
1775 OPT_STRING('c', "create", &opts.new_branch, N_("branch"),
1776 N_("create and switch to a new branch")),
1777 OPT_STRING('C', "force-create", &opts.new_branch_force, N_("branch"),
1778 N_("create/reset and switch to a branch")),
1779 OPT_BOOL(0, "guess", &opts.dwim_new_local_branch,
1780 N_("second guess 'git switch <no-such-branch>'")),
1781 OPT_BOOL(0, "discard-changes", &opts.discard_changes,
1782 N_("throw away local modifications")),
1787 memset(&opts, 0, sizeof(opts));
1788 opts.dwim_new_local_branch = 1;
1789 opts.accept_ref = 1;
1790 opts.accept_pathspec = 0;
1791 opts.switch_branch_doing_nothing_is_ok = 0;
1792 opts.only_merge_on_switching_branches = 1;
1793 opts.implicit_detach = 0;
1794 opts.can_switch_when_in_progress = 0;
1795 opts.orphan_from_empty_tree = 1;
1796 opts.overlay_mode = -1;
1798 options = parse_options_dup(switch_options);
1799 options = add_common_options(&opts, options);
1800 options = add_common_switch_branch_options(&opts, options);
1802 ret = checkout_main(argc, argv, prefix, &opts,
1803 options, switch_branch_usage);
1804 FREE_AND_NULL(options);
1808 int cmd_restore(int argc, const char **argv, const char *prefix)
1810 struct checkout_opts opts;
1811 struct option *options;
1812 struct option restore_options[] = {
1813 OPT_STRING('s', "source", &opts.from_treeish, "<tree-ish>",
1814 N_("which tree-ish to checkout from")),
1815 OPT_BOOL('S', "staged", &opts.checkout_index,
1816 N_("restore the index")),
1817 OPT_BOOL('W', "worktree", &opts.checkout_worktree,
1818 N_("restore the working tree (default)")),
1819 OPT_BOOL(0, "ignore-unmerged", &opts.ignore_unmerged,
1820 N_("ignore unmerged entries")),
1821 OPT_BOOL(0, "overlay", &opts.overlay_mode, N_("use overlay mode")),
1826 memset(&opts, 0, sizeof(opts));
1827 opts.accept_ref = 0;
1828 opts.accept_pathspec = 1;
1829 opts.empty_pathspec_ok = 0;
1830 opts.overlay_mode = 0;
1831 opts.checkout_index = -1; /* default off */
1832 opts.checkout_worktree = -2; /* default on */
1833 opts.ignore_unmerged_opt = "--ignore-unmerged";
1835 options = parse_options_dup(restore_options);
1836 options = add_common_options(&opts, options);
1837 options = add_checkout_path_options(&opts, options);
1839 ret = checkout_main(argc, argv, prefix, &opts,
1840 options, restore_usage);
1841 FREE_AND_NULL(options);