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 #include "parallel-checkout.h"
32 static const char * const checkout_usage
[] = {
33 N_("git checkout [<options>] <branch>"),
34 N_("git checkout [<options>] [<branch>] -- <file>..."),
38 static const char * const switch_branch_usage
[] = {
39 N_("git switch [<options>] [<branch>]"),
43 static const char * const restore_usage
[] = {
44 N_("git restore [<options>] [--source=<branch>] <file>..."),
48 struct checkout_opts
{
57 int ignore_skipworktree
;
58 int ignore_other_worktrees
;
60 int count_checkout_paths
;
62 int dwim_new_local_branch
;
66 int switch_branch_doing_nothing_is_ok
;
67 int only_merge_on_switching_branches
;
68 int can_switch_when_in_progress
;
69 int orphan_from_empty_tree
;
70 int empty_pathspec_ok
;
72 int checkout_worktree
;
73 const char *ignore_unmerged_opt
;
75 int pathspec_file_nul
;
76 const char *pathspec_from_file
;
78 const char *new_branch
;
79 const char *new_branch_force
;
80 const char *new_orphan_branch
;
82 enum branch_track track
;
83 struct diff_options diff_options
;
88 struct pathspec pathspec
;
89 const char *from_treeish
;
90 struct tree
*source_tree
;
94 char *name
; /* The short name used */
95 char *path
; /* The full name of a real branch */
96 struct commit
*commit
; /* The named commit */
97 char *refname
; /* The full name of the ref being checked out. */
98 struct object_id oid
; /* The object ID of the commit being checked out. */
100 * if not null the branch is detached because it's already
101 * checked out in this checkout
106 static void branch_info_release(struct branch_info
*info
)
111 free(info
->checkout
);
114 static int post_checkout_hook(struct commit
*old_commit
, struct commit
*new_commit
,
117 return run_hook_le(NULL
, "post-checkout",
118 oid_to_hex(old_commit
? &old_commit
->object
.oid
: null_oid()),
119 oid_to_hex(new_commit
? &new_commit
->object
.oid
: null_oid()),
120 changed
? "1" : "0", NULL
);
121 /* "new_commit" can be NULL when checking out from the index before
126 static int update_some(const struct object_id
*oid
, struct strbuf
*base
,
127 const char *pathname
, unsigned mode
, void *context
)
130 struct cache_entry
*ce
;
134 return READ_TREE_RECURSIVE
;
136 len
= base
->len
+ strlen(pathname
);
137 ce
= make_empty_cache_entry(&the_index
, len
);
138 oidcpy(&ce
->oid
, oid
);
139 memcpy(ce
->name
, base
->buf
, base
->len
);
140 memcpy(ce
->name
+ base
->len
, pathname
, len
- base
->len
);
141 ce
->ce_flags
= create_ce_flags(0) | CE_UPDATE
;
142 ce
->ce_namelen
= len
;
143 ce
->ce_mode
= create_ce_mode(mode
);
146 * If the entry is the same as the current index, we can leave the old
147 * entry in place. Whether it is UPTODATE or not, checkout_entry will
148 * do the right thing.
150 pos
= cache_name_pos(ce
->name
, ce
->ce_namelen
);
152 struct cache_entry
*old
= active_cache
[pos
];
153 if (ce
->ce_mode
== old
->ce_mode
&&
154 !ce_intent_to_add(old
) &&
155 oideq(&ce
->oid
, &old
->oid
)) {
156 old
->ce_flags
|= CE_UPDATE
;
157 discard_cache_entry(ce
);
162 add_cache_entry(ce
, ADD_CACHE_OK_TO_ADD
| ADD_CACHE_OK_TO_REPLACE
);
166 static int read_tree_some(struct tree
*tree
, const struct pathspec
*pathspec
)
168 read_tree(the_repository
, tree
,
169 pathspec
, update_some
, NULL
);
171 /* update the index with the given tree's info
172 * for all args, expanding wildcards, and exit
173 * with any non-zero return code.
178 static int skip_same_name(const struct cache_entry
*ce
, int pos
)
180 while (++pos
< active_nr
&&
181 !strcmp(active_cache
[pos
]->name
, ce
->name
))
186 static int check_stage(int stage
, const struct cache_entry
*ce
, int pos
,
189 while (pos
< active_nr
&&
190 !strcmp(active_cache
[pos
]->name
, ce
->name
)) {
191 if (ce_stage(active_cache
[pos
]) == stage
)
198 return error(_("path '%s' does not have our version"), ce
->name
);
200 return error(_("path '%s' does not have their version"), ce
->name
);
203 static int check_stages(unsigned stages
, const struct cache_entry
*ce
, int pos
)
206 const char *name
= ce
->name
;
208 while (pos
< active_nr
) {
209 ce
= active_cache
[pos
];
210 if (strcmp(name
, ce
->name
))
212 seen
|= (1 << ce_stage(ce
));
215 if ((stages
& seen
) != stages
)
216 return error(_("path '%s' does not have all necessary versions"),
221 static int checkout_stage(int stage
, const struct cache_entry
*ce
, int pos
,
222 const struct checkout
*state
, int *nr_checkouts
,
225 while (pos
< active_nr
&&
226 !strcmp(active_cache
[pos
]->name
, ce
->name
)) {
227 if (ce_stage(active_cache
[pos
]) == stage
)
228 return checkout_entry(active_cache
[pos
], state
,
237 return error(_("path '%s' does not have our version"), ce
->name
);
239 return error(_("path '%s' does not have their version"), ce
->name
);
242 static int checkout_merged(int pos
, const struct checkout
*state
,
243 int *nr_checkouts
, struct mem_pool
*ce_mem_pool
)
245 struct cache_entry
*ce
= active_cache
[pos
];
246 const char *path
= ce
->name
;
247 mmfile_t ancestor
, ours
, theirs
;
249 struct object_id oid
;
250 mmbuffer_t result_buf
;
251 struct object_id threeway
[3];
253 struct ll_merge_options ll_opts
;
256 memset(threeway
, 0, sizeof(threeway
));
257 while (pos
< active_nr
) {
259 stage
= ce_stage(ce
);
260 if (!stage
|| strcmp(path
, ce
->name
))
262 oidcpy(&threeway
[stage
- 1], &ce
->oid
);
264 mode
= create_ce_mode(ce
->ce_mode
);
266 ce
= active_cache
[pos
];
268 if (is_null_oid(&threeway
[1]) || is_null_oid(&threeway
[2]))
269 return error(_("path '%s' does not have necessary versions"), path
);
271 read_mmblob(&ancestor
, &threeway
[0]);
272 read_mmblob(&ours
, &threeway
[1]);
273 read_mmblob(&theirs
, &threeway
[2]);
275 memset(&ll_opts
, 0, sizeof(ll_opts
));
276 git_config_get_bool("merge.renormalize", &renormalize
);
277 ll_opts
.renormalize
= renormalize
;
278 status
= ll_merge(&result_buf
, path
, &ancestor
, "base",
279 &ours
, "ours", &theirs
, "theirs",
280 state
->istate
, &ll_opts
);
284 if (status
< 0 || !result_buf
.ptr
) {
285 free(result_buf
.ptr
);
286 return error(_("path '%s': cannot merge"), path
);
291 * There is absolutely no reason to write this as a blob object
292 * and create a phony cache entry. This hack is primarily to get
293 * to the write_entry() machinery that massages the contents to
294 * work-tree format and writes out which only allows it for a
295 * cache entry. The code in write_entry() needs to be refactored
296 * to allow us to feed a <buffer, size, mode> instead of a cache
297 * entry. Such a refactoring would help merge_recursive as well
298 * (it also writes the merge result to the object database even
299 * when it may contain conflicts).
301 if (write_object_file(result_buf
.ptr
, result_buf
.size
, blob_type
, &oid
))
302 die(_("Unable to add merge result for '%s'"), path
);
303 free(result_buf
.ptr
);
304 ce
= make_transient_cache_entry(mode
, &oid
, path
, 2, ce_mem_pool
);
306 die(_("make_cache_entry failed for path '%s'"), path
);
307 status
= checkout_entry(ce
, state
, NULL
, nr_checkouts
);
311 static void mark_ce_for_checkout_overlay(struct cache_entry
*ce
,
313 const struct checkout_opts
*opts
)
315 ce
->ce_flags
&= ~CE_MATCHED
;
316 if (!opts
->ignore_skipworktree
&& ce_skip_worktree(ce
))
318 if (opts
->source_tree
&& !(ce
->ce_flags
& CE_UPDATE
))
320 * "git checkout tree-ish -- path", but this entry
321 * is in the original index but is not in tree-ish
322 * or does not match the pathspec; it will not be
323 * checked out to the working tree. We will not do
324 * anything to this entry at all.
328 * Either this entry came from the tree-ish we are
329 * checking the paths out of, or we are checking out
332 * If it comes from the tree-ish, we already know it
333 * matches the pathspec and could just stamp
334 * CE_MATCHED to it from update_some(). But we still
335 * need ps_matched and read_tree (and
336 * eventually tree_entry_interesting) cannot fill
337 * ps_matched yet. Once it can, we can avoid calling
338 * match_pathspec() for _all_ entries when
339 * opts->source_tree != NULL.
341 if (ce_path_match(&the_index
, ce
, &opts
->pathspec
, ps_matched
))
342 ce
->ce_flags
|= CE_MATCHED
;
345 static void mark_ce_for_checkout_no_overlay(struct cache_entry
*ce
,
347 const struct checkout_opts
*opts
)
349 ce
->ce_flags
&= ~CE_MATCHED
;
350 if (!opts
->ignore_skipworktree
&& ce_skip_worktree(ce
))
352 if (ce_path_match(&the_index
, ce
, &opts
->pathspec
, ps_matched
)) {
353 ce
->ce_flags
|= CE_MATCHED
;
354 if (opts
->source_tree
&& !(ce
->ce_flags
& CE_UPDATE
))
356 * In overlay mode, but the path is not in
357 * tree-ish, which means we should remove it
358 * from the index and the working tree.
360 ce
->ce_flags
|= CE_REMOVE
| CE_WT_REMOVE
;
364 static int checkout_worktree(const struct checkout_opts
*opts
,
365 const struct branch_info
*info
)
367 struct checkout state
= CHECKOUT_INIT
;
368 int nr_checkouts
= 0, nr_unmerged
= 0;
371 int pc_workers
, pc_threshold
;
372 struct mem_pool ce_mem_pool
;
375 state
.refresh_cache
= 1;
376 state
.istate
= &the_index
;
378 mem_pool_init(&ce_mem_pool
, 0);
379 get_parallel_checkout_configs(&pc_workers
, &pc_threshold
);
380 init_checkout_metadata(&state
.meta
, info
->refname
,
381 info
->commit
? &info
->commit
->object
.oid
: &info
->oid
,
384 enable_delayed_checkout(&state
);
387 init_parallel_checkout();
389 for (pos
= 0; pos
< active_nr
; pos
++) {
390 struct cache_entry
*ce
= active_cache
[pos
];
391 if (ce
->ce_flags
& CE_MATCHED
) {
393 errs
|= checkout_entry(ce
, &state
,
394 NULL
, &nr_checkouts
);
397 if (opts
->writeout_stage
)
398 errs
|= checkout_stage(opts
->writeout_stage
,
401 &nr_checkouts
, opts
->overlay_mode
);
402 else if (opts
->merge
)
403 errs
|= checkout_merged(pos
, &state
,
406 pos
= skip_same_name(ce
, pos
) - 1;
410 errs
|= run_parallel_checkout(&state
, pc_workers
, pc_threshold
,
412 mem_pool_discard(&ce_mem_pool
, should_validate_cache_entries());
413 remove_marked_cache_entries(&the_index
, 1);
414 remove_scheduled_dirs();
415 errs
|= finish_delayed_checkout(&state
, &nr_checkouts
, opts
->show_progress
);
417 if (opts
->count_checkout_paths
) {
419 fprintf_ln(stderr
, Q_("Recreated %d merge conflict",
420 "Recreated %d merge conflicts",
423 if (opts
->source_tree
)
424 fprintf_ln(stderr
, Q_("Updated %d path from %s",
425 "Updated %d paths from %s",
428 find_unique_abbrev(&opts
->source_tree
->object
.oid
,
430 else if (!nr_unmerged
|| nr_checkouts
)
431 fprintf_ln(stderr
, Q_("Updated %d path from the index",
432 "Updated %d paths from the index",
440 static int checkout_paths(const struct checkout_opts
*opts
,
441 const struct branch_info
*new_branch_info
)
444 static char *ps_matched
;
445 struct object_id rev
;
448 struct lock_file lock_file
= LOCK_INIT
;
451 trace2_cmd_mode(opts
->patch_mode
? "patch" : "path");
453 if (opts
->track
!= BRANCH_TRACK_UNSPECIFIED
)
454 die(_("'%s' cannot be used with updating paths"), "--track");
456 if (opts
->new_branch_log
)
457 die(_("'%s' cannot be used with updating paths"), "-l");
459 if (opts
->ignore_unmerged
&& opts
->patch_mode
)
460 die(_("'%s' cannot be used with updating paths"),
461 opts
->ignore_unmerged_opt
);
463 if (opts
->force_detach
)
464 die(_("'%s' cannot be used with updating paths"), "--detach");
466 if (opts
->merge
&& opts
->patch_mode
)
467 die(_("options '%s' and '%s' cannot be used together"), "--merge", "--patch");
469 if (opts
->ignore_unmerged
&& opts
->merge
)
470 die(_("options '%s' and '%s' cannot be used together"),
471 opts
->ignore_unmerged_opt
, "-m");
473 if (opts
->new_branch
)
474 die(_("Cannot update paths and switch to branch '%s' at the same time."),
477 if (!opts
->checkout_worktree
&& !opts
->checkout_index
)
478 die(_("neither '%s' or '%s' is specified"),
479 "--staged", "--worktree");
481 if (!opts
->checkout_worktree
&& !opts
->from_treeish
)
482 die(_("'%s' must be used when '%s' is not specified"),
483 "--worktree", "--source");
485 if (opts
->checkout_index
&& !opts
->checkout_worktree
&&
486 opts
->writeout_stage
)
487 die(_("'%s' or '%s' cannot be used with %s"),
488 "--ours", "--theirs", "--staged");
490 if (opts
->checkout_index
&& !opts
->checkout_worktree
&&
492 die(_("'%s' or '%s' cannot be used with %s"),
493 "--merge", "--conflict", "--staged");
495 if (opts
->patch_mode
) {
496 const char *patch_mode
;
497 const char *rev
= new_branch_info
->name
;
498 char rev_oid
[GIT_MAX_HEXSZ
+ 1];
501 * Since rev can be in the form of `<a>...<b>` (which is not
502 * recognized by diff-index), we will always replace the name
503 * with the hex of the commit (whether it's in `...` form or
504 * not) for the run_add_interactive() machinery to work
505 * properly. However, there is special logic for the HEAD case
506 * so we mustn't replace that. Also, when we were given a
507 * tree-object, new_branch_info->commit would be NULL, but we
508 * do not have to do any replacement, either.
510 if (rev
&& new_branch_info
->commit
&& strcmp(rev
, "HEAD"))
511 rev
= oid_to_hex_r(rev_oid
, &new_branch_info
->commit
->object
.oid
);
513 if (opts
->checkout_index
&& opts
->checkout_worktree
)
514 patch_mode
= "--patch=checkout";
515 else if (opts
->checkout_index
&& !opts
->checkout_worktree
)
516 patch_mode
= "--patch=reset";
517 else if (!opts
->checkout_index
&& opts
->checkout_worktree
)
518 patch_mode
= "--patch=worktree";
520 BUG("either flag must have been set, worktree=%d, index=%d",
521 opts
->checkout_worktree
, opts
->checkout_index
);
522 return run_add_interactive(rev
, patch_mode
, &opts
->pathspec
);
525 repo_hold_locked_index(the_repository
, &lock_file
, LOCK_DIE_ON_ERROR
);
526 if (read_cache_preload(&opts
->pathspec
) < 0)
527 return error(_("index file corrupt"));
529 if (opts
->source_tree
)
530 read_tree_some(opts
->source_tree
, &opts
->pathspec
);
532 ps_matched
= xcalloc(opts
->pathspec
.nr
, 1);
535 * Make sure all pathspecs participated in locating the paths
538 for (pos
= 0; pos
< active_nr
; pos
++)
539 if (opts
->overlay_mode
)
540 mark_ce_for_checkout_overlay(active_cache
[pos
],
544 mark_ce_for_checkout_no_overlay(active_cache
[pos
],
548 if (report_path_error(ps_matched
, &opts
->pathspec
)) {
554 /* "checkout -m path" to recreate conflicted state */
556 unmerge_marked_index(&the_index
);
558 /* Any unmerged paths? */
559 for (pos
= 0; pos
< active_nr
; pos
++) {
560 const struct cache_entry
*ce
= active_cache
[pos
];
561 if (ce
->ce_flags
& CE_MATCHED
) {
564 if (opts
->ignore_unmerged
) {
566 warning(_("path '%s' is unmerged"), ce
->name
);
567 } else if (opts
->writeout_stage
) {
568 errs
|= check_stage(opts
->writeout_stage
, ce
, pos
, opts
->overlay_mode
);
569 } else if (opts
->merge
) {
570 errs
|= check_stages((1<<2) | (1<<3), ce
, pos
);
573 error(_("path '%s' is unmerged"), ce
->name
);
575 pos
= skip_same_name(ce
, pos
) - 1;
581 /* Now we are committed to check them out */
582 if (opts
->checkout_worktree
)
583 errs
|= checkout_worktree(opts
, new_branch_info
);
585 remove_marked_cache_entries(&the_index
, 1);
588 * Allow updating the index when checking out from the index.
589 * This is to save new stat info.
591 if (opts
->checkout_worktree
&& !opts
->checkout_index
&& !opts
->source_tree
)
594 checkout_index
= opts
->checkout_index
;
596 if (checkout_index
) {
597 if (write_locked_index(&the_index
, &lock_file
, COMMIT_LOCK
))
598 die(_("unable to write new index file"));
601 * NEEDSWORK: if --worktree is not specified, we
602 * should save stat info of checked out files in the
603 * index to avoid the next (potentially costly)
604 * refresh. But it's a bit tricker to do...
606 rollback_lock_file(&lock_file
);
609 read_ref_full("HEAD", 0, &rev
, NULL
);
610 head
= lookup_commit_reference_gently(the_repository
, &rev
, 1);
612 errs
|= post_checkout_hook(head
, head
, 0);
616 static void show_local_changes(struct object
*head
,
617 const struct diff_options
*opts
)
620 /* I think we want full paths, even if we're in a subdirectory. */
621 repo_init_revisions(the_repository
, &rev
, NULL
);
622 rev
.diffopt
.flags
= opts
->flags
;
623 rev
.diffopt
.output_format
|= DIFF_FORMAT_NAME_STATUS
;
624 diff_setup_done(&rev
.diffopt
);
625 add_pending_object(&rev
, head
, NULL
);
626 run_diff_index(&rev
, 0);
627 object_array_clear(&rev
.pending
);
630 static void describe_detached_head(const char *msg
, struct commit
*commit
)
632 struct strbuf sb
= STRBUF_INIT
;
634 if (!parse_commit(commit
))
635 pp_commit_easy(CMIT_FMT_ONELINE
, commit
, &sb
);
636 if (print_sha1_ellipsis()) {
637 fprintf(stderr
, "%s %s... %s\n", msg
,
638 find_unique_abbrev(&commit
->object
.oid
, DEFAULT_ABBREV
), sb
.buf
);
640 fprintf(stderr
, "%s %s %s\n", msg
,
641 find_unique_abbrev(&commit
->object
.oid
, DEFAULT_ABBREV
), sb
.buf
);
646 static int reset_tree(struct tree
*tree
, const struct checkout_opts
*o
,
647 int worktree
, int *writeout_error
,
648 struct branch_info
*info
)
650 struct unpack_trees_options opts
;
651 struct tree_desc tree_desc
;
653 memset(&opts
, 0, sizeof(opts
));
655 opts
.update
= worktree
;
656 opts
.skip_unmerged
= !worktree
;
657 opts
.reset
= o
->force
? UNPACK_RESET_OVERWRITE_UNTRACKED
:
658 UNPACK_RESET_PROTECT_UNTRACKED
;
659 opts
.preserve_ignored
= (!o
->force
&& !o
->overwrite_ignore
);
661 opts
.fn
= oneway_merge
;
662 opts
.verbose_update
= o
->show_progress
;
663 opts
.src_index
= &the_index
;
664 opts
.dst_index
= &the_index
;
665 init_checkout_metadata(&opts
.meta
, info
->refname
,
666 info
->commit
? &info
->commit
->object
.oid
: null_oid(),
669 init_tree_desc(&tree_desc
, tree
->buffer
, tree
->size
);
670 switch (unpack_trees(1, &tree_desc
, &opts
)) {
674 * We return 0 nevertheless, as the index is all right
675 * and more importantly we have made best efforts to
676 * update paths in the work tree, and we cannot revert
687 static void setup_branch_path(struct branch_info
*branch
)
689 struct strbuf buf
= STRBUF_INIT
;
692 * If this is a ref, resolve it; otherwise, look up the OID for our
693 * expression. Failure here is okay.
695 if (!dwim_ref(branch
->name
, strlen(branch
->name
), &branch
->oid
, &branch
->refname
, 0))
696 repo_get_oid_committish(the_repository
, branch
->name
, &branch
->oid
);
698 strbuf_branchname(&buf
, branch
->name
, INTERPRET_BRANCH_LOCAL
);
699 if (strcmp(buf
.buf
, branch
->name
)) {
701 branch
->name
= xstrdup(buf
.buf
);
703 strbuf_splice(&buf
, 0, 0, "refs/heads/", 11);
705 branch
->path
= strbuf_detach(&buf
, NULL
);
708 static int merge_working_tree(const struct checkout_opts
*opts
,
709 struct branch_info
*old_branch_info
,
710 struct branch_info
*new_branch_info
,
714 struct lock_file lock_file
= LOCK_INIT
;
715 struct tree
*new_tree
;
717 hold_locked_index(&lock_file
, LOCK_DIE_ON_ERROR
);
718 if (read_cache_preload(NULL
) < 0)
719 return error(_("index file corrupt"));
721 resolve_undo_clear();
722 if (opts
->new_orphan_branch
&& opts
->orphan_from_empty_tree
) {
723 if (new_branch_info
->commit
)
724 BUG("'switch --orphan' should never accept a commit as starting point");
725 new_tree
= parse_tree_indirect(the_hash_algo
->empty_tree
);
727 new_tree
= get_commit_tree(new_branch_info
->commit
);
728 if (opts
->discard_changes
) {
729 ret
= reset_tree(new_tree
, opts
, 1, writeout_error
, new_branch_info
);
733 struct tree_desc trees
[2];
735 struct unpack_trees_options topts
;
737 memset(&topts
, 0, sizeof(topts
));
739 topts
.src_index
= &the_index
;
740 topts
.dst_index
= &the_index
;
742 setup_unpack_trees_porcelain(&topts
, "checkout");
744 refresh_cache(REFRESH_QUIET
);
746 if (unmerged_cache()) {
747 error(_("you need to resolve your current index first"));
751 /* 2-way merge to the new branch */
752 topts
.initial_checkout
= is_cache_unborn();
755 topts
.quiet
= opts
->merge
&& old_branch_info
->commit
;
756 topts
.verbose_update
= opts
->show_progress
;
757 topts
.fn
= twoway_merge
;
758 init_checkout_metadata(&topts
.meta
, new_branch_info
->refname
,
759 new_branch_info
->commit
?
760 &new_branch_info
->commit
->object
.oid
:
761 &new_branch_info
->oid
, NULL
);
762 topts
.preserve_ignored
= !opts
->overwrite_ignore
;
763 tree
= parse_tree_indirect(old_branch_info
->commit
?
764 &old_branch_info
->commit
->object
.oid
:
765 the_hash_algo
->empty_tree
);
766 init_tree_desc(&trees
[0], tree
->buffer
, tree
->size
);
767 parse_tree(new_tree
);
769 init_tree_desc(&trees
[1], tree
->buffer
, tree
->size
);
771 ret
= unpack_trees(2, trees
, &topts
);
772 clear_unpack_trees_porcelain(&topts
);
775 * Unpack couldn't do a trivial merge; either
776 * give up or do a real merge, depending on
777 * whether the merge flag was used.
780 struct tree
*old_tree
;
781 struct merge_options o
;
782 struct strbuf sb
= STRBUF_INIT
;
783 struct strbuf old_commit_shortname
= STRBUF_INIT
;
789 * Without old_branch_info->commit, the below is the same as
790 * the two-tree unpack we already tried and failed.
792 if (!old_branch_info
->commit
)
794 old_tree
= get_commit_tree(old_branch_info
->commit
);
796 if (repo_index_has_changes(the_repository
, old_tree
, &sb
))
797 die(_("cannot continue with staged changes in "
798 "the following files:\n%s"), sb
.buf
);
801 /* Do more real merge */
804 * We update the index fully, then write the
805 * tree from the index, then merge the new
806 * branch with the current tree, with the old
807 * branch as the base. Then we reset the index
808 * (but not the working tree) to the new
809 * branch, leaving the working tree as the
810 * merged version, but skipping unmerged
811 * entries in the index.
814 add_files_to_cache(NULL
, NULL
, 0);
815 init_merge_options(&o
, the_repository
);
817 work
= write_in_core_index_as_tree(the_repository
);
819 ret
= reset_tree(new_tree
,
821 writeout_error
, new_branch_info
);
824 o
.ancestor
= old_branch_info
->name
;
825 if (old_branch_info
->name
== NULL
) {
826 strbuf_add_unique_abbrev(&old_commit_shortname
,
827 &old_branch_info
->commit
->object
.oid
,
829 o
.ancestor
= old_commit_shortname
.buf
;
831 o
.branch1
= new_branch_info
->name
;
833 ret
= merge_trees(&o
,
839 ret
= reset_tree(new_tree
,
841 writeout_error
, new_branch_info
);
842 strbuf_release(&o
.obuf
);
843 strbuf_release(&old_commit_shortname
);
849 if (!cache_tree_fully_valid(active_cache_tree
))
850 cache_tree_update(&the_index
, WRITE_TREE_SILENT
| WRITE_TREE_REPAIR
);
852 if (write_locked_index(&the_index
, &lock_file
, COMMIT_LOCK
))
853 die(_("unable to write new index file"));
855 if (!opts
->discard_changes
&& !opts
->quiet
&& new_branch_info
->commit
)
856 show_local_changes(&new_branch_info
->commit
->object
, &opts
->diff_options
);
861 static void report_tracking(struct branch_info
*new_branch_info
)
863 struct strbuf sb
= STRBUF_INIT
;
864 struct branch
*branch
= branch_get(new_branch_info
->name
);
866 if (!format_tracking_info(branch
, &sb
, AHEAD_BEHIND_FULL
))
868 fputs(sb
.buf
, stdout
);
872 static void update_refs_for_switch(const struct checkout_opts
*opts
,
873 struct branch_info
*old_branch_info
,
874 struct branch_info
*new_branch_info
)
876 struct strbuf msg
= STRBUF_INIT
;
877 const char *old_desc
, *reflog_msg
;
878 if (opts
->new_branch
) {
879 if (opts
->new_orphan_branch
) {
882 refname
= mkpathdup("refs/heads/%s", opts
->new_orphan_branch
);
883 if (opts
->new_branch_log
&&
884 !should_autocreate_reflog(refname
)) {
886 struct strbuf err
= STRBUF_INIT
;
888 ret
= safe_create_reflog(refname
, &err
);
890 fprintf(stderr
, _("Can not do reflog for '%s': %s\n"),
891 opts
->new_orphan_branch
, err
.buf
);
892 strbuf_release(&err
);
896 strbuf_release(&err
);
901 create_branch(the_repository
,
902 opts
->new_branch
, new_branch_info
->name
,
903 opts
->new_branch_force
? 1 : 0,
904 opts
->new_branch_force
? 1 : 0,
905 opts
->new_branch_log
,
908 free(new_branch_info
->name
);
909 free(new_branch_info
->refname
);
910 new_branch_info
->name
= xstrdup(opts
->new_branch
);
911 setup_branch_path(new_branch_info
);
914 old_desc
= old_branch_info
->name
;
915 if (!old_desc
&& old_branch_info
->commit
)
916 old_desc
= oid_to_hex(&old_branch_info
->commit
->object
.oid
);
918 reflog_msg
= getenv("GIT_REFLOG_ACTION");
920 strbuf_addf(&msg
, "checkout: moving from %s to %s",
921 old_desc
? old_desc
: "(invalid)", new_branch_info
->name
);
923 strbuf_insertstr(&msg
, 0, reflog_msg
);
925 if (!strcmp(new_branch_info
->name
, "HEAD") && !new_branch_info
->path
&& !opts
->force_detach
) {
927 } else if (opts
->force_detach
|| !new_branch_info
->path
) { /* No longer on any branch. */
928 update_ref(msg
.buf
, "HEAD", &new_branch_info
->commit
->object
.oid
, NULL
,
929 REF_NO_DEREF
, UPDATE_REFS_DIE_ON_ERR
);
931 if (old_branch_info
->path
&&
932 advice_enabled(ADVICE_DETACHED_HEAD
) && !opts
->force_detach
)
933 detach_advice(new_branch_info
->name
);
934 describe_detached_head(_("HEAD is now at"), new_branch_info
->commit
);
936 } else if (new_branch_info
->path
) { /* Switch branches. */
937 if (create_symref("HEAD", new_branch_info
->path
, msg
.buf
) < 0)
938 die(_("unable to update HEAD"));
940 if (old_branch_info
->path
&& !strcmp(new_branch_info
->path
, old_branch_info
->path
)) {
941 if (opts
->new_branch_force
)
942 fprintf(stderr
, _("Reset branch '%s'\n"),
943 new_branch_info
->name
);
945 fprintf(stderr
, _("Already on '%s'\n"),
946 new_branch_info
->name
);
947 } else if (opts
->new_branch
) {
948 if (opts
->branch_exists
)
949 fprintf(stderr
, _("Switched to and reset branch '%s'\n"), new_branch_info
->name
);
951 fprintf(stderr
, _("Switched to a new branch '%s'\n"), new_branch_info
->name
);
953 fprintf(stderr
, _("Switched to branch '%s'\n"),
954 new_branch_info
->name
);
957 if (old_branch_info
->path
&& old_branch_info
->name
) {
958 if (!ref_exists(old_branch_info
->path
) && reflog_exists(old_branch_info
->path
))
959 delete_reflog(old_branch_info
->path
);
962 remove_branch_state(the_repository
, !opts
->quiet
);
963 strbuf_release(&msg
);
965 (new_branch_info
->path
|| (!opts
->force_detach
&& !strcmp(new_branch_info
->name
, "HEAD"))))
966 report_tracking(new_branch_info
);
969 static int add_pending_uninteresting_ref(const char *refname
,
970 const struct object_id
*oid
,
971 int flags
, void *cb_data
)
973 add_pending_oid(cb_data
, refname
, oid
, UNINTERESTING
);
977 static void describe_one_orphan(struct strbuf
*sb
, struct commit
*commit
)
979 strbuf_addstr(sb
, " ");
980 strbuf_add_unique_abbrev(sb
, &commit
->object
.oid
, DEFAULT_ABBREV
);
981 strbuf_addch(sb
, ' ');
982 if (!parse_commit(commit
))
983 pp_commit_easy(CMIT_FMT_ONELINE
, commit
, sb
);
984 strbuf_addch(sb
, '\n');
987 #define ORPHAN_CUTOFF 4
988 static void suggest_reattach(struct commit
*commit
, struct rev_info
*revs
)
990 struct commit
*c
, *last
= NULL
;
991 struct strbuf sb
= STRBUF_INIT
;
993 while ((c
= get_revision(revs
)) != NULL
) {
994 if (lost
< ORPHAN_CUTOFF
)
995 describe_one_orphan(&sb
, c
);
999 if (ORPHAN_CUTOFF
< lost
) {
1000 int more
= lost
- ORPHAN_CUTOFF
;
1002 describe_one_orphan(&sb
, last
);
1004 strbuf_addf(&sb
, _(" ... and %d more.\n"), more
);
1009 /* The singular version */
1010 "Warning: you are leaving %d commit behind, "
1011 "not connected to\n"
1012 "any of your branches:\n\n"
1014 /* The plural version */
1015 "Warning: you are leaving %d commits behind, "
1016 "not connected to\n"
1017 "any of your branches:\n\n"
1019 /* Give ngettext() the count */
1023 strbuf_release(&sb
);
1025 if (advice_enabled(ADVICE_DETACHED_HEAD
))
1028 /* The singular version */
1029 "If you want to keep it by creating a new branch, "
1030 "this may be a good time\nto do so with:\n\n"
1031 " git branch <new-branch-name> %s\n\n",
1032 /* The plural version */
1033 "If you want to keep them by creating a new branch, "
1034 "this may be a good time\nto do so with:\n\n"
1035 " git branch <new-branch-name> %s\n\n",
1036 /* Give ngettext() the count */
1038 find_unique_abbrev(&commit
->object
.oid
, DEFAULT_ABBREV
));
1042 * We are about to leave commit that was at the tip of a detached
1043 * HEAD. If it is not reachable from any ref, this is the last chance
1044 * for the user to do so without resorting to reflog.
1046 static void orphaned_commit_warning(struct commit
*old_commit
, struct commit
*new_commit
)
1048 struct rev_info revs
;
1049 struct object
*object
= &old_commit
->object
;
1051 repo_init_revisions(the_repository
, &revs
, NULL
);
1052 setup_revisions(0, NULL
, &revs
, NULL
);
1054 object
->flags
&= ~UNINTERESTING
;
1055 add_pending_object(&revs
, object
, oid_to_hex(&object
->oid
));
1057 for_each_ref(add_pending_uninteresting_ref
, &revs
);
1059 add_pending_oid(&revs
, "HEAD",
1060 &new_commit
->object
.oid
,
1063 if (prepare_revision_walk(&revs
))
1064 die(_("internal error in revision walk"));
1065 if (!(old_commit
->object
.flags
& UNINTERESTING
))
1066 suggest_reattach(old_commit
, &revs
);
1068 describe_detached_head(_("Previous HEAD position was"), old_commit
);
1070 /* Clean up objects used, as they will be reused. */
1071 repo_clear_commit_marks(the_repository
, ALL_REV_FLAGS
);
1074 static int switch_branches(const struct checkout_opts
*opts
,
1075 struct branch_info
*new_branch_info
)
1078 struct branch_info old_branch_info
= { 0 };
1079 struct object_id rev
;
1080 int flag
, writeout_error
= 0;
1083 trace2_cmd_mode("branch");
1085 memset(&old_branch_info
, 0, sizeof(old_branch_info
));
1086 old_branch_info
.path
= resolve_refdup("HEAD", 0, &rev
, &flag
);
1087 if (old_branch_info
.path
)
1088 old_branch_info
.commit
= lookup_commit_reference_gently(the_repository
, &rev
, 1);
1089 if (!(flag
& REF_ISSYMREF
))
1090 FREE_AND_NULL(old_branch_info
.path
);
1092 if (old_branch_info
.path
) {
1093 const char *const prefix
= "refs/heads/";
1095 if (skip_prefix(old_branch_info
.path
, prefix
, &p
))
1096 old_branch_info
.name
= xstrdup(p
);
1098 BUG("should be able to skip past '%s' in '%s'!",
1099 prefix
, old_branch_info
.path
);
1102 if (opts
->new_orphan_branch
&& opts
->orphan_from_empty_tree
) {
1103 if (new_branch_info
->name
)
1104 BUG("'switch --orphan' should never accept a commit as starting point");
1105 new_branch_info
->commit
= NULL
;
1106 new_branch_info
->name
= xstrdup("(empty)");
1110 if (!new_branch_info
->name
) {
1111 new_branch_info
->name
= xstrdup("HEAD");
1112 new_branch_info
->commit
= old_branch_info
.commit
;
1113 if (!new_branch_info
->commit
)
1114 die(_("You are on a branch yet to be born"));
1115 parse_commit_or_die(new_branch_info
->commit
);
1117 if (opts
->only_merge_on_switching_branches
)
1122 ret
= merge_working_tree(opts
, &old_branch_info
, new_branch_info
, &writeout_error
);
1124 branch_info_release(&old_branch_info
);
1129 if (!opts
->quiet
&& !old_branch_info
.path
&& old_branch_info
.commit
&& new_branch_info
->commit
!= old_branch_info
.commit
)
1130 orphaned_commit_warning(old_branch_info
.commit
, new_branch_info
->commit
);
1132 update_refs_for_switch(opts
, &old_branch_info
, new_branch_info
);
1134 ret
= post_checkout_hook(old_branch_info
.commit
, new_branch_info
->commit
, 1);
1135 branch_info_release(&old_branch_info
);
1137 return ret
|| writeout_error
;
1140 static int git_checkout_config(const char *var
, const char *value
, void *cb
)
1142 struct checkout_opts
*opts
= cb
;
1144 if (!strcmp(var
, "diff.ignoresubmodules")) {
1145 handle_ignore_submodules_arg(&opts
->diff_options
, value
);
1148 if (!strcmp(var
, "checkout.guess")) {
1149 opts
->dwim_new_local_branch
= git_config_bool(var
, value
);
1153 if (starts_with(var
, "submodule."))
1154 return git_default_submodule_config(var
, value
, NULL
);
1156 return git_xmerge_config(var
, value
, NULL
);
1159 static void setup_new_branch_info_and_source_tree(
1160 struct branch_info
*new_branch_info
,
1161 struct checkout_opts
*opts
,
1162 struct object_id
*rev
,
1165 struct tree
**source_tree
= &opts
->source_tree
;
1166 struct object_id branch_rev
;
1168 new_branch_info
->name
= xstrdup(arg
);
1169 setup_branch_path(new_branch_info
);
1171 if (!check_refname_format(new_branch_info
->path
, 0) &&
1172 !read_ref(new_branch_info
->path
, &branch_rev
))
1173 oidcpy(rev
, &branch_rev
);
1175 /* not an existing branch */
1176 FREE_AND_NULL(new_branch_info
->path
);
1178 new_branch_info
->commit
= lookup_commit_reference_gently(the_repository
, rev
, 1);
1179 if (!new_branch_info
->commit
) {
1181 *source_tree
= parse_tree_indirect(rev
);
1183 parse_commit_or_die(new_branch_info
->commit
);
1184 *source_tree
= get_commit_tree(new_branch_info
->commit
);
1188 static const char *parse_remote_branch(const char *arg
,
1189 struct object_id
*rev
,
1190 int could_be_checkout_paths
)
1192 int num_matches
= 0;
1193 const char *remote
= unique_tracking_name(arg
, rev
, &num_matches
);
1195 if (remote
&& could_be_checkout_paths
) {
1196 die(_("'%s' could be both a local file and a tracking branch.\n"
1197 "Please use -- (and optionally --no-guess) to disambiguate"),
1201 if (!remote
&& num_matches
> 1) {
1202 if (advice_enabled(ADVICE_CHECKOUT_AMBIGUOUS_REMOTE_BRANCH_NAME
)) {
1203 advise(_("If you meant to check out a remote tracking branch on, e.g. 'origin',\n"
1204 "you can do so by fully qualifying the name with the --track option:\n"
1206 " git checkout --track origin/<name>\n"
1208 "If you'd like to always have checkouts of an ambiguous <name> prefer\n"
1209 "one remote, e.g. the 'origin' remote, consider setting\n"
1210 "checkout.defaultRemote=origin in your config."));
1213 die(_("'%s' matched multiple (%d) remote tracking branches"),
1220 static int parse_branchname_arg(int argc
, const char **argv
,
1221 int dwim_new_local_branch_ok
,
1222 struct branch_info
*new_branch_info
,
1223 struct checkout_opts
*opts
,
1224 struct object_id
*rev
)
1226 const char **new_branch
= &opts
->new_branch
;
1230 int has_dash_dash
= 0;
1234 * case 1: git checkout <ref> -- [<paths>]
1236 * <ref> must be a valid tree, everything after the '--' must be
1239 * case 2: git checkout -- [<paths>]
1241 * everything after the '--' must be paths.
1243 * case 3: git checkout <something> [--]
1245 * (a) If <something> is a commit, that is to
1246 * switch to the branch or detach HEAD at it. As a special case,
1247 * if <something> is A...B (missing A or B means HEAD but you can
1248 * omit at most one side), and if there is a unique merge base
1249 * between A and B, A...B names that merge base.
1251 * (b) If <something> is _not_ a commit, either "--" is present
1252 * or <something> is not a path, no -t or -b was given, and
1253 * and there is a tracking branch whose name is <something>
1254 * in one and only one remote (or if the branch exists on the
1255 * remote named in checkout.defaultRemote), then this is a
1256 * short-hand to fork local <something> from that
1257 * remote-tracking branch.
1259 * (c) Otherwise, if "--" is present, treat it like case (1).
1262 * - if it's a reference, treat it like case (1)
1263 * - else if it's a path, treat it like case (2)
1266 * case 4: git checkout <something> <paths>
1268 * The first argument must not be ambiguous.
1269 * - If it's *only* a reference, treat it like case (1).
1270 * - If it's only a path, treat it like case (2).
1277 if (!opts
->accept_pathspec
) {
1279 die(_("only one reference expected"));
1280 has_dash_dash
= 1; /* helps disambiguate */
1285 for (i
= 0; i
< argc
; i
++) {
1286 if (opts
->accept_pathspec
&& !strcmp(argv
[i
], "--")) {
1291 if (dash_dash_pos
== 0)
1292 return 1; /* case (2) */
1293 else if (dash_dash_pos
== 1)
1294 has_dash_dash
= 1; /* case (3) or (1) */
1295 else if (dash_dash_pos
>= 2)
1296 die(_("only one reference expected, %d given."), dash_dash_pos
);
1297 opts
->count_checkout_paths
= !opts
->quiet
&& !has_dash_dash
;
1299 if (!strcmp(arg
, "-"))
1302 if (get_oid_mb(arg
, rev
)) {
1304 * Either case (3) or (4), with <something> not being
1305 * a commit, or an attempt to use case (1) with an
1308 * It's likely an error, but we need to find out if
1309 * we should auto-create the branch, case (3).(b).
1311 int recover_with_dwim
= dwim_new_local_branch_ok
;
1313 int could_be_checkout_paths
= !has_dash_dash
&&
1314 check_filename(opts
->prefix
, arg
);
1316 if (!has_dash_dash
&& !no_wildcard(arg
))
1317 recover_with_dwim
= 0;
1320 * Accept "git checkout foo", "git checkout foo --"
1321 * and "git switch foo" as candidates for dwim.
1323 if (!(argc
== 1 && !has_dash_dash
) &&
1324 !(argc
== 2 && has_dash_dash
) &&
1325 opts
->accept_pathspec
)
1326 recover_with_dwim
= 0;
1328 if (recover_with_dwim
) {
1329 const char *remote
= parse_remote_branch(arg
, rev
,
1330 could_be_checkout_paths
);
1334 /* DWIMmed to create local branch, case (3).(b) */
1336 recover_with_dwim
= 0;
1340 if (!recover_with_dwim
) {
1342 die(_("invalid reference: %s"), arg
);
1347 /* we can't end up being in (2) anymore, eat the argument */
1352 setup_new_branch_info_and_source_tree(new_branch_info
, opts
, rev
, arg
);
1354 if (!opts
->source_tree
) /* case (1): want a tree */
1355 die(_("reference is not a tree: %s"), arg
);
1357 if (!has_dash_dash
) { /* case (3).(d) -> (1) */
1359 * Do not complain the most common case
1360 * git checkout branch
1361 * even if there happen to be a file called 'branch';
1362 * it would be extremely annoying.
1365 verify_non_filename(opts
->prefix
, arg
);
1366 } else if (opts
->accept_pathspec
) {
1375 static int switch_unborn_to_new_branch(const struct checkout_opts
*opts
)
1378 struct strbuf branch_ref
= STRBUF_INIT
;
1380 trace2_cmd_mode("unborn");
1382 if (!opts
->new_branch
)
1383 die(_("You are on a branch yet to be born"));
1384 strbuf_addf(&branch_ref
, "refs/heads/%s", opts
->new_branch
);
1385 status
= create_symref("HEAD", branch_ref
.buf
, "checkout -b");
1386 strbuf_release(&branch_ref
);
1388 fprintf(stderr
, _("Switched to a new branch '%s'\n"),
1393 static void die_expecting_a_branch(const struct branch_info
*branch_info
)
1395 struct object_id oid
;
1398 if (dwim_ref(branch_info
->name
, strlen(branch_info
->name
), &oid
, &to_free
, 0) == 1) {
1399 const char *ref
= to_free
;
1401 if (skip_prefix(ref
, "refs/tags/", &ref
))
1402 die(_("a branch is expected, got tag '%s'"), ref
);
1403 if (skip_prefix(ref
, "refs/remotes/", &ref
))
1404 die(_("a branch is expected, got remote branch '%s'"), ref
);
1405 die(_("a branch is expected, got '%s'"), ref
);
1407 if (branch_info
->commit
)
1408 die(_("a branch is expected, got commit '%s'"), branch_info
->name
);
1410 * This case should never happen because we already die() on
1411 * non-commit, but just in case.
1413 die(_("a branch is expected, got '%s'"), branch_info
->name
);
1416 static void die_if_some_operation_in_progress(void)
1418 struct wt_status_state state
;
1420 memset(&state
, 0, sizeof(state
));
1421 wt_status_get_state(the_repository
, &state
, 0);
1423 if (state
.merge_in_progress
)
1424 die(_("cannot switch branch while merging\n"
1425 "Consider \"git merge --quit\" "
1426 "or \"git worktree add\"."));
1427 if (state
.am_in_progress
)
1428 die(_("cannot switch branch in the middle of an am session\n"
1429 "Consider \"git am --quit\" "
1430 "or \"git worktree add\"."));
1431 if (state
.rebase_interactive_in_progress
|| state
.rebase_in_progress
)
1432 die(_("cannot switch branch while rebasing\n"
1433 "Consider \"git rebase --quit\" "
1434 "or \"git worktree add\"."));
1435 if (state
.cherry_pick_in_progress
)
1436 die(_("cannot switch branch while cherry-picking\n"
1437 "Consider \"git cherry-pick --quit\" "
1438 "or \"git worktree add\"."));
1439 if (state
.revert_in_progress
)
1440 die(_("cannot switch branch while reverting\n"
1441 "Consider \"git revert --quit\" "
1442 "or \"git worktree add\"."));
1443 if (state
.bisect_in_progress
)
1444 warning(_("you are switching branch while bisecting"));
1447 static int checkout_branch(struct checkout_opts
*opts
,
1448 struct branch_info
*new_branch_info
)
1450 if (opts
->pathspec
.nr
)
1451 die(_("paths cannot be used with switching branches"));
1453 if (opts
->patch_mode
)
1454 die(_("'%s' cannot be used with switching branches"),
1457 if (opts
->overlay_mode
!= -1)
1458 die(_("'%s' cannot be used with switching branches"),
1461 if (opts
->writeout_stage
)
1462 die(_("'%s' cannot be used with switching branches"),
1465 if (opts
->force
&& opts
->merge
)
1466 die(_("'%s' cannot be used with '%s'"), "-f", "-m");
1468 if (opts
->discard_changes
&& opts
->merge
)
1469 die(_("'%s' cannot be used with '%s'"), "--discard-changes", "--merge");
1471 if (opts
->force_detach
&& opts
->new_branch
)
1472 die(_("'%s' cannot be used with '%s'"),
1473 "--detach", "-b/-B/--orphan");
1475 if (opts
->new_orphan_branch
) {
1476 if (opts
->track
!= BRANCH_TRACK_UNSPECIFIED
)
1477 die(_("'%s' cannot be used with '%s'"), "--orphan", "-t");
1478 if (opts
->orphan_from_empty_tree
&& new_branch_info
->name
)
1479 die(_("'%s' cannot take <start-point>"), "--orphan");
1480 } else if (opts
->force_detach
) {
1481 if (opts
->track
!= BRANCH_TRACK_UNSPECIFIED
)
1482 die(_("'%s' cannot be used with '%s'"), "--detach", "-t");
1483 } else if (opts
->track
== BRANCH_TRACK_UNSPECIFIED
)
1484 opts
->track
= git_branch_track
;
1486 if (new_branch_info
->name
&& !new_branch_info
->commit
)
1487 die(_("Cannot switch branch to a non-commit '%s'"),
1488 new_branch_info
->name
);
1490 if (!opts
->switch_branch_doing_nothing_is_ok
&&
1491 !new_branch_info
->name
&&
1492 !opts
->new_branch
&&
1493 !opts
->force_detach
)
1494 die(_("missing branch or commit argument"));
1496 if (!opts
->implicit_detach
&&
1497 !opts
->force_detach
&&
1498 !opts
->new_branch
&&
1499 !opts
->new_branch_force
&&
1500 new_branch_info
->name
&&
1501 !new_branch_info
->path
)
1502 die_expecting_a_branch(new_branch_info
);
1504 if (!opts
->can_switch_when_in_progress
)
1505 die_if_some_operation_in_progress();
1507 if (new_branch_info
->path
&& !opts
->force_detach
&& !opts
->new_branch
&&
1508 !opts
->ignore_other_worktrees
) {
1510 char *head_ref
= resolve_refdup("HEAD", 0, NULL
, &flag
);
1512 (!(flag
& REF_ISSYMREF
) || strcmp(head_ref
, new_branch_info
->path
)))
1513 die_if_checked_out(new_branch_info
->path
, 1);
1517 if (!new_branch_info
->commit
&& opts
->new_branch
) {
1518 struct object_id rev
;
1521 if (!read_ref_full("HEAD", 0, &rev
, &flag
) &&
1522 (flag
& REF_ISSYMREF
) && is_null_oid(&rev
))
1523 return switch_unborn_to_new_branch(opts
);
1525 return switch_branches(opts
, new_branch_info
);
1528 static struct option
*add_common_options(struct checkout_opts
*opts
,
1529 struct option
*prevopts
)
1531 struct option options
[] = {
1532 OPT__QUIET(&opts
->quiet
, N_("suppress progress reporting")),
1533 OPT_CALLBACK_F(0, "recurse-submodules", NULL
,
1534 "checkout", "control recursive updating of submodules",
1535 PARSE_OPT_OPTARG
, option_parse_recurse_submodules_worktree_updater
),
1536 OPT_BOOL(0, "progress", &opts
->show_progress
, N_("force progress reporting")),
1537 OPT_BOOL('m', "merge", &opts
->merge
, N_("perform a 3-way merge with the new branch")),
1538 OPT_STRING(0, "conflict", &opts
->conflict_style
, N_("style"),
1539 N_("conflict style (merge, diff3, or zdiff3)")),
1542 struct option
*newopts
= parse_options_concat(prevopts
, options
);
1547 static struct option
*add_common_switch_branch_options(
1548 struct checkout_opts
*opts
, struct option
*prevopts
)
1550 struct option options
[] = {
1551 OPT_BOOL('d', "detach", &opts
->force_detach
, N_("detach HEAD at named commit")),
1552 OPT_CALLBACK_F('t', "track", &opts
->track
, N_("mode"),
1553 N_("set branch tracking configuration"),
1555 parse_opt_tracking_mode
),
1556 OPT__FORCE(&opts
->force
, N_("force checkout (throw away local modifications)"),
1557 PARSE_OPT_NOCOMPLETE
),
1558 OPT_STRING(0, "orphan", &opts
->new_orphan_branch
, N_("new-branch"), N_("new unparented branch")),
1559 OPT_BOOL_F(0, "overwrite-ignore", &opts
->overwrite_ignore
,
1560 N_("update ignored files (default)"),
1561 PARSE_OPT_NOCOMPLETE
),
1562 OPT_BOOL(0, "ignore-other-worktrees", &opts
->ignore_other_worktrees
,
1563 N_("do not check if another worktree is holding the given ref")),
1566 struct option
*newopts
= parse_options_concat(prevopts
, options
);
1571 static struct option
*add_checkout_path_options(struct checkout_opts
*opts
,
1572 struct option
*prevopts
)
1574 struct option options
[] = {
1575 OPT_SET_INT_F('2', "ours", &opts
->writeout_stage
,
1576 N_("checkout our version for unmerged files"),
1577 2, PARSE_OPT_NONEG
),
1578 OPT_SET_INT_F('3', "theirs", &opts
->writeout_stage
,
1579 N_("checkout their version for unmerged files"),
1580 3, PARSE_OPT_NONEG
),
1581 OPT_BOOL('p', "patch", &opts
->patch_mode
, N_("select hunks interactively")),
1582 OPT_BOOL(0, "ignore-skip-worktree-bits", &opts
->ignore_skipworktree
,
1583 N_("do not limit pathspecs to sparse entries only")),
1584 OPT_PATHSPEC_FROM_FILE(&opts
->pathspec_from_file
),
1585 OPT_PATHSPEC_FILE_NUL(&opts
->pathspec_file_nul
),
1588 struct option
*newopts
= parse_options_concat(prevopts
, options
);
1593 /* create-branch option (either b or c) */
1594 static char cb_option
= 'b';
1596 static int checkout_main(int argc
, const char **argv
, const char *prefix
,
1597 struct checkout_opts
*opts
, struct option
*options
,
1598 const char * const usagestr
[],
1599 struct branch_info
*new_branch_info
)
1601 int parseopt_flags
= 0;
1603 opts
->overwrite_ignore
= 1;
1604 opts
->prefix
= prefix
;
1605 opts
->show_progress
= -1;
1607 git_config(git_checkout_config
, opts
);
1609 prepare_repo_settings(the_repository
);
1610 the_repository
->settings
.command_requires_full_index
= 0;
1612 opts
->track
= BRANCH_TRACK_UNSPECIFIED
;
1614 if (!opts
->accept_pathspec
&& !opts
->accept_ref
)
1615 BUG("make up your mind, you need to take _something_");
1616 if (opts
->accept_pathspec
&& opts
->accept_ref
)
1617 parseopt_flags
= PARSE_OPT_KEEP_DASHDASH
;
1619 argc
= parse_options(argc
, argv
, prefix
, options
,
1620 usagestr
, parseopt_flags
);
1622 if (opts
->show_progress
< 0) {
1624 opts
->show_progress
= 0;
1626 opts
->show_progress
= isatty(2);
1629 if (opts
->conflict_style
) {
1630 opts
->merge
= 1; /* implied */
1631 git_xmerge_config("merge.conflictstyle", opts
->conflict_style
, NULL
);
1634 opts
->discard_changes
= 1;
1635 opts
->ignore_unmerged_opt
= "--force";
1636 opts
->ignore_unmerged
= 1;
1639 if ((!!opts
->new_branch
+ !!opts
->new_branch_force
+ !!opts
->new_orphan_branch
) > 1)
1640 die(_("options '-%c', '-%c', and '%s' cannot be used together"),
1641 cb_option
, toupper(cb_option
), "--orphan");
1643 if (opts
->overlay_mode
== 1 && opts
->patch_mode
)
1644 die(_("options '%s' and '%s' cannot be used together"), "-p", "--overlay");
1646 if (opts
->checkout_index
>= 0 || opts
->checkout_worktree
>= 0) {
1647 if (opts
->checkout_index
< 0)
1648 opts
->checkout_index
= 0;
1649 if (opts
->checkout_worktree
< 0)
1650 opts
->checkout_worktree
= 0;
1652 if (opts
->checkout_index
< 0)
1653 opts
->checkout_index
= -opts
->checkout_index
- 1;
1654 if (opts
->checkout_worktree
< 0)
1655 opts
->checkout_worktree
= -opts
->checkout_worktree
- 1;
1657 if (opts
->checkout_index
< 0 || opts
->checkout_worktree
< 0)
1658 BUG("these flags should be non-negative by now");
1660 * convenient shortcut: "git restore --staged [--worktree]" equals
1661 * "git restore --staged [--worktree] --source HEAD"
1663 if (!opts
->from_treeish
&& opts
->checkout_index
)
1664 opts
->from_treeish
= "HEAD";
1667 * From here on, new_branch will contain the branch to be checked out,
1668 * and new_branch_force and new_orphan_branch will tell us which one of
1669 * -b/-B/-c/-C/--orphan is being used.
1671 if (opts
->new_branch_force
)
1672 opts
->new_branch
= opts
->new_branch_force
;
1674 if (opts
->new_orphan_branch
)
1675 opts
->new_branch
= opts
->new_orphan_branch
;
1677 /* --track without -c/-C/-b/-B/--orphan should DWIM */
1678 if (opts
->track
!= BRANCH_TRACK_UNSPECIFIED
&& !opts
->new_branch
) {
1679 const char *argv0
= argv
[0];
1680 if (!argc
|| !strcmp(argv0
, "--"))
1681 die(_("--track needs a branch name"));
1682 skip_prefix(argv0
, "refs/", &argv0
);
1683 skip_prefix(argv0
, "remotes/", &argv0
);
1684 argv0
= strchr(argv0
, '/');
1685 if (!argv0
|| !argv0
[1])
1686 die(_("missing branch name; try -%c"), cb_option
);
1687 opts
->new_branch
= argv0
+ 1;
1691 * Extract branch name from command line arguments, so
1692 * all that is left is pathspecs.
1696 * 1) git checkout <tree> -- [<paths>]
1697 * 2) git checkout -- [<paths>]
1698 * 3) git checkout <something> [<paths>]
1700 * including "last branch" syntax and DWIM-ery for names of
1701 * remote branches, erroring out for invalid or ambiguous cases.
1703 if (argc
&& opts
->accept_ref
) {
1704 struct object_id rev
;
1706 !opts
->patch_mode
&&
1707 opts
->dwim_new_local_branch
&&
1708 opts
->track
== BRANCH_TRACK_UNSPECIFIED
&&
1710 int n
= parse_branchname_arg(argc
, argv
, dwim_ok
,
1711 new_branch_info
, opts
, &rev
);
1714 } else if (!opts
->accept_ref
&& opts
->from_treeish
) {
1715 struct object_id rev
;
1717 if (get_oid_mb(opts
->from_treeish
, &rev
))
1718 die(_("could not resolve %s"), opts
->from_treeish
);
1720 setup_new_branch_info_and_source_tree(new_branch_info
,
1722 opts
->from_treeish
);
1724 if (!opts
->source_tree
)
1725 die(_("reference is not a tree: %s"), opts
->from_treeish
);
1729 parse_pathspec(&opts
->pathspec
, 0,
1730 opts
->patch_mode
? PATHSPEC_PREFIX_ORIGIN
: 0,
1733 if (!opts
->pathspec
.nr
)
1734 die(_("invalid path specification"));
1737 * Try to give more helpful suggestion.
1738 * new_branch && argc > 1 will be caught later.
1740 if (opts
->new_branch
&& argc
== 1 && !new_branch_info
->commit
)
1741 die(_("'%s' is not a commit and a branch '%s' cannot be created from it"),
1742 argv
[0], opts
->new_branch
);
1744 if (opts
->force_detach
)
1745 die(_("git checkout: --detach does not take a path argument '%s'"),
1749 if (opts
->pathspec_from_file
) {
1750 if (opts
->pathspec
.nr
)
1751 die(_("'%s' and pathspec arguments cannot be used together"), "--pathspec-from-file");
1753 if (opts
->force_detach
)
1754 die(_("options '%s' and '%s' cannot be used together"), "--pathspec-from-file", "--detach");
1756 if (opts
->patch_mode
)
1757 die(_("options '%s' and '%s' cannot be used together"), "--pathspec-from-file", "--patch");
1759 parse_pathspec_file(&opts
->pathspec
, 0,
1761 prefix
, opts
->pathspec_from_file
, opts
->pathspec_file_nul
);
1762 } else if (opts
->pathspec_file_nul
) {
1763 die(_("the option '%s' requires '%s'"), "--pathspec-file-nul", "--pathspec-from-file");
1766 opts
->pathspec
.recursive
= 1;
1768 if (opts
->pathspec
.nr
) {
1769 if (1 < !!opts
->writeout_stage
+ !!opts
->force
+ !!opts
->merge
)
1770 die(_("git checkout: --ours/--theirs, --force and --merge are incompatible when\n"
1771 "checking out of the index."));
1773 if (opts
->accept_pathspec
&& !opts
->empty_pathspec_ok
&&
1774 !opts
->patch_mode
) /* patch mode is special */
1775 die(_("you must specify path(s) to restore"));
1778 if (opts
->new_branch
) {
1779 struct strbuf buf
= STRBUF_INIT
;
1781 if (opts
->new_branch_force
)
1782 opts
->branch_exists
= validate_branchname(opts
->new_branch
, &buf
);
1784 opts
->branch_exists
=
1785 validate_new_branchname(opts
->new_branch
, &buf
, 0);
1786 strbuf_release(&buf
);
1789 if (opts
->patch_mode
|| opts
->pathspec
.nr
)
1790 return checkout_paths(opts
, new_branch_info
);
1792 return checkout_branch(opts
, new_branch_info
);
1795 int cmd_checkout(int argc
, const char **argv
, const char *prefix
)
1797 struct checkout_opts opts
;
1798 struct option
*options
;
1799 struct option checkout_options
[] = {
1800 OPT_STRING('b', NULL
, &opts
.new_branch
, N_("branch"),
1801 N_("create and checkout a new branch")),
1802 OPT_STRING('B', NULL
, &opts
.new_branch_force
, N_("branch"),
1803 N_("create/reset and checkout a branch")),
1804 OPT_BOOL('l', NULL
, &opts
.new_branch_log
, N_("create reflog for new branch")),
1805 OPT_BOOL(0, "guess", &opts
.dwim_new_local_branch
,
1806 N_("second guess 'git checkout <no-such-branch>' (default)")),
1807 OPT_BOOL(0, "overlay", &opts
.overlay_mode
, N_("use overlay mode (default)")),
1811 struct branch_info new_branch_info
= { 0 };
1813 memset(&opts
, 0, sizeof(opts
));
1814 opts
.dwim_new_local_branch
= 1;
1815 opts
.switch_branch_doing_nothing_is_ok
= 1;
1816 opts
.only_merge_on_switching_branches
= 0;
1817 opts
.accept_ref
= 1;
1818 opts
.accept_pathspec
= 1;
1819 opts
.implicit_detach
= 1;
1820 opts
.can_switch_when_in_progress
= 1;
1821 opts
.orphan_from_empty_tree
= 0;
1822 opts
.empty_pathspec_ok
= 1;
1823 opts
.overlay_mode
= -1;
1824 opts
.checkout_index
= -2; /* default on */
1825 opts
.checkout_worktree
= -2; /* default on */
1827 if (argc
== 3 && !strcmp(argv
[1], "-b")) {
1829 * User ran 'git checkout -b <branch>' and expects
1830 * the same behavior as 'git switch -c <branch>'.
1832 opts
.switch_branch_doing_nothing_is_ok
= 0;
1833 opts
.only_merge_on_switching_branches
= 1;
1836 options
= parse_options_dup(checkout_options
);
1837 options
= add_common_options(&opts
, options
);
1838 options
= add_common_switch_branch_options(&opts
, options
);
1839 options
= add_checkout_path_options(&opts
, options
);
1841 ret
= checkout_main(argc
, argv
, prefix
, &opts
,
1842 options
, checkout_usage
, &new_branch_info
);
1843 branch_info_release(&new_branch_info
);
1844 clear_pathspec(&opts
.pathspec
);
1845 FREE_AND_NULL(options
);
1849 int cmd_switch(int argc
, const char **argv
, const char *prefix
)
1851 struct checkout_opts opts
;
1852 struct option
*options
= NULL
;
1853 struct option switch_options
[] = {
1854 OPT_STRING('c', "create", &opts
.new_branch
, N_("branch"),
1855 N_("create and switch to a new branch")),
1856 OPT_STRING('C', "force-create", &opts
.new_branch_force
, N_("branch"),
1857 N_("create/reset and switch to a branch")),
1858 OPT_BOOL(0, "guess", &opts
.dwim_new_local_branch
,
1859 N_("second guess 'git switch <no-such-branch>'")),
1860 OPT_BOOL(0, "discard-changes", &opts
.discard_changes
,
1861 N_("throw away local modifications")),
1865 struct branch_info new_branch_info
= { 0 };
1867 memset(&opts
, 0, sizeof(opts
));
1868 opts
.dwim_new_local_branch
= 1;
1869 opts
.accept_ref
= 1;
1870 opts
.accept_pathspec
= 0;
1871 opts
.switch_branch_doing_nothing_is_ok
= 0;
1872 opts
.only_merge_on_switching_branches
= 1;
1873 opts
.implicit_detach
= 0;
1874 opts
.can_switch_when_in_progress
= 0;
1875 opts
.orphan_from_empty_tree
= 1;
1876 opts
.overlay_mode
= -1;
1878 options
= parse_options_dup(switch_options
);
1879 options
= add_common_options(&opts
, options
);
1880 options
= add_common_switch_branch_options(&opts
, options
);
1884 ret
= checkout_main(argc
, argv
, prefix
, &opts
,
1885 options
, switch_branch_usage
, &new_branch_info
);
1886 branch_info_release(&new_branch_info
);
1887 FREE_AND_NULL(options
);
1891 int cmd_restore(int argc
, const char **argv
, const char *prefix
)
1893 struct checkout_opts opts
;
1894 struct option
*options
;
1895 struct option restore_options
[] = {
1896 OPT_STRING('s', "source", &opts
.from_treeish
, "<tree-ish>",
1897 N_("which tree-ish to checkout from")),
1898 OPT_BOOL('S', "staged", &opts
.checkout_index
,
1899 N_("restore the index")),
1900 OPT_BOOL('W', "worktree", &opts
.checkout_worktree
,
1901 N_("restore the working tree (default)")),
1902 OPT_BOOL(0, "ignore-unmerged", &opts
.ignore_unmerged
,
1903 N_("ignore unmerged entries")),
1904 OPT_BOOL(0, "overlay", &opts
.overlay_mode
, N_("use overlay mode")),
1908 struct branch_info new_branch_info
= { 0 };
1910 memset(&opts
, 0, sizeof(opts
));
1911 opts
.accept_ref
= 0;
1912 opts
.accept_pathspec
= 1;
1913 opts
.empty_pathspec_ok
= 0;
1914 opts
.overlay_mode
= 0;
1915 opts
.checkout_index
= -1; /* default off */
1916 opts
.checkout_worktree
= -2; /* default on */
1917 opts
.ignore_unmerged_opt
= "--ignore-unmerged";
1919 options
= parse_options_dup(restore_options
);
1920 options
= add_common_options(&opts
, options
);
1921 options
= add_checkout_path_options(&opts
, options
);
1923 ret
= checkout_main(argc
, argv
, prefix
, &opts
,
1924 options
, restore_usage
, &new_branch_info
);
1925 branch_info_release(&new_branch_info
);
1926 FREE_AND_NULL(options
);