1 #define USE_THE_INDEX_VARIABLE
6 #include "cache-tree.h"
12 #include "environment.h"
18 #include "merge-recursive.h"
19 #include "object-store.h"
20 #include "parse-options.h"
23 #include "resolve-undo.h"
25 #include "run-command.h"
27 #include "submodule.h"
28 #include "submodule-config.h"
30 #include "tree-walk.h"
31 #include "unpack-trees.h"
32 #include "wt-status.h"
33 #include "xdiff-interface.h"
35 #include "parallel-checkout.h"
36 #include "add-interactive.h"
38 static const char * const checkout_usage
[] = {
39 N_("git checkout [<options>] <branch>"),
40 N_("git checkout [<options>] [<branch>] -- <file>..."),
44 static const char * const switch_branch_usage
[] = {
45 N_("git switch [<options>] [<branch>]"),
49 static const char * const restore_usage
[] = {
50 N_("git restore [<options>] [--source=<branch>] <file>..."),
54 struct checkout_opts
{
63 int ignore_skipworktree
;
64 int ignore_other_worktrees
;
66 int count_checkout_paths
;
68 int dwim_new_local_branch
;
72 int switch_branch_doing_nothing_is_ok
;
73 int only_merge_on_switching_branches
;
74 int can_switch_when_in_progress
;
75 int orphan_from_empty_tree
;
76 int empty_pathspec_ok
;
78 int checkout_worktree
;
79 const char *ignore_unmerged_opt
;
81 int pathspec_file_nul
;
82 char *pathspec_from_file
;
84 const char *new_branch
;
85 const char *new_branch_force
;
86 const char *new_orphan_branch
;
88 enum branch_track track
;
89 struct diff_options diff_options
;
94 struct pathspec pathspec
;
95 const char *from_treeish
;
96 struct tree
*source_tree
;
100 char *name
; /* The short name used */
101 char *path
; /* The full name of a real branch */
102 struct commit
*commit
; /* The named commit */
103 char *refname
; /* The full name of the ref being checked out. */
104 struct object_id oid
; /* The object ID of the commit being checked out. */
106 * if not null the branch is detached because it's already
107 * checked out in this checkout
112 static void branch_info_release(struct branch_info
*info
)
117 free(info
->checkout
);
120 static int post_checkout_hook(struct commit
*old_commit
, struct commit
*new_commit
,
123 return run_hooks_l("post-checkout",
124 oid_to_hex(old_commit
? &old_commit
->object
.oid
: null_oid()),
125 oid_to_hex(new_commit
? &new_commit
->object
.oid
: null_oid()),
126 changed
? "1" : "0", NULL
);
127 /* "new_commit" can be NULL when checking out from the index before
132 static int update_some(const struct object_id
*oid
, struct strbuf
*base
,
133 const char *pathname
, unsigned mode
, void *context UNUSED
)
136 struct cache_entry
*ce
;
140 return READ_TREE_RECURSIVE
;
142 len
= base
->len
+ strlen(pathname
);
143 ce
= make_empty_cache_entry(&the_index
, len
);
144 oidcpy(&ce
->oid
, oid
);
145 memcpy(ce
->name
, base
->buf
, base
->len
);
146 memcpy(ce
->name
+ base
->len
, pathname
, len
- base
->len
);
147 ce
->ce_flags
= create_ce_flags(0) | CE_UPDATE
;
148 ce
->ce_namelen
= len
;
149 ce
->ce_mode
= create_ce_mode(mode
);
152 * If the entry is the same as the current index, we can leave the old
153 * entry in place. Whether it is UPTODATE or not, checkout_entry will
154 * do the right thing.
156 pos
= index_name_pos(&the_index
, ce
->name
, ce
->ce_namelen
);
158 struct cache_entry
*old
= the_index
.cache
[pos
];
159 if (ce
->ce_mode
== old
->ce_mode
&&
160 !ce_intent_to_add(old
) &&
161 oideq(&ce
->oid
, &old
->oid
)) {
162 old
->ce_flags
|= CE_UPDATE
;
163 discard_cache_entry(ce
);
168 add_index_entry(&the_index
, ce
,
169 ADD_CACHE_OK_TO_ADD
| ADD_CACHE_OK_TO_REPLACE
);
173 static int read_tree_some(struct tree
*tree
, const struct pathspec
*pathspec
)
175 read_tree(the_repository
, tree
,
176 pathspec
, update_some
, NULL
);
178 /* update the index with the given tree's info
179 * for all args, expanding wildcards, and exit
180 * with any non-zero return code.
185 static int skip_same_name(const struct cache_entry
*ce
, int pos
)
187 while (++pos
< the_index
.cache_nr
&&
188 !strcmp(the_index
.cache
[pos
]->name
, ce
->name
))
193 static int check_stage(int stage
, const struct cache_entry
*ce
, int pos
,
196 while (pos
< the_index
.cache_nr
&&
197 !strcmp(the_index
.cache
[pos
]->name
, ce
->name
)) {
198 if (ce_stage(the_index
.cache
[pos
]) == stage
)
205 return error(_("path '%s' does not have our version"), ce
->name
);
207 return error(_("path '%s' does not have their version"), ce
->name
);
210 static int check_stages(unsigned stages
, const struct cache_entry
*ce
, int pos
)
213 const char *name
= ce
->name
;
215 while (pos
< the_index
.cache_nr
) {
216 ce
= the_index
.cache
[pos
];
217 if (strcmp(name
, ce
->name
))
219 seen
|= (1 << ce_stage(ce
));
222 if ((stages
& seen
) != stages
)
223 return error(_("path '%s' does not have all necessary versions"),
228 static int checkout_stage(int stage
, const struct cache_entry
*ce
, int pos
,
229 const struct checkout
*state
, int *nr_checkouts
,
232 while (pos
< the_index
.cache_nr
&&
233 !strcmp(the_index
.cache
[pos
]->name
, ce
->name
)) {
234 if (ce_stage(the_index
.cache
[pos
]) == stage
)
235 return checkout_entry(the_index
.cache
[pos
], state
,
240 unlink_entry(ce
, NULL
);
244 return error(_("path '%s' does not have our version"), ce
->name
);
246 return error(_("path '%s' does not have their version"), ce
->name
);
249 static int checkout_merged(int pos
, const struct checkout
*state
,
250 int *nr_checkouts
, struct mem_pool
*ce_mem_pool
)
252 struct cache_entry
*ce
= the_index
.cache
[pos
];
253 const char *path
= ce
->name
;
254 mmfile_t ancestor
, ours
, theirs
;
255 enum ll_merge_result merge_status
;
257 struct object_id oid
;
258 mmbuffer_t result_buf
;
259 struct object_id threeway
[3];
261 struct ll_merge_options ll_opts
;
264 memset(threeway
, 0, sizeof(threeway
));
265 while (pos
< the_index
.cache_nr
) {
267 stage
= ce_stage(ce
);
268 if (!stage
|| strcmp(path
, ce
->name
))
270 oidcpy(&threeway
[stage
- 1], &ce
->oid
);
272 mode
= create_ce_mode(ce
->ce_mode
);
274 ce
= the_index
.cache
[pos
];
276 if (is_null_oid(&threeway
[1]) || is_null_oid(&threeway
[2]))
277 return error(_("path '%s' does not have necessary versions"), path
);
279 read_mmblob(&ancestor
, &threeway
[0]);
280 read_mmblob(&ours
, &threeway
[1]);
281 read_mmblob(&theirs
, &threeway
[2]);
283 memset(&ll_opts
, 0, sizeof(ll_opts
));
284 git_config_get_bool("merge.renormalize", &renormalize
);
285 ll_opts
.renormalize
= renormalize
;
286 merge_status
= ll_merge(&result_buf
, path
, &ancestor
, "base",
287 &ours
, "ours", &theirs
, "theirs",
288 state
->istate
, &ll_opts
);
292 if (merge_status
== LL_MERGE_BINARY_CONFLICT
)
293 warning("Cannot merge binary files: %s (%s vs. %s)",
294 path
, "ours", "theirs");
295 if (merge_status
< 0 || !result_buf
.ptr
) {
296 free(result_buf
.ptr
);
297 return error(_("path '%s': cannot merge"), path
);
302 * There is absolutely no reason to write this as a blob object
303 * and create a phony cache entry. This hack is primarily to get
304 * to the write_entry() machinery that massages the contents to
305 * work-tree format and writes out which only allows it for a
306 * cache entry. The code in write_entry() needs to be refactored
307 * to allow us to feed a <buffer, size, mode> instead of a cache
308 * entry. Such a refactoring would help merge_recursive as well
309 * (it also writes the merge result to the object database even
310 * when it may contain conflicts).
312 if (write_object_file(result_buf
.ptr
, result_buf
.size
, OBJ_BLOB
, &oid
))
313 die(_("Unable to add merge result for '%s'"), path
);
314 free(result_buf
.ptr
);
315 ce
= make_transient_cache_entry(mode
, &oid
, path
, 2, ce_mem_pool
);
317 die(_("make_cache_entry failed for path '%s'"), path
);
318 status
= checkout_entry(ce
, state
, NULL
, nr_checkouts
);
322 static void mark_ce_for_checkout_overlay(struct cache_entry
*ce
,
324 const struct checkout_opts
*opts
)
326 ce
->ce_flags
&= ~CE_MATCHED
;
327 if (!opts
->ignore_skipworktree
&& ce_skip_worktree(ce
))
329 if (opts
->source_tree
&& !(ce
->ce_flags
& CE_UPDATE
))
331 * "git checkout tree-ish -- path", but this entry
332 * is in the original index but is not in tree-ish
333 * or does not match the pathspec; it will not be
334 * checked out to the working tree. We will not do
335 * anything to this entry at all.
339 * Either this entry came from the tree-ish we are
340 * checking the paths out of, or we are checking out
343 * If it comes from the tree-ish, we already know it
344 * matches the pathspec and could just stamp
345 * CE_MATCHED to it from update_some(). But we still
346 * need ps_matched and read_tree (and
347 * eventually tree_entry_interesting) cannot fill
348 * ps_matched yet. Once it can, we can avoid calling
349 * match_pathspec() for _all_ entries when
350 * opts->source_tree != NULL.
352 if (ce_path_match(&the_index
, ce
, &opts
->pathspec
, ps_matched
))
353 ce
->ce_flags
|= CE_MATCHED
;
356 static void mark_ce_for_checkout_no_overlay(struct cache_entry
*ce
,
358 const struct checkout_opts
*opts
)
360 ce
->ce_flags
&= ~CE_MATCHED
;
361 if (!opts
->ignore_skipworktree
&& ce_skip_worktree(ce
))
363 if (ce_path_match(&the_index
, ce
, &opts
->pathspec
, ps_matched
)) {
364 ce
->ce_flags
|= CE_MATCHED
;
365 if (opts
->source_tree
&& !(ce
->ce_flags
& CE_UPDATE
))
367 * In overlay mode, but the path is not in
368 * tree-ish, which means we should remove it
369 * from the index and the working tree.
371 ce
->ce_flags
|= CE_REMOVE
| CE_WT_REMOVE
;
375 static int checkout_worktree(const struct checkout_opts
*opts
,
376 const struct branch_info
*info
)
378 struct checkout state
= CHECKOUT_INIT
;
379 int nr_checkouts
= 0, nr_unmerged
= 0;
382 int pc_workers
, pc_threshold
;
383 struct mem_pool ce_mem_pool
;
386 state
.refresh_cache
= 1;
387 state
.istate
= &the_index
;
389 mem_pool_init(&ce_mem_pool
, 0);
390 get_parallel_checkout_configs(&pc_workers
, &pc_threshold
);
391 init_checkout_metadata(&state
.meta
, info
->refname
,
392 info
->commit
? &info
->commit
->object
.oid
: &info
->oid
,
395 enable_delayed_checkout(&state
);
398 init_parallel_checkout();
400 for (pos
= 0; pos
< the_index
.cache_nr
; pos
++) {
401 struct cache_entry
*ce
= the_index
.cache
[pos
];
402 if (ce
->ce_flags
& CE_MATCHED
) {
404 errs
|= checkout_entry(ce
, &state
,
405 NULL
, &nr_checkouts
);
408 if (opts
->writeout_stage
)
409 errs
|= checkout_stage(opts
->writeout_stage
,
412 &nr_checkouts
, opts
->overlay_mode
);
413 else if (opts
->merge
)
414 errs
|= checkout_merged(pos
, &state
,
417 pos
= skip_same_name(ce
, pos
) - 1;
421 errs
|= run_parallel_checkout(&state
, pc_workers
, pc_threshold
,
423 mem_pool_discard(&ce_mem_pool
, should_validate_cache_entries());
424 remove_marked_cache_entries(&the_index
, 1);
425 remove_scheduled_dirs();
426 errs
|= finish_delayed_checkout(&state
, opts
->show_progress
);
428 if (opts
->count_checkout_paths
) {
430 fprintf_ln(stderr
, Q_("Recreated %d merge conflict",
431 "Recreated %d merge conflicts",
434 if (opts
->source_tree
)
435 fprintf_ln(stderr
, Q_("Updated %d path from %s",
436 "Updated %d paths from %s",
439 find_unique_abbrev(&opts
->source_tree
->object
.oid
,
441 else if (!nr_unmerged
|| nr_checkouts
)
442 fprintf_ln(stderr
, Q_("Updated %d path from the index",
443 "Updated %d paths from the index",
451 static int checkout_paths(const struct checkout_opts
*opts
,
452 const struct branch_info
*new_branch_info
)
455 static char *ps_matched
;
456 struct object_id rev
;
459 struct lock_file lock_file
= LOCK_INIT
;
462 trace2_cmd_mode(opts
->patch_mode
? "patch" : "path");
464 if (opts
->track
!= BRANCH_TRACK_UNSPECIFIED
)
465 die(_("'%s' cannot be used with updating paths"), "--track");
467 if (opts
->new_branch_log
)
468 die(_("'%s' cannot be used with updating paths"), "-l");
470 if (opts
->ignore_unmerged
&& opts
->patch_mode
)
471 die(_("'%s' cannot be used with updating paths"),
472 opts
->ignore_unmerged_opt
);
474 if (opts
->force_detach
)
475 die(_("'%s' cannot be used with updating paths"), "--detach");
477 if (opts
->merge
&& opts
->patch_mode
)
478 die(_("options '%s' and '%s' cannot be used together"), "--merge", "--patch");
480 if (opts
->ignore_unmerged
&& opts
->merge
)
481 die(_("options '%s' and '%s' cannot be used together"),
482 opts
->ignore_unmerged_opt
, "-m");
484 if (opts
->new_branch
)
485 die(_("Cannot update paths and switch to branch '%s' at the same time."),
488 if (!opts
->checkout_worktree
&& !opts
->checkout_index
)
489 die(_("neither '%s' or '%s' is specified"),
490 "--staged", "--worktree");
492 if (!opts
->checkout_worktree
&& !opts
->from_treeish
)
493 die(_("'%s' must be used when '%s' is not specified"),
494 "--worktree", "--source");
497 * Reject --staged option to the restore command when combined with
498 * merge-related options. Use the accept_ref flag to distinguish it
499 * from the checkout command, which does not accept --staged anyway.
501 * `restore --ours|--theirs --worktree --staged` could mean resolving
502 * conflicted paths to one side in both the worktree and the index,
503 * but does not currently.
505 * `restore --merge|--conflict=<style>` already recreates conflicts
506 * in both the worktree and the index, so adding --staged would be
509 if (!opts
->accept_ref
&& opts
->checkout_index
) {
510 if (opts
->writeout_stage
)
511 die(_("'%s' or '%s' cannot be used with %s"),
512 "--ours", "--theirs", "--staged");
515 die(_("'%s' or '%s' cannot be used with %s"),
516 "--merge", "--conflict", "--staged");
519 if (opts
->patch_mode
) {
520 enum add_p_mode patch_mode
;
521 const char *rev
= new_branch_info
->name
;
522 char rev_oid
[GIT_MAX_HEXSZ
+ 1];
525 * Since rev can be in the form of `<a>...<b>` (which is not
526 * recognized by diff-index), we will always replace the name
527 * with the hex of the commit (whether it's in `...` form or
528 * not) for the run_add_interactive() machinery to work
529 * properly. However, there is special logic for the HEAD case
530 * so we mustn't replace that. Also, when we were given a
531 * tree-object, new_branch_info->commit would be NULL, but we
532 * do not have to do any replacement, either.
534 if (rev
&& new_branch_info
->commit
&& strcmp(rev
, "HEAD"))
535 rev
= oid_to_hex_r(rev_oid
, &new_branch_info
->commit
->object
.oid
);
537 if (opts
->checkout_index
&& opts
->checkout_worktree
)
538 patch_mode
= ADD_P_CHECKOUT
;
539 else if (opts
->checkout_index
&& !opts
->checkout_worktree
)
540 patch_mode
= ADD_P_RESET
;
541 else if (!opts
->checkout_index
&& opts
->checkout_worktree
)
542 patch_mode
= ADD_P_WORKTREE
;
544 BUG("either flag must have been set, worktree=%d, index=%d",
545 opts
->checkout_worktree
, opts
->checkout_index
);
546 return !!run_add_p(the_repository
, patch_mode
, rev
,
550 repo_hold_locked_index(the_repository
, &lock_file
, LOCK_DIE_ON_ERROR
);
551 if (repo_read_index_preload(the_repository
, &opts
->pathspec
, 0) < 0)
552 return error(_("index file corrupt"));
554 if (opts
->source_tree
)
555 read_tree_some(opts
->source_tree
, &opts
->pathspec
);
557 ps_matched
= xcalloc(opts
->pathspec
.nr
, 1);
560 * Make sure all pathspecs participated in locating the paths
563 for (pos
= 0; pos
< the_index
.cache_nr
; pos
++)
564 if (opts
->overlay_mode
)
565 mark_ce_for_checkout_overlay(the_index
.cache
[pos
],
569 mark_ce_for_checkout_no_overlay(the_index
.cache
[pos
],
573 if (report_path_error(ps_matched
, &opts
->pathspec
)) {
579 /* "checkout -m path" to recreate conflicted state */
581 unmerge_marked_index(&the_index
);
583 /* Any unmerged paths? */
584 for (pos
= 0; pos
< the_index
.cache_nr
; pos
++) {
585 const struct cache_entry
*ce
= the_index
.cache
[pos
];
586 if (ce
->ce_flags
& CE_MATCHED
) {
589 if (opts
->ignore_unmerged
) {
591 warning(_("path '%s' is unmerged"), ce
->name
);
592 } else if (opts
->writeout_stage
) {
593 errs
|= check_stage(opts
->writeout_stage
, ce
, pos
, opts
->overlay_mode
);
594 } else if (opts
->merge
) {
595 errs
|= check_stages((1<<2) | (1<<3), ce
, pos
);
598 error(_("path '%s' is unmerged"), ce
->name
);
600 pos
= skip_same_name(ce
, pos
) - 1;
606 /* Now we are committed to check them out */
607 if (opts
->checkout_worktree
)
608 errs
|= checkout_worktree(opts
, new_branch_info
);
610 remove_marked_cache_entries(&the_index
, 1);
613 * Allow updating the index when checking out from the index.
614 * This is to save new stat info.
616 if (opts
->checkout_worktree
&& !opts
->checkout_index
&& !opts
->source_tree
)
619 checkout_index
= opts
->checkout_index
;
621 if (checkout_index
) {
622 if (write_locked_index(&the_index
, &lock_file
, COMMIT_LOCK
))
623 die(_("unable to write new index file"));
626 * NEEDSWORK: if --worktree is not specified, we
627 * should save stat info of checked out files in the
628 * index to avoid the next (potentially costly)
629 * refresh. But it's a bit tricker to do...
631 rollback_lock_file(&lock_file
);
634 read_ref_full("HEAD", 0, &rev
, NULL
);
635 head
= lookup_commit_reference_gently(the_repository
, &rev
, 1);
637 errs
|= post_checkout_hook(head
, head
, 0);
641 static void show_local_changes(struct object
*head
,
642 const struct diff_options
*opts
)
645 /* I think we want full paths, even if we're in a subdirectory. */
646 repo_init_revisions(the_repository
, &rev
, NULL
);
647 rev
.diffopt
.flags
= opts
->flags
;
648 rev
.diffopt
.output_format
|= DIFF_FORMAT_NAME_STATUS
;
649 rev
.diffopt
.flags
.recursive
= 1;
650 diff_setup_done(&rev
.diffopt
);
651 add_pending_object(&rev
, head
, NULL
);
652 run_diff_index(&rev
, 0);
653 release_revisions(&rev
);
656 static void describe_detached_head(const char *msg
, struct commit
*commit
)
658 struct strbuf sb
= STRBUF_INIT
;
660 if (!parse_commit(commit
))
661 pp_commit_easy(CMIT_FMT_ONELINE
, commit
, &sb
);
662 if (print_sha1_ellipsis()) {
663 fprintf(stderr
, "%s %s... %s\n", msg
,
664 find_unique_abbrev(&commit
->object
.oid
, DEFAULT_ABBREV
), sb
.buf
);
666 fprintf(stderr
, "%s %s %s\n", msg
,
667 find_unique_abbrev(&commit
->object
.oid
, DEFAULT_ABBREV
), sb
.buf
);
672 static int reset_tree(struct tree
*tree
, const struct checkout_opts
*o
,
673 int worktree
, int *writeout_error
,
674 struct branch_info
*info
)
676 struct unpack_trees_options opts
;
677 struct tree_desc tree_desc
;
679 memset(&opts
, 0, sizeof(opts
));
681 opts
.update
= worktree
;
682 opts
.skip_unmerged
= !worktree
;
683 opts
.reset
= o
->force
? UNPACK_RESET_OVERWRITE_UNTRACKED
:
684 UNPACK_RESET_PROTECT_UNTRACKED
;
685 opts
.preserve_ignored
= (!o
->force
&& !o
->overwrite_ignore
);
687 opts
.fn
= oneway_merge
;
688 opts
.verbose_update
= o
->show_progress
;
689 opts
.src_index
= &the_index
;
690 opts
.dst_index
= &the_index
;
691 init_checkout_metadata(&opts
.meta
, info
->refname
,
692 info
->commit
? &info
->commit
->object
.oid
: null_oid(),
695 init_tree_desc(&tree_desc
, tree
->buffer
, tree
->size
);
696 switch (unpack_trees(1, &tree_desc
, &opts
)) {
700 * We return 0 nevertheless, as the index is all right
701 * and more importantly we have made best efforts to
702 * update paths in the work tree, and we cannot revert
713 static void setup_branch_path(struct branch_info
*branch
)
715 struct strbuf buf
= STRBUF_INIT
;
718 * If this is a ref, resolve it; otherwise, look up the OID for our
719 * expression. Failure here is okay.
721 if (!dwim_ref(branch
->name
, strlen(branch
->name
), &branch
->oid
, &branch
->refname
, 0))
722 repo_get_oid_committish(the_repository
, branch
->name
, &branch
->oid
);
724 strbuf_branchname(&buf
, branch
->name
, INTERPRET_BRANCH_LOCAL
);
725 if (strcmp(buf
.buf
, branch
->name
)) {
727 branch
->name
= xstrdup(buf
.buf
);
729 strbuf_splice(&buf
, 0, 0, "refs/heads/", 11);
731 branch
->path
= strbuf_detach(&buf
, NULL
);
734 static void init_topts(struct unpack_trees_options
*topts
, int merge
,
735 int show_progress
, int overwrite_ignore
,
736 struct commit
*old_commit
)
738 memset(topts
, 0, sizeof(*topts
));
739 topts
->head_idx
= -1;
740 topts
->src_index
= &the_index
;
741 topts
->dst_index
= &the_index
;
743 setup_unpack_trees_porcelain(topts
, "checkout");
745 topts
->initial_checkout
= is_index_unborn(&the_index
);
748 topts
->quiet
= merge
&& old_commit
;
749 topts
->verbose_update
= show_progress
;
750 topts
->fn
= twoway_merge
;
751 topts
->preserve_ignored
= !overwrite_ignore
;
754 static int merge_working_tree(const struct checkout_opts
*opts
,
755 struct branch_info
*old_branch_info
,
756 struct branch_info
*new_branch_info
,
760 struct lock_file lock_file
= LOCK_INIT
;
761 struct tree
*new_tree
;
763 repo_hold_locked_index(the_repository
, &lock_file
, LOCK_DIE_ON_ERROR
);
764 if (repo_read_index_preload(the_repository
, NULL
, 0) < 0)
765 return error(_("index file corrupt"));
767 resolve_undo_clear_index(&the_index
);
768 if (opts
->new_orphan_branch
&& opts
->orphan_from_empty_tree
) {
769 if (new_branch_info
->commit
)
770 BUG("'switch --orphan' should never accept a commit as starting point");
771 new_tree
= parse_tree_indirect(the_hash_algo
->empty_tree
);
773 new_tree
= get_commit_tree(new_branch_info
->commit
);
774 if (opts
->discard_changes
) {
775 ret
= reset_tree(new_tree
, opts
, 1, writeout_error
, new_branch_info
);
779 struct tree_desc trees
[2];
781 struct unpack_trees_options topts
;
782 const struct object_id
*old_commit_oid
;
784 refresh_index(&the_index
, REFRESH_QUIET
, NULL
, NULL
, NULL
);
786 if (unmerged_index(&the_index
)) {
787 error(_("you need to resolve your current index first"));
791 /* 2-way merge to the new branch */
792 init_topts(&topts
, opts
->merge
, opts
->show_progress
,
793 opts
->overwrite_ignore
, old_branch_info
->commit
);
794 init_checkout_metadata(&topts
.meta
, new_branch_info
->refname
,
795 new_branch_info
->commit
?
796 &new_branch_info
->commit
->object
.oid
:
797 &new_branch_info
->oid
, NULL
);
799 old_commit_oid
= old_branch_info
->commit
?
800 &old_branch_info
->commit
->object
.oid
:
801 the_hash_algo
->empty_tree
;
802 tree
= parse_tree_indirect(old_commit_oid
);
804 die(_("unable to parse commit %s"),
805 oid_to_hex(old_commit_oid
));
807 init_tree_desc(&trees
[0], tree
->buffer
, tree
->size
);
808 parse_tree(new_tree
);
810 init_tree_desc(&trees
[1], tree
->buffer
, tree
->size
);
812 ret
= unpack_trees(2, trees
, &topts
);
813 clear_unpack_trees_porcelain(&topts
);
816 * Unpack couldn't do a trivial merge; either
817 * give up or do a real merge, depending on
818 * whether the merge flag was used.
821 struct tree
*old_tree
;
822 struct merge_options o
;
823 struct strbuf sb
= STRBUF_INIT
;
824 struct strbuf old_commit_shortname
= STRBUF_INIT
;
830 * Without old_branch_info->commit, the below is the same as
831 * the two-tree unpack we already tried and failed.
833 if (!old_branch_info
->commit
)
835 old_tree
= get_commit_tree(old_branch_info
->commit
);
837 if (repo_index_has_changes(the_repository
, old_tree
, &sb
))
838 die(_("cannot continue with staged changes in "
839 "the following files:\n%s"), sb
.buf
);
842 /* Do more real merge */
845 * We update the index fully, then write the
846 * tree from the index, then merge the new
847 * branch with the current tree, with the old
848 * branch as the base. Then we reset the index
849 * (but not the working tree) to the new
850 * branch, leaving the working tree as the
851 * merged version, but skipping unmerged
852 * entries in the index.
855 add_files_to_cache(NULL
, NULL
, 0);
856 init_merge_options(&o
, the_repository
);
858 work
= write_in_core_index_as_tree(the_repository
);
860 ret
= reset_tree(new_tree
,
862 writeout_error
, new_branch_info
);
865 o
.ancestor
= old_branch_info
->name
;
866 if (!old_branch_info
->name
) {
867 strbuf_add_unique_abbrev(&old_commit_shortname
,
868 &old_branch_info
->commit
->object
.oid
,
870 o
.ancestor
= old_commit_shortname
.buf
;
872 o
.branch1
= new_branch_info
->name
;
874 ret
= merge_trees(&o
,
880 ret
= reset_tree(new_tree
,
882 writeout_error
, new_branch_info
);
883 strbuf_release(&o
.obuf
);
884 strbuf_release(&old_commit_shortname
);
890 if (!cache_tree_fully_valid(the_index
.cache_tree
))
891 cache_tree_update(&the_index
, WRITE_TREE_SILENT
| WRITE_TREE_REPAIR
);
893 if (write_locked_index(&the_index
, &lock_file
, COMMIT_LOCK
))
894 die(_("unable to write new index file"));
896 if (!opts
->discard_changes
&& !opts
->quiet
&& new_branch_info
->commit
)
897 show_local_changes(&new_branch_info
->commit
->object
, &opts
->diff_options
);
902 static void report_tracking(struct branch_info
*new_branch_info
)
904 struct strbuf sb
= STRBUF_INIT
;
905 struct branch
*branch
= branch_get(new_branch_info
->name
);
907 if (!format_tracking_info(branch
, &sb
, AHEAD_BEHIND_FULL
))
909 fputs(sb
.buf
, stdout
);
913 static void update_refs_for_switch(const struct checkout_opts
*opts
,
914 struct branch_info
*old_branch_info
,
915 struct branch_info
*new_branch_info
)
917 struct strbuf msg
= STRBUF_INIT
;
918 const char *old_desc
, *reflog_msg
;
919 if (opts
->new_branch
) {
920 if (opts
->new_orphan_branch
) {
923 refname
= mkpathdup("refs/heads/%s", opts
->new_orphan_branch
);
924 if (opts
->new_branch_log
&&
925 !should_autocreate_reflog(refname
)) {
927 struct strbuf err
= STRBUF_INIT
;
929 ret
= safe_create_reflog(refname
, &err
);
931 fprintf(stderr
, _("Can not do reflog for '%s': %s\n"),
932 opts
->new_orphan_branch
, err
.buf
);
933 strbuf_release(&err
);
937 strbuf_release(&err
);
942 create_branch(the_repository
,
943 opts
->new_branch
, new_branch_info
->name
,
944 opts
->new_branch_force
? 1 : 0,
945 opts
->new_branch_force
? 1 : 0,
946 opts
->new_branch_log
,
950 free(new_branch_info
->name
);
951 free(new_branch_info
->refname
);
952 new_branch_info
->name
= xstrdup(opts
->new_branch
);
953 setup_branch_path(new_branch_info
);
956 old_desc
= old_branch_info
->name
;
957 if (!old_desc
&& old_branch_info
->commit
)
958 old_desc
= oid_to_hex(&old_branch_info
->commit
->object
.oid
);
960 reflog_msg
= getenv("GIT_REFLOG_ACTION");
962 strbuf_addf(&msg
, "checkout: moving from %s to %s",
963 old_desc
? old_desc
: "(invalid)", new_branch_info
->name
);
965 strbuf_insertstr(&msg
, 0, reflog_msg
);
967 if (!strcmp(new_branch_info
->name
, "HEAD") && !new_branch_info
->path
&& !opts
->force_detach
) {
969 } else if (opts
->force_detach
|| !new_branch_info
->path
) { /* No longer on any branch. */
970 update_ref(msg
.buf
, "HEAD", &new_branch_info
->commit
->object
.oid
, NULL
,
971 REF_NO_DEREF
, UPDATE_REFS_DIE_ON_ERR
);
973 if (old_branch_info
->path
&&
974 advice_enabled(ADVICE_DETACHED_HEAD
) && !opts
->force_detach
)
975 detach_advice(new_branch_info
->name
);
976 describe_detached_head(_("HEAD is now at"), new_branch_info
->commit
);
978 } else if (new_branch_info
->path
) { /* Switch branches. */
979 if (create_symref("HEAD", new_branch_info
->path
, msg
.buf
) < 0)
980 die(_("unable to update HEAD"));
982 if (old_branch_info
->path
&& !strcmp(new_branch_info
->path
, old_branch_info
->path
)) {
983 if (opts
->new_branch_force
)
984 fprintf(stderr
, _("Reset branch '%s'\n"),
985 new_branch_info
->name
);
987 fprintf(stderr
, _("Already on '%s'\n"),
988 new_branch_info
->name
);
989 } else if (opts
->new_branch
) {
990 if (opts
->branch_exists
)
991 fprintf(stderr
, _("Switched to and reset branch '%s'\n"), new_branch_info
->name
);
993 fprintf(stderr
, _("Switched to a new branch '%s'\n"), new_branch_info
->name
);
995 fprintf(stderr
, _("Switched to branch '%s'\n"),
996 new_branch_info
->name
);
999 if (old_branch_info
->path
&& old_branch_info
->name
) {
1000 if (!ref_exists(old_branch_info
->path
) && reflog_exists(old_branch_info
->path
))
1001 delete_reflog(old_branch_info
->path
);
1004 remove_branch_state(the_repository
, !opts
->quiet
);
1005 strbuf_release(&msg
);
1007 (new_branch_info
->path
|| (!opts
->force_detach
&& !strcmp(new_branch_info
->name
, "HEAD"))))
1008 report_tracking(new_branch_info
);
1011 static int add_pending_uninteresting_ref(const char *refname
,
1012 const struct object_id
*oid
,
1013 int flags UNUSED
, void *cb_data
)
1015 add_pending_oid(cb_data
, refname
, oid
, UNINTERESTING
);
1019 static void describe_one_orphan(struct strbuf
*sb
, struct commit
*commit
)
1021 strbuf_addstr(sb
, " ");
1022 strbuf_add_unique_abbrev(sb
, &commit
->object
.oid
, DEFAULT_ABBREV
);
1023 strbuf_addch(sb
, ' ');
1024 if (!parse_commit(commit
))
1025 pp_commit_easy(CMIT_FMT_ONELINE
, commit
, sb
);
1026 strbuf_addch(sb
, '\n');
1029 #define ORPHAN_CUTOFF 4
1030 static void suggest_reattach(struct commit
*commit
, struct rev_info
*revs
)
1032 struct commit
*c
, *last
= NULL
;
1033 struct strbuf sb
= STRBUF_INIT
;
1035 while ((c
= get_revision(revs
)) != NULL
) {
1036 if (lost
< ORPHAN_CUTOFF
)
1037 describe_one_orphan(&sb
, c
);
1041 if (ORPHAN_CUTOFF
< lost
) {
1042 int more
= lost
- ORPHAN_CUTOFF
;
1044 describe_one_orphan(&sb
, last
);
1046 strbuf_addf(&sb
, _(" ... and %d more.\n"), more
);
1051 /* The singular version */
1052 "Warning: you are leaving %d commit behind, "
1053 "not connected to\n"
1054 "any of your branches:\n\n"
1056 /* The plural version */
1057 "Warning: you are leaving %d commits behind, "
1058 "not connected to\n"
1059 "any of your branches:\n\n"
1061 /* Give ngettext() the count */
1065 strbuf_release(&sb
);
1067 if (advice_enabled(ADVICE_DETACHED_HEAD
))
1070 /* The singular version */
1071 "If you want to keep it by creating a new branch, "
1072 "this may be a good time\nto do so with:\n\n"
1073 " git branch <new-branch-name> %s\n\n",
1074 /* The plural version */
1075 "If you want to keep them by creating a new branch, "
1076 "this may be a good time\nto do so with:\n\n"
1077 " git branch <new-branch-name> %s\n\n",
1078 /* Give ngettext() the count */
1080 find_unique_abbrev(&commit
->object
.oid
, DEFAULT_ABBREV
));
1084 * We are about to leave commit that was at the tip of a detached
1085 * HEAD. If it is not reachable from any ref, this is the last chance
1086 * for the user to do so without resorting to reflog.
1088 static void orphaned_commit_warning(struct commit
*old_commit
, struct commit
*new_commit
)
1090 struct rev_info revs
;
1091 struct object
*object
= &old_commit
->object
;
1093 repo_init_revisions(the_repository
, &revs
, NULL
);
1094 setup_revisions(0, NULL
, &revs
, NULL
);
1096 object
->flags
&= ~UNINTERESTING
;
1097 add_pending_object(&revs
, object
, oid_to_hex(&object
->oid
));
1099 for_each_ref(add_pending_uninteresting_ref
, &revs
);
1101 add_pending_oid(&revs
, "HEAD",
1102 &new_commit
->object
.oid
,
1105 if (prepare_revision_walk(&revs
))
1106 die(_("internal error in revision walk"));
1107 if (!(old_commit
->object
.flags
& UNINTERESTING
))
1108 suggest_reattach(old_commit
, &revs
);
1110 describe_detached_head(_("Previous HEAD position was"), old_commit
);
1112 /* Clean up objects used, as they will be reused. */
1113 repo_clear_commit_marks(the_repository
, ALL_REV_FLAGS
);
1114 release_revisions(&revs
);
1117 static int switch_branches(const struct checkout_opts
*opts
,
1118 struct branch_info
*new_branch_info
)
1121 struct branch_info old_branch_info
= { 0 };
1122 struct object_id rev
;
1123 int flag
, writeout_error
= 0;
1126 trace2_cmd_mode("branch");
1128 memset(&old_branch_info
, 0, sizeof(old_branch_info
));
1129 old_branch_info
.path
= resolve_refdup("HEAD", 0, &rev
, &flag
);
1130 if (old_branch_info
.path
)
1131 old_branch_info
.commit
= lookup_commit_reference_gently(the_repository
, &rev
, 1);
1132 if (!(flag
& REF_ISSYMREF
))
1133 FREE_AND_NULL(old_branch_info
.path
);
1135 if (old_branch_info
.path
) {
1136 const char *const prefix
= "refs/heads/";
1138 if (skip_prefix(old_branch_info
.path
, prefix
, &p
))
1139 old_branch_info
.name
= xstrdup(p
);
1142 if (opts
->new_orphan_branch
&& opts
->orphan_from_empty_tree
) {
1143 if (new_branch_info
->name
)
1144 BUG("'switch --orphan' should never accept a commit as starting point");
1145 new_branch_info
->commit
= NULL
;
1146 new_branch_info
->name
= xstrdup("(empty)");
1150 if (!new_branch_info
->name
) {
1151 new_branch_info
->name
= xstrdup("HEAD");
1152 new_branch_info
->commit
= old_branch_info
.commit
;
1153 if (!new_branch_info
->commit
)
1154 die(_("You are on a branch yet to be born"));
1155 parse_commit_or_die(new_branch_info
->commit
);
1157 if (opts
->only_merge_on_switching_branches
)
1162 ret
= merge_working_tree(opts
, &old_branch_info
, new_branch_info
, &writeout_error
);
1164 branch_info_release(&old_branch_info
);
1169 if (!opts
->quiet
&& !old_branch_info
.path
&& old_branch_info
.commit
&& new_branch_info
->commit
!= old_branch_info
.commit
)
1170 orphaned_commit_warning(old_branch_info
.commit
, new_branch_info
->commit
);
1172 update_refs_for_switch(opts
, &old_branch_info
, new_branch_info
);
1174 ret
= post_checkout_hook(old_branch_info
.commit
, new_branch_info
->commit
, 1);
1175 branch_info_release(&old_branch_info
);
1177 return ret
|| writeout_error
;
1180 static int git_checkout_config(const char *var
, const char *value
, void *cb
)
1182 struct checkout_opts
*opts
= cb
;
1184 if (!strcmp(var
, "diff.ignoresubmodules")) {
1185 handle_ignore_submodules_arg(&opts
->diff_options
, value
);
1188 if (!strcmp(var
, "checkout.guess")) {
1189 opts
->dwim_new_local_branch
= git_config_bool(var
, value
);
1193 if (starts_with(var
, "submodule."))
1194 return git_default_submodule_config(var
, value
, NULL
);
1196 return git_xmerge_config(var
, value
, NULL
);
1199 static void setup_new_branch_info_and_source_tree(
1200 struct branch_info
*new_branch_info
,
1201 struct checkout_opts
*opts
,
1202 struct object_id
*rev
,
1205 struct tree
**source_tree
= &opts
->source_tree
;
1206 struct object_id branch_rev
;
1208 new_branch_info
->name
= xstrdup(arg
);
1209 setup_branch_path(new_branch_info
);
1211 if (!check_refname_format(new_branch_info
->path
, 0) &&
1212 !read_ref(new_branch_info
->path
, &branch_rev
))
1213 oidcpy(rev
, &branch_rev
);
1215 /* not an existing branch */
1216 FREE_AND_NULL(new_branch_info
->path
);
1218 new_branch_info
->commit
= lookup_commit_reference_gently(the_repository
, rev
, 1);
1219 if (!new_branch_info
->commit
) {
1221 *source_tree
= parse_tree_indirect(rev
);
1223 parse_commit_or_die(new_branch_info
->commit
);
1224 *source_tree
= get_commit_tree(new_branch_info
->commit
);
1228 static const char *parse_remote_branch(const char *arg
,
1229 struct object_id
*rev
,
1230 int could_be_checkout_paths
)
1232 int num_matches
= 0;
1233 const char *remote
= unique_tracking_name(arg
, rev
, &num_matches
);
1235 if (remote
&& could_be_checkout_paths
) {
1236 die(_("'%s' could be both a local file and a tracking branch.\n"
1237 "Please use -- (and optionally --no-guess) to disambiguate"),
1241 if (!remote
&& num_matches
> 1) {
1242 if (advice_enabled(ADVICE_CHECKOUT_AMBIGUOUS_REMOTE_BRANCH_NAME
)) {
1243 advise(_("If you meant to check out a remote tracking branch on, e.g. 'origin',\n"
1244 "you can do so by fully qualifying the name with the --track option:\n"
1246 " git checkout --track origin/<name>\n"
1248 "If you'd like to always have checkouts of an ambiguous <name> prefer\n"
1249 "one remote, e.g. the 'origin' remote, consider setting\n"
1250 "checkout.defaultRemote=origin in your config."));
1253 die(_("'%s' matched multiple (%d) remote tracking branches"),
1260 static int parse_branchname_arg(int argc
, const char **argv
,
1261 int dwim_new_local_branch_ok
,
1262 struct branch_info
*new_branch_info
,
1263 struct checkout_opts
*opts
,
1264 struct object_id
*rev
)
1266 const char **new_branch
= &opts
->new_branch
;
1270 int has_dash_dash
= 0;
1274 * case 1: git checkout <ref> -- [<paths>]
1276 * <ref> must be a valid tree, everything after the '--' must be
1279 * case 2: git checkout -- [<paths>]
1281 * everything after the '--' must be paths.
1283 * case 3: git checkout <something> [--]
1285 * (a) If <something> is a commit, that is to
1286 * switch to the branch or detach HEAD at it. As a special case,
1287 * if <something> is A...B (missing A or B means HEAD but you can
1288 * omit at most one side), and if there is a unique merge base
1289 * between A and B, A...B names that merge base.
1291 * (b) If <something> is _not_ a commit, either "--" is present
1292 * or <something> is not a path, no -t or -b was given,
1293 * and there is a tracking branch whose name is <something>
1294 * in one and only one remote (or if the branch exists on the
1295 * remote named in checkout.defaultRemote), then this is a
1296 * short-hand to fork local <something> from that
1297 * remote-tracking branch.
1299 * (c) Otherwise, if "--" is present, treat it like case (1).
1302 * - if it's a reference, treat it like case (1)
1303 * - else if it's a path, treat it like case (2)
1306 * case 4: git checkout <something> <paths>
1308 * The first argument must not be ambiguous.
1309 * - If it's *only* a reference, treat it like case (1).
1310 * - If it's only a path, treat it like case (2).
1317 if (!opts
->accept_pathspec
) {
1319 die(_("only one reference expected"));
1320 has_dash_dash
= 1; /* helps disambiguate */
1325 for (i
= 0; i
< argc
; i
++) {
1326 if (opts
->accept_pathspec
&& !strcmp(argv
[i
], "--")) {
1331 if (dash_dash_pos
== 0)
1332 return 1; /* case (2) */
1333 else if (dash_dash_pos
== 1)
1334 has_dash_dash
= 1; /* case (3) or (1) */
1335 else if (dash_dash_pos
>= 2)
1336 die(_("only one reference expected, %d given."), dash_dash_pos
);
1337 opts
->count_checkout_paths
= !opts
->quiet
&& !has_dash_dash
;
1339 if (!strcmp(arg
, "-"))
1342 if (get_oid_mb(arg
, rev
)) {
1344 * Either case (3) or (4), with <something> not being
1345 * a commit, or an attempt to use case (1) with an
1348 * It's likely an error, but we need to find out if
1349 * we should auto-create the branch, case (3).(b).
1351 int recover_with_dwim
= dwim_new_local_branch_ok
;
1353 int could_be_checkout_paths
= !has_dash_dash
&&
1354 check_filename(opts
->prefix
, arg
);
1356 if (!has_dash_dash
&& !no_wildcard(arg
))
1357 recover_with_dwim
= 0;
1360 * Accept "git checkout foo", "git checkout foo --"
1361 * and "git switch foo" as candidates for dwim.
1363 if (!(argc
== 1 && !has_dash_dash
) &&
1364 !(argc
== 2 && has_dash_dash
) &&
1365 opts
->accept_pathspec
)
1366 recover_with_dwim
= 0;
1368 if (recover_with_dwim
) {
1369 const char *remote
= parse_remote_branch(arg
, rev
,
1370 could_be_checkout_paths
);
1374 /* DWIMmed to create local branch, case (3).(b) */
1376 recover_with_dwim
= 0;
1380 if (!recover_with_dwim
) {
1382 die(_("invalid reference: %s"), arg
);
1387 /* we can't end up being in (2) anymore, eat the argument */
1392 setup_new_branch_info_and_source_tree(new_branch_info
, opts
, rev
, arg
);
1394 if (!opts
->source_tree
) /* case (1): want a tree */
1395 die(_("reference is not a tree: %s"), arg
);
1397 if (!has_dash_dash
) { /* case (3).(d) -> (1) */
1399 * Do not complain the most common case
1400 * git checkout branch
1401 * even if there happen to be a file called 'branch';
1402 * it would be extremely annoying.
1405 verify_non_filename(opts
->prefix
, arg
);
1406 } else if (opts
->accept_pathspec
) {
1415 static int switch_unborn_to_new_branch(const struct checkout_opts
*opts
)
1418 struct strbuf branch_ref
= STRBUF_INIT
;
1420 trace2_cmd_mode("unborn");
1422 if (!opts
->new_branch
)
1423 die(_("You are on a branch yet to be born"));
1424 strbuf_addf(&branch_ref
, "refs/heads/%s", opts
->new_branch
);
1425 status
= create_symref("HEAD", branch_ref
.buf
, "checkout -b");
1426 strbuf_release(&branch_ref
);
1428 fprintf(stderr
, _("Switched to a new branch '%s'\n"),
1433 static void die_expecting_a_branch(const struct branch_info
*branch_info
)
1435 struct object_id oid
;
1439 if (dwim_ref(branch_info
->name
, strlen(branch_info
->name
), &oid
, &to_free
, 0) == 1) {
1440 const char *ref
= to_free
;
1442 if (skip_prefix(ref
, "refs/tags/", &ref
))
1443 code
= die_message(_("a branch is expected, got tag '%s'"), ref
);
1444 else if (skip_prefix(ref
, "refs/remotes/", &ref
))
1445 code
= die_message(_("a branch is expected, got remote branch '%s'"), ref
);
1447 code
= die_message(_("a branch is expected, got '%s'"), ref
);
1449 else if (branch_info
->commit
)
1450 code
= die_message(_("a branch is expected, got commit '%s'"), branch_info
->name
);
1453 * This case should never happen because we already die() on
1454 * non-commit, but just in case.
1456 code
= die_message(_("a branch is expected, got '%s'"), branch_info
->name
);
1458 if (advice_enabled(ADVICE_SUGGEST_DETACHING_HEAD
))
1459 advise(_("If you want to detach HEAD at the commit, try again with the --detach option."));
1464 static void die_if_some_operation_in_progress(void)
1466 struct wt_status_state state
;
1468 memset(&state
, 0, sizeof(state
));
1469 wt_status_get_state(the_repository
, &state
, 0);
1471 if (state
.merge_in_progress
)
1472 die(_("cannot switch branch while merging\n"
1473 "Consider \"git merge --quit\" "
1474 "or \"git worktree add\"."));
1475 if (state
.am_in_progress
)
1476 die(_("cannot switch branch in the middle of an am session\n"
1477 "Consider \"git am --quit\" "
1478 "or \"git worktree add\"."));
1479 if (state
.rebase_interactive_in_progress
|| state
.rebase_in_progress
)
1480 die(_("cannot switch branch while rebasing\n"
1481 "Consider \"git rebase --quit\" "
1482 "or \"git worktree add\"."));
1483 if (state
.cherry_pick_in_progress
)
1484 die(_("cannot switch branch while cherry-picking\n"
1485 "Consider \"git cherry-pick --quit\" "
1486 "or \"git worktree add\"."));
1487 if (state
.revert_in_progress
)
1488 die(_("cannot switch branch while reverting\n"
1489 "Consider \"git revert --quit\" "
1490 "or \"git worktree add\"."));
1491 if (state
.bisect_in_progress
)
1492 warning(_("you are switching branch while bisecting"));
1494 wt_status_state_free_buffers(&state
);
1497 static int checkout_branch(struct checkout_opts
*opts
,
1498 struct branch_info
*new_branch_info
)
1500 if (opts
->pathspec
.nr
)
1501 die(_("paths cannot be used with switching branches"));
1503 if (opts
->patch_mode
)
1504 die(_("'%s' cannot be used with switching branches"),
1507 if (opts
->overlay_mode
!= -1)
1508 die(_("'%s' cannot be used with switching branches"),
1511 if (opts
->writeout_stage
)
1512 die(_("'%s' cannot be used with switching branches"),
1515 if (opts
->force
&& opts
->merge
)
1516 die(_("'%s' cannot be used with '%s'"), "-f", "-m");
1518 if (opts
->discard_changes
&& opts
->merge
)
1519 die(_("'%s' cannot be used with '%s'"), "--discard-changes", "--merge");
1521 if (opts
->force_detach
&& opts
->new_branch
)
1522 die(_("'%s' cannot be used with '%s'"),
1523 "--detach", "-b/-B/--orphan");
1525 if (opts
->new_orphan_branch
) {
1526 if (opts
->track
!= BRANCH_TRACK_UNSPECIFIED
)
1527 die(_("'%s' cannot be used with '%s'"), "--orphan", "-t");
1528 if (opts
->orphan_from_empty_tree
&& new_branch_info
->name
)
1529 die(_("'%s' cannot take <start-point>"), "--orphan");
1530 } else if (opts
->force_detach
) {
1531 if (opts
->track
!= BRANCH_TRACK_UNSPECIFIED
)
1532 die(_("'%s' cannot be used with '%s'"), "--detach", "-t");
1533 } else if (opts
->track
== BRANCH_TRACK_UNSPECIFIED
)
1534 opts
->track
= git_branch_track
;
1536 if (new_branch_info
->name
&& !new_branch_info
->commit
)
1537 die(_("Cannot switch branch to a non-commit '%s'"),
1538 new_branch_info
->name
);
1540 if (!opts
->switch_branch_doing_nothing_is_ok
&&
1541 !new_branch_info
->name
&&
1542 !opts
->new_branch
&&
1543 !opts
->force_detach
)
1544 die(_("missing branch or commit argument"));
1546 if (!opts
->implicit_detach
&&
1547 !opts
->force_detach
&&
1548 !opts
->new_branch
&&
1549 !opts
->new_branch_force
&&
1550 new_branch_info
->name
&&
1551 !new_branch_info
->path
)
1552 die_expecting_a_branch(new_branch_info
);
1554 if (!opts
->can_switch_when_in_progress
)
1555 die_if_some_operation_in_progress();
1557 if (new_branch_info
->path
&& !opts
->force_detach
&& !opts
->new_branch
&&
1558 !opts
->ignore_other_worktrees
) {
1560 char *head_ref
= resolve_refdup("HEAD", 0, NULL
, &flag
);
1562 (!(flag
& REF_ISSYMREF
) || strcmp(head_ref
, new_branch_info
->path
)))
1563 die_if_checked_out(new_branch_info
->path
, 1);
1567 if (!new_branch_info
->commit
&& opts
->new_branch
) {
1568 struct object_id rev
;
1571 if (!read_ref_full("HEAD", 0, &rev
, &flag
) &&
1572 (flag
& REF_ISSYMREF
) && is_null_oid(&rev
))
1573 return switch_unborn_to_new_branch(opts
);
1575 return switch_branches(opts
, new_branch_info
);
1578 static struct option
*add_common_options(struct checkout_opts
*opts
,
1579 struct option
*prevopts
)
1581 struct option options
[] = {
1582 OPT__QUIET(&opts
->quiet
, N_("suppress progress reporting")),
1583 OPT_CALLBACK_F(0, "recurse-submodules", NULL
,
1584 "checkout", "control recursive updating of submodules",
1585 PARSE_OPT_OPTARG
, option_parse_recurse_submodules_worktree_updater
),
1586 OPT_BOOL(0, "progress", &opts
->show_progress
, N_("force progress reporting")),
1587 OPT_BOOL('m', "merge", &opts
->merge
, N_("perform a 3-way merge with the new branch")),
1588 OPT_STRING(0, "conflict", &opts
->conflict_style
, N_("style"),
1589 N_("conflict style (merge, diff3, or zdiff3)")),
1592 struct option
*newopts
= parse_options_concat(prevopts
, options
);
1597 static struct option
*add_common_switch_branch_options(
1598 struct checkout_opts
*opts
, struct option
*prevopts
)
1600 struct option options
[] = {
1601 OPT_BOOL('d', "detach", &opts
->force_detach
, N_("detach HEAD at named commit")),
1602 OPT_CALLBACK_F('t', "track", &opts
->track
, "(direct|inherit)",
1603 N_("set branch tracking configuration"),
1605 parse_opt_tracking_mode
),
1606 OPT__FORCE(&opts
->force
, N_("force checkout (throw away local modifications)"),
1607 PARSE_OPT_NOCOMPLETE
),
1608 OPT_STRING(0, "orphan", &opts
->new_orphan_branch
, N_("new-branch"), N_("new unparented branch")),
1609 OPT_BOOL_F(0, "overwrite-ignore", &opts
->overwrite_ignore
,
1610 N_("update ignored files (default)"),
1611 PARSE_OPT_NOCOMPLETE
),
1612 OPT_BOOL(0, "ignore-other-worktrees", &opts
->ignore_other_worktrees
,
1613 N_("do not check if another worktree is holding the given ref")),
1616 struct option
*newopts
= parse_options_concat(prevopts
, options
);
1621 static struct option
*add_checkout_path_options(struct checkout_opts
*opts
,
1622 struct option
*prevopts
)
1624 struct option options
[] = {
1625 OPT_SET_INT_F('2', "ours", &opts
->writeout_stage
,
1626 N_("checkout our version for unmerged files"),
1627 2, PARSE_OPT_NONEG
),
1628 OPT_SET_INT_F('3', "theirs", &opts
->writeout_stage
,
1629 N_("checkout their version for unmerged files"),
1630 3, PARSE_OPT_NONEG
),
1631 OPT_BOOL('p', "patch", &opts
->patch_mode
, N_("select hunks interactively")),
1632 OPT_BOOL(0, "ignore-skip-worktree-bits", &opts
->ignore_skipworktree
,
1633 N_("do not limit pathspecs to sparse entries only")),
1634 OPT_PATHSPEC_FROM_FILE(&opts
->pathspec_from_file
),
1635 OPT_PATHSPEC_FILE_NUL(&opts
->pathspec_file_nul
),
1638 struct option
*newopts
= parse_options_concat(prevopts
, options
);
1643 /* create-branch option (either b or c) */
1644 static char cb_option
= 'b';
1646 static int checkout_main(int argc
, const char **argv
, const char *prefix
,
1647 struct checkout_opts
*opts
, struct option
*options
,
1648 const char * const usagestr
[],
1649 struct branch_info
*new_branch_info
)
1651 int parseopt_flags
= 0;
1653 opts
->overwrite_ignore
= 1;
1654 opts
->prefix
= prefix
;
1655 opts
->show_progress
= -1;
1657 git_config(git_checkout_config
, opts
);
1658 if (the_repository
->gitdir
) {
1659 prepare_repo_settings(the_repository
);
1660 the_repository
->settings
.command_requires_full_index
= 0;
1663 opts
->track
= BRANCH_TRACK_UNSPECIFIED
;
1665 if (!opts
->accept_pathspec
&& !opts
->accept_ref
)
1666 BUG("make up your mind, you need to take _something_");
1667 if (opts
->accept_pathspec
&& opts
->accept_ref
)
1668 parseopt_flags
= PARSE_OPT_KEEP_DASHDASH
;
1670 argc
= parse_options(argc
, argv
, prefix
, options
,
1671 usagestr
, parseopt_flags
);
1673 if (opts
->show_progress
< 0) {
1675 opts
->show_progress
= 0;
1677 opts
->show_progress
= isatty(2);
1680 if (opts
->conflict_style
) {
1681 opts
->merge
= 1; /* implied */
1682 git_xmerge_config("merge.conflictstyle", opts
->conflict_style
, NULL
);
1685 opts
->discard_changes
= 1;
1686 opts
->ignore_unmerged_opt
= "--force";
1687 opts
->ignore_unmerged
= 1;
1690 if ((!!opts
->new_branch
+ !!opts
->new_branch_force
+ !!opts
->new_orphan_branch
) > 1)
1691 die(_("options '-%c', '-%c', and '%s' cannot be used together"),
1692 cb_option
, toupper(cb_option
), "--orphan");
1694 if (opts
->overlay_mode
== 1 && opts
->patch_mode
)
1695 die(_("options '%s' and '%s' cannot be used together"), "-p", "--overlay");
1697 if (opts
->checkout_index
>= 0 || opts
->checkout_worktree
>= 0) {
1698 if (opts
->checkout_index
< 0)
1699 opts
->checkout_index
= 0;
1700 if (opts
->checkout_worktree
< 0)
1701 opts
->checkout_worktree
= 0;
1703 if (opts
->checkout_index
< 0)
1704 opts
->checkout_index
= -opts
->checkout_index
- 1;
1705 if (opts
->checkout_worktree
< 0)
1706 opts
->checkout_worktree
= -opts
->checkout_worktree
- 1;
1708 if (opts
->checkout_index
< 0 || opts
->checkout_worktree
< 0)
1709 BUG("these flags should be non-negative by now");
1711 * convenient shortcut: "git restore --staged [--worktree]" equals
1712 * "git restore --staged [--worktree] --source HEAD"
1714 if (!opts
->from_treeish
&& opts
->checkout_index
)
1715 opts
->from_treeish
= "HEAD";
1718 * From here on, new_branch will contain the branch to be checked out,
1719 * and new_branch_force and new_orphan_branch will tell us which one of
1720 * -b/-B/-c/-C/--orphan is being used.
1722 if (opts
->new_branch_force
)
1723 opts
->new_branch
= opts
->new_branch_force
;
1725 if (opts
->new_orphan_branch
)
1726 opts
->new_branch
= opts
->new_orphan_branch
;
1728 /* --track without -c/-C/-b/-B/--orphan should DWIM */
1729 if (opts
->track
!= BRANCH_TRACK_UNSPECIFIED
&& !opts
->new_branch
) {
1730 const char *argv0
= argv
[0];
1731 if (!argc
|| !strcmp(argv0
, "--"))
1732 die(_("--track needs a branch name"));
1733 skip_prefix(argv0
, "refs/", &argv0
);
1734 skip_prefix(argv0
, "remotes/", &argv0
);
1735 argv0
= strchr(argv0
, '/');
1736 if (!argv0
|| !argv0
[1])
1737 die(_("missing branch name; try -%c"), cb_option
);
1738 opts
->new_branch
= argv0
+ 1;
1742 * Extract branch name from command line arguments, so
1743 * all that is left is pathspecs.
1747 * 1) git checkout <tree> -- [<paths>]
1748 * 2) git checkout -- [<paths>]
1749 * 3) git checkout <something> [<paths>]
1751 * including "last branch" syntax and DWIM-ery for names of
1752 * remote branches, erroring out for invalid or ambiguous cases.
1754 if (argc
&& opts
->accept_ref
) {
1755 struct object_id rev
;
1757 !opts
->patch_mode
&&
1758 opts
->dwim_new_local_branch
&&
1759 opts
->track
== BRANCH_TRACK_UNSPECIFIED
&&
1761 int n
= parse_branchname_arg(argc
, argv
, dwim_ok
,
1762 new_branch_info
, opts
, &rev
);
1765 } else if (!opts
->accept_ref
&& opts
->from_treeish
) {
1766 struct object_id rev
;
1768 if (get_oid_mb(opts
->from_treeish
, &rev
))
1769 die(_("could not resolve %s"), opts
->from_treeish
);
1771 setup_new_branch_info_and_source_tree(new_branch_info
,
1773 opts
->from_treeish
);
1775 if (!opts
->source_tree
)
1776 die(_("reference is not a tree: %s"), opts
->from_treeish
);
1780 parse_pathspec(&opts
->pathspec
, 0,
1781 opts
->patch_mode
? PATHSPEC_PREFIX_ORIGIN
: 0,
1784 if (!opts
->pathspec
.nr
)
1785 die(_("invalid path specification"));
1788 * Try to give more helpful suggestion.
1789 * new_branch && argc > 1 will be caught later.
1791 if (opts
->new_branch
&& argc
== 1 && !new_branch_info
->commit
)
1792 die(_("'%s' is not a commit and a branch '%s' cannot be created from it"),
1793 argv
[0], opts
->new_branch
);
1795 if (opts
->force_detach
)
1796 die(_("git checkout: --detach does not take a path argument '%s'"),
1800 if (opts
->pathspec_from_file
) {
1801 if (opts
->pathspec
.nr
)
1802 die(_("'%s' and pathspec arguments cannot be used together"), "--pathspec-from-file");
1804 if (opts
->force_detach
)
1805 die(_("options '%s' and '%s' cannot be used together"), "--pathspec-from-file", "--detach");
1807 if (opts
->patch_mode
)
1808 die(_("options '%s' and '%s' cannot be used together"), "--pathspec-from-file", "--patch");
1810 parse_pathspec_file(&opts
->pathspec
, 0,
1812 prefix
, opts
->pathspec_from_file
, opts
->pathspec_file_nul
);
1813 } else if (opts
->pathspec_file_nul
) {
1814 die(_("the option '%s' requires '%s'"), "--pathspec-file-nul", "--pathspec-from-file");
1817 opts
->pathspec
.recursive
= 1;
1819 if (opts
->pathspec
.nr
) {
1820 if (1 < !!opts
->writeout_stage
+ !!opts
->force
+ !!opts
->merge
)
1821 die(_("git checkout: --ours/--theirs, --force and --merge are incompatible when\n"
1822 "checking out of the index."));
1824 if (opts
->accept_pathspec
&& !opts
->empty_pathspec_ok
&&
1825 !opts
->patch_mode
) /* patch mode is special */
1826 die(_("you must specify path(s) to restore"));
1829 if (opts
->new_branch
) {
1830 struct strbuf buf
= STRBUF_INIT
;
1832 if (opts
->new_branch_force
)
1833 opts
->branch_exists
= validate_branchname(opts
->new_branch
, &buf
);
1835 opts
->branch_exists
=
1836 validate_new_branchname(opts
->new_branch
, &buf
, 0);
1837 strbuf_release(&buf
);
1840 if (opts
->patch_mode
|| opts
->pathspec
.nr
)
1841 return checkout_paths(opts
, new_branch_info
);
1843 return checkout_branch(opts
, new_branch_info
);
1846 int cmd_checkout(int argc
, const char **argv
, const char *prefix
)
1848 struct checkout_opts opts
;
1849 struct option
*options
;
1850 struct option checkout_options
[] = {
1851 OPT_STRING('b', NULL
, &opts
.new_branch
, N_("branch"),
1852 N_("create and checkout a new branch")),
1853 OPT_STRING('B', NULL
, &opts
.new_branch_force
, N_("branch"),
1854 N_("create/reset and checkout a branch")),
1855 OPT_BOOL('l', NULL
, &opts
.new_branch_log
, N_("create reflog for new branch")),
1856 OPT_BOOL(0, "guess", &opts
.dwim_new_local_branch
,
1857 N_("second guess 'git checkout <no-such-branch>' (default)")),
1858 OPT_BOOL(0, "overlay", &opts
.overlay_mode
, N_("use overlay mode (default)")),
1862 struct branch_info new_branch_info
= { 0 };
1864 memset(&opts
, 0, sizeof(opts
));
1865 opts
.dwim_new_local_branch
= 1;
1866 opts
.switch_branch_doing_nothing_is_ok
= 1;
1867 opts
.only_merge_on_switching_branches
= 0;
1868 opts
.accept_ref
= 1;
1869 opts
.accept_pathspec
= 1;
1870 opts
.implicit_detach
= 1;
1871 opts
.can_switch_when_in_progress
= 1;
1872 opts
.orphan_from_empty_tree
= 0;
1873 opts
.empty_pathspec_ok
= 1;
1874 opts
.overlay_mode
= -1;
1875 opts
.checkout_index
= -2; /* default on */
1876 opts
.checkout_worktree
= -2; /* default on */
1878 if (argc
== 3 && !strcmp(argv
[1], "-b")) {
1880 * User ran 'git checkout -b <branch>' and expects
1881 * the same behavior as 'git switch -c <branch>'.
1883 opts
.switch_branch_doing_nothing_is_ok
= 0;
1884 opts
.only_merge_on_switching_branches
= 1;
1887 options
= parse_options_dup(checkout_options
);
1888 options
= add_common_options(&opts
, options
);
1889 options
= add_common_switch_branch_options(&opts
, options
);
1890 options
= add_checkout_path_options(&opts
, options
);
1892 ret
= checkout_main(argc
, argv
, prefix
, &opts
,
1893 options
, checkout_usage
, &new_branch_info
);
1894 branch_info_release(&new_branch_info
);
1895 clear_pathspec(&opts
.pathspec
);
1896 free(opts
.pathspec_from_file
);
1897 FREE_AND_NULL(options
);
1901 int cmd_switch(int argc
, const char **argv
, const char *prefix
)
1903 struct checkout_opts opts
;
1904 struct option
*options
= NULL
;
1905 struct option switch_options
[] = {
1906 OPT_STRING('c', "create", &opts
.new_branch
, N_("branch"),
1907 N_("create and switch to a new branch")),
1908 OPT_STRING('C', "force-create", &opts
.new_branch_force
, N_("branch"),
1909 N_("create/reset and switch to a branch")),
1910 OPT_BOOL(0, "guess", &opts
.dwim_new_local_branch
,
1911 N_("second guess 'git switch <no-such-branch>'")),
1912 OPT_BOOL(0, "discard-changes", &opts
.discard_changes
,
1913 N_("throw away local modifications")),
1917 struct branch_info new_branch_info
= { 0 };
1919 memset(&opts
, 0, sizeof(opts
));
1920 opts
.dwim_new_local_branch
= 1;
1921 opts
.accept_ref
= 1;
1922 opts
.accept_pathspec
= 0;
1923 opts
.switch_branch_doing_nothing_is_ok
= 0;
1924 opts
.only_merge_on_switching_branches
= 1;
1925 opts
.implicit_detach
= 0;
1926 opts
.can_switch_when_in_progress
= 0;
1927 opts
.orphan_from_empty_tree
= 1;
1928 opts
.overlay_mode
= -1;
1930 options
= parse_options_dup(switch_options
);
1931 options
= add_common_options(&opts
, options
);
1932 options
= add_common_switch_branch_options(&opts
, options
);
1936 ret
= checkout_main(argc
, argv
, prefix
, &opts
,
1937 options
, switch_branch_usage
, &new_branch_info
);
1938 branch_info_release(&new_branch_info
);
1939 FREE_AND_NULL(options
);
1943 int cmd_restore(int argc
, const char **argv
, const char *prefix
)
1945 struct checkout_opts opts
;
1946 struct option
*options
;
1947 struct option restore_options
[] = {
1948 OPT_STRING('s', "source", &opts
.from_treeish
, "<tree-ish>",
1949 N_("which tree-ish to checkout from")),
1950 OPT_BOOL('S', "staged", &opts
.checkout_index
,
1951 N_("restore the index")),
1952 OPT_BOOL('W', "worktree", &opts
.checkout_worktree
,
1953 N_("restore the working tree (default)")),
1954 OPT_BOOL(0, "ignore-unmerged", &opts
.ignore_unmerged
,
1955 N_("ignore unmerged entries")),
1956 OPT_BOOL(0, "overlay", &opts
.overlay_mode
, N_("use overlay mode")),
1960 struct branch_info new_branch_info
= { 0 };
1962 memset(&opts
, 0, sizeof(opts
));
1963 opts
.accept_ref
= 0;
1964 opts
.accept_pathspec
= 1;
1965 opts
.empty_pathspec_ok
= 0;
1966 opts
.overlay_mode
= 0;
1967 opts
.checkout_index
= -1; /* default off */
1968 opts
.checkout_worktree
= -2; /* default on */
1969 opts
.ignore_unmerged_opt
= "--ignore-unmerged";
1971 options
= parse_options_dup(restore_options
);
1972 options
= add_common_options(&opts
, options
);
1973 options
= add_checkout_path_options(&opts
, options
);
1975 ret
= checkout_main(argc
, argv
, prefix
, &opts
,
1976 options
, restore_usage
, &new_branch_info
);
1977 branch_info_release(&new_branch_info
);
1978 FREE_AND_NULL(options
);