1 #define USE_THE_INDEX_COMPATIBILITY_MACROS
6 #include "cache-tree.h"
15 #include "merge-recursive.h"
16 #include "object-store.h"
17 #include "parse-options.h"
20 #include "resolve-undo.h"
22 #include "run-command.h"
23 #include "submodule.h"
24 #include "submodule-config.h"
26 #include "tree-walk.h"
27 #include "unpack-trees.h"
28 #include "wt-status.h"
29 #include "xdiff-interface.h"
31 #include "parallel-checkout.h"
33 static const char * const checkout_usage
[] = {
34 N_("git checkout [<options>] <branch>"),
35 N_("git checkout [<options>] [<branch>] -- <file>..."),
39 static const char * const switch_branch_usage
[] = {
40 N_("git switch [<options>] [<branch>]"),
44 static const char * const restore_usage
[] = {
45 N_("git restore [<options>] [--source=<branch>] <file>..."),
49 struct checkout_opts
{
58 int ignore_skipworktree
;
59 int ignore_other_worktrees
;
61 int count_checkout_paths
;
63 int dwim_new_local_branch
;
67 int switch_branch_doing_nothing_is_ok
;
68 int only_merge_on_switching_branches
;
69 int can_switch_when_in_progress
;
70 int orphan_from_empty_tree
;
71 int empty_pathspec_ok
;
73 int checkout_worktree
;
74 const char *ignore_unmerged_opt
;
76 int pathspec_file_nul
;
77 const char *pathspec_from_file
;
79 const char *new_branch
;
80 const char *new_branch_force
;
81 const char *new_orphan_branch
;
83 enum branch_track track
;
84 struct diff_options diff_options
;
89 struct pathspec pathspec
;
90 const char *from_treeish
;
91 struct tree
*source_tree
;
95 char *name
; /* The short name used */
96 char *path
; /* The full name of a real branch */
97 struct commit
*commit
; /* The named commit */
98 char *refname
; /* The full name of the ref being checked out. */
99 struct object_id oid
; /* The object ID of the commit being checked out. */
101 * if not null the branch is detached because it's already
102 * checked out in this checkout
107 static void branch_info_release(struct branch_info
*info
)
112 free(info
->checkout
);
115 static int post_checkout_hook(struct commit
*old_commit
, struct commit
*new_commit
,
118 return run_hooks_l("post-checkout",
119 oid_to_hex(old_commit
? &old_commit
->object
.oid
: null_oid()),
120 oid_to_hex(new_commit
? &new_commit
->object
.oid
: null_oid()),
121 changed
? "1" : "0", NULL
);
122 /* "new_commit" can be NULL when checking out from the index before
127 static int update_some(const struct object_id
*oid
, struct strbuf
*base
,
128 const char *pathname
, unsigned mode
, void *context
)
131 struct cache_entry
*ce
;
135 return READ_TREE_RECURSIVE
;
137 len
= base
->len
+ strlen(pathname
);
138 ce
= make_empty_cache_entry(&the_index
, len
);
139 oidcpy(&ce
->oid
, oid
);
140 memcpy(ce
->name
, base
->buf
, base
->len
);
141 memcpy(ce
->name
+ base
->len
, pathname
, len
- base
->len
);
142 ce
->ce_flags
= create_ce_flags(0) | CE_UPDATE
;
143 ce
->ce_namelen
= len
;
144 ce
->ce_mode
= create_ce_mode(mode
);
147 * If the entry is the same as the current index, we can leave the old
148 * entry in place. Whether it is UPTODATE or not, checkout_entry will
149 * do the right thing.
151 pos
= cache_name_pos(ce
->name
, ce
->ce_namelen
);
153 struct cache_entry
*old
= active_cache
[pos
];
154 if (ce
->ce_mode
== old
->ce_mode
&&
155 !ce_intent_to_add(old
) &&
156 oideq(&ce
->oid
, &old
->oid
)) {
157 old
->ce_flags
|= CE_UPDATE
;
158 discard_cache_entry(ce
);
163 add_cache_entry(ce
, ADD_CACHE_OK_TO_ADD
| ADD_CACHE_OK_TO_REPLACE
);
167 static int read_tree_some(struct tree
*tree
, const struct pathspec
*pathspec
)
169 read_tree(the_repository
, tree
,
170 pathspec
, update_some
, NULL
);
172 /* update the index with the given tree's info
173 * for all args, expanding wildcards, and exit
174 * with any non-zero return code.
179 static int skip_same_name(const struct cache_entry
*ce
, int pos
)
181 while (++pos
< active_nr
&&
182 !strcmp(active_cache
[pos
]->name
, ce
->name
))
187 static int check_stage(int stage
, const struct cache_entry
*ce
, int pos
,
190 while (pos
< active_nr
&&
191 !strcmp(active_cache
[pos
]->name
, ce
->name
)) {
192 if (ce_stage(active_cache
[pos
]) == stage
)
199 return error(_("path '%s' does not have our version"), ce
->name
);
201 return error(_("path '%s' does not have their version"), ce
->name
);
204 static int check_stages(unsigned stages
, const struct cache_entry
*ce
, int pos
)
207 const char *name
= ce
->name
;
209 while (pos
< active_nr
) {
210 ce
= active_cache
[pos
];
211 if (strcmp(name
, ce
->name
))
213 seen
|= (1 << ce_stage(ce
));
216 if ((stages
& seen
) != stages
)
217 return error(_("path '%s' does not have all necessary versions"),
222 static int checkout_stage(int stage
, const struct cache_entry
*ce
, int pos
,
223 const struct checkout
*state
, int *nr_checkouts
,
226 while (pos
< active_nr
&&
227 !strcmp(active_cache
[pos
]->name
, ce
->name
)) {
228 if (ce_stage(active_cache
[pos
]) == stage
)
229 return checkout_entry(active_cache
[pos
], state
,
238 return error(_("path '%s' does not have our version"), ce
->name
);
240 return error(_("path '%s' does not have their version"), ce
->name
);
243 static int checkout_merged(int pos
, const struct checkout
*state
,
244 int *nr_checkouts
, struct mem_pool
*ce_mem_pool
)
246 struct cache_entry
*ce
= active_cache
[pos
];
247 const char *path
= ce
->name
;
248 mmfile_t ancestor
, ours
, theirs
;
249 enum ll_merge_result merge_status
;
251 struct object_id oid
;
252 mmbuffer_t result_buf
;
253 struct object_id threeway
[3];
255 struct ll_merge_options ll_opts
;
258 memset(threeway
, 0, sizeof(threeway
));
259 while (pos
< active_nr
) {
261 stage
= ce_stage(ce
);
262 if (!stage
|| strcmp(path
, ce
->name
))
264 oidcpy(&threeway
[stage
- 1], &ce
->oid
);
266 mode
= create_ce_mode(ce
->ce_mode
);
268 ce
= active_cache
[pos
];
270 if (is_null_oid(&threeway
[1]) || is_null_oid(&threeway
[2]))
271 return error(_("path '%s' does not have necessary versions"), path
);
273 read_mmblob(&ancestor
, &threeway
[0]);
274 read_mmblob(&ours
, &threeway
[1]);
275 read_mmblob(&theirs
, &threeway
[2]);
277 memset(&ll_opts
, 0, sizeof(ll_opts
));
278 git_config_get_bool("merge.renormalize", &renormalize
);
279 ll_opts
.renormalize
= renormalize
;
280 merge_status
= ll_merge(&result_buf
, path
, &ancestor
, "base",
281 &ours
, "ours", &theirs
, "theirs",
282 state
->istate
, &ll_opts
);
286 if (merge_status
== LL_MERGE_BINARY_CONFLICT
)
287 warning("Cannot merge binary files: %s (%s vs. %s)",
288 path
, "ours", "theirs");
289 if (merge_status
< 0 || !result_buf
.ptr
) {
290 free(result_buf
.ptr
);
291 return error(_("path '%s': cannot merge"), path
);
296 * There is absolutely no reason to write this as a blob object
297 * and create a phony cache entry. This hack is primarily to get
298 * to the write_entry() machinery that massages the contents to
299 * work-tree format and writes out which only allows it for a
300 * cache entry. The code in write_entry() needs to be refactored
301 * to allow us to feed a <buffer, size, mode> instead of a cache
302 * entry. Such a refactoring would help merge_recursive as well
303 * (it also writes the merge result to the object database even
304 * when it may contain conflicts).
306 if (write_object_file(result_buf
.ptr
, result_buf
.size
, blob_type
, &oid
))
307 die(_("Unable to add merge result for '%s'"), path
);
308 free(result_buf
.ptr
);
309 ce
= make_transient_cache_entry(mode
, &oid
, path
, 2, ce_mem_pool
);
311 die(_("make_cache_entry failed for path '%s'"), path
);
312 status
= checkout_entry(ce
, state
, NULL
, nr_checkouts
);
316 static void mark_ce_for_checkout_overlay(struct cache_entry
*ce
,
318 const struct checkout_opts
*opts
)
320 ce
->ce_flags
&= ~CE_MATCHED
;
321 if (!opts
->ignore_skipworktree
&& ce_skip_worktree(ce
))
323 if (opts
->source_tree
&& !(ce
->ce_flags
& CE_UPDATE
))
325 * "git checkout tree-ish -- path", but this entry
326 * is in the original index but is not in tree-ish
327 * or does not match the pathspec; it will not be
328 * checked out to the working tree. We will not do
329 * anything to this entry at all.
333 * Either this entry came from the tree-ish we are
334 * checking the paths out of, or we are checking out
337 * If it comes from the tree-ish, we already know it
338 * matches the pathspec and could just stamp
339 * CE_MATCHED to it from update_some(). But we still
340 * need ps_matched and read_tree (and
341 * eventually tree_entry_interesting) cannot fill
342 * ps_matched yet. Once it can, we can avoid calling
343 * match_pathspec() for _all_ entries when
344 * opts->source_tree != NULL.
346 if (ce_path_match(&the_index
, ce
, &opts
->pathspec
, ps_matched
))
347 ce
->ce_flags
|= CE_MATCHED
;
350 static void mark_ce_for_checkout_no_overlay(struct cache_entry
*ce
,
352 const struct checkout_opts
*opts
)
354 ce
->ce_flags
&= ~CE_MATCHED
;
355 if (!opts
->ignore_skipworktree
&& ce_skip_worktree(ce
))
357 if (ce_path_match(&the_index
, ce
, &opts
->pathspec
, ps_matched
)) {
358 ce
->ce_flags
|= CE_MATCHED
;
359 if (opts
->source_tree
&& !(ce
->ce_flags
& CE_UPDATE
))
361 * In overlay mode, but the path is not in
362 * tree-ish, which means we should remove it
363 * from the index and the working tree.
365 ce
->ce_flags
|= CE_REMOVE
| CE_WT_REMOVE
;
369 static int checkout_worktree(const struct checkout_opts
*opts
,
370 const struct branch_info
*info
)
372 struct checkout state
= CHECKOUT_INIT
;
373 int nr_checkouts
= 0, nr_unmerged
= 0;
376 int pc_workers
, pc_threshold
;
377 struct mem_pool ce_mem_pool
;
380 state
.refresh_cache
= 1;
381 state
.istate
= &the_index
;
383 mem_pool_init(&ce_mem_pool
, 0);
384 get_parallel_checkout_configs(&pc_workers
, &pc_threshold
);
385 init_checkout_metadata(&state
.meta
, info
->refname
,
386 info
->commit
? &info
->commit
->object
.oid
: &info
->oid
,
389 enable_delayed_checkout(&state
);
392 init_parallel_checkout();
394 for (pos
= 0; pos
< active_nr
; pos
++) {
395 struct cache_entry
*ce
= active_cache
[pos
];
396 if (ce
->ce_flags
& CE_MATCHED
) {
398 errs
|= checkout_entry(ce
, &state
,
399 NULL
, &nr_checkouts
);
402 if (opts
->writeout_stage
)
403 errs
|= checkout_stage(opts
->writeout_stage
,
406 &nr_checkouts
, opts
->overlay_mode
);
407 else if (opts
->merge
)
408 errs
|= checkout_merged(pos
, &state
,
411 pos
= skip_same_name(ce
, pos
) - 1;
415 errs
|= run_parallel_checkout(&state
, pc_workers
, pc_threshold
,
417 mem_pool_discard(&ce_mem_pool
, should_validate_cache_entries());
418 remove_marked_cache_entries(&the_index
, 1);
419 remove_scheduled_dirs();
420 errs
|= finish_delayed_checkout(&state
, &nr_checkouts
, opts
->show_progress
);
422 if (opts
->count_checkout_paths
) {
424 fprintf_ln(stderr
, Q_("Recreated %d merge conflict",
425 "Recreated %d merge conflicts",
428 if (opts
->source_tree
)
429 fprintf_ln(stderr
, Q_("Updated %d path from %s",
430 "Updated %d paths from %s",
433 find_unique_abbrev(&opts
->source_tree
->object
.oid
,
435 else if (!nr_unmerged
|| nr_checkouts
)
436 fprintf_ln(stderr
, Q_("Updated %d path from the index",
437 "Updated %d paths from the index",
445 static int checkout_paths(const struct checkout_opts
*opts
,
446 const struct branch_info
*new_branch_info
)
449 static char *ps_matched
;
450 struct object_id rev
;
453 struct lock_file lock_file
= LOCK_INIT
;
456 trace2_cmd_mode(opts
->patch_mode
? "patch" : "path");
458 if (opts
->track
!= BRANCH_TRACK_UNSPECIFIED
)
459 die(_("'%s' cannot be used with updating paths"), "--track");
461 if (opts
->new_branch_log
)
462 die(_("'%s' cannot be used with updating paths"), "-l");
464 if (opts
->ignore_unmerged
&& opts
->patch_mode
)
465 die(_("'%s' cannot be used with updating paths"),
466 opts
->ignore_unmerged_opt
);
468 if (opts
->force_detach
)
469 die(_("'%s' cannot be used with updating paths"), "--detach");
471 if (opts
->merge
&& opts
->patch_mode
)
472 die(_("options '%s' and '%s' cannot be used together"), "--merge", "--patch");
474 if (opts
->ignore_unmerged
&& opts
->merge
)
475 die(_("options '%s' and '%s' cannot be used together"),
476 opts
->ignore_unmerged_opt
, "-m");
478 if (opts
->new_branch
)
479 die(_("Cannot update paths and switch to branch '%s' at the same time."),
482 if (!opts
->checkout_worktree
&& !opts
->checkout_index
)
483 die(_("neither '%s' or '%s' is specified"),
484 "--staged", "--worktree");
486 if (!opts
->checkout_worktree
&& !opts
->from_treeish
)
487 die(_("'%s' must be used when '%s' is not specified"),
488 "--worktree", "--source");
490 if (opts
->checkout_index
&& !opts
->checkout_worktree
&&
491 opts
->writeout_stage
)
492 die(_("'%s' or '%s' cannot be used with %s"),
493 "--ours", "--theirs", "--staged");
495 if (opts
->checkout_index
&& !opts
->checkout_worktree
&&
497 die(_("'%s' or '%s' cannot be used with %s"),
498 "--merge", "--conflict", "--staged");
500 if (opts
->patch_mode
) {
501 const char *patch_mode
;
502 const char *rev
= new_branch_info
->name
;
503 char rev_oid
[GIT_MAX_HEXSZ
+ 1];
506 * Since rev can be in the form of `<a>...<b>` (which is not
507 * recognized by diff-index), we will always replace the name
508 * with the hex of the commit (whether it's in `...` form or
509 * not) for the run_add_interactive() machinery to work
510 * properly. However, there is special logic for the HEAD case
511 * so we mustn't replace that. Also, when we were given a
512 * tree-object, new_branch_info->commit would be NULL, but we
513 * do not have to do any replacement, either.
515 if (rev
&& new_branch_info
->commit
&& strcmp(rev
, "HEAD"))
516 rev
= oid_to_hex_r(rev_oid
, &new_branch_info
->commit
->object
.oid
);
518 if (opts
->checkout_index
&& opts
->checkout_worktree
)
519 patch_mode
= "--patch=checkout";
520 else if (opts
->checkout_index
&& !opts
->checkout_worktree
)
521 patch_mode
= "--patch=reset";
522 else if (!opts
->checkout_index
&& opts
->checkout_worktree
)
523 patch_mode
= "--patch=worktree";
525 BUG("either flag must have been set, worktree=%d, index=%d",
526 opts
->checkout_worktree
, opts
->checkout_index
);
527 return run_add_interactive(rev
, patch_mode
, &opts
->pathspec
);
530 repo_hold_locked_index(the_repository
, &lock_file
, LOCK_DIE_ON_ERROR
);
531 if (read_cache_preload(&opts
->pathspec
) < 0)
532 return error(_("index file corrupt"));
534 if (opts
->source_tree
)
535 read_tree_some(opts
->source_tree
, &opts
->pathspec
);
537 ps_matched
= xcalloc(opts
->pathspec
.nr
, 1);
540 * Make sure all pathspecs participated in locating the paths
543 for (pos
= 0; pos
< active_nr
; pos
++)
544 if (opts
->overlay_mode
)
545 mark_ce_for_checkout_overlay(active_cache
[pos
],
549 mark_ce_for_checkout_no_overlay(active_cache
[pos
],
553 if (report_path_error(ps_matched
, &opts
->pathspec
)) {
559 /* "checkout -m path" to recreate conflicted state */
561 unmerge_marked_index(&the_index
);
563 /* Any unmerged paths? */
564 for (pos
= 0; pos
< active_nr
; pos
++) {
565 const struct cache_entry
*ce
= active_cache
[pos
];
566 if (ce
->ce_flags
& CE_MATCHED
) {
569 if (opts
->ignore_unmerged
) {
571 warning(_("path '%s' is unmerged"), ce
->name
);
572 } else if (opts
->writeout_stage
) {
573 errs
|= check_stage(opts
->writeout_stage
, ce
, pos
, opts
->overlay_mode
);
574 } else if (opts
->merge
) {
575 errs
|= check_stages((1<<2) | (1<<3), ce
, pos
);
578 error(_("path '%s' is unmerged"), ce
->name
);
580 pos
= skip_same_name(ce
, pos
) - 1;
586 /* Now we are committed to check them out */
587 if (opts
->checkout_worktree
)
588 errs
|= checkout_worktree(opts
, new_branch_info
);
590 remove_marked_cache_entries(&the_index
, 1);
593 * Allow updating the index when checking out from the index.
594 * This is to save new stat info.
596 if (opts
->checkout_worktree
&& !opts
->checkout_index
&& !opts
->source_tree
)
599 checkout_index
= opts
->checkout_index
;
601 if (checkout_index
) {
602 if (write_locked_index(&the_index
, &lock_file
, COMMIT_LOCK
))
603 die(_("unable to write new index file"));
606 * NEEDSWORK: if --worktree is not specified, we
607 * should save stat info of checked out files in the
608 * index to avoid the next (potentially costly)
609 * refresh. But it's a bit tricker to do...
611 rollback_lock_file(&lock_file
);
614 read_ref_full("HEAD", 0, &rev
, NULL
);
615 head
= lookup_commit_reference_gently(the_repository
, &rev
, 1);
617 errs
|= post_checkout_hook(head
, head
, 0);
621 static void show_local_changes(struct object
*head
,
622 const struct diff_options
*opts
)
625 /* I think we want full paths, even if we're in a subdirectory. */
626 repo_init_revisions(the_repository
, &rev
, NULL
);
627 rev
.diffopt
.flags
= opts
->flags
;
628 rev
.diffopt
.output_format
|= DIFF_FORMAT_NAME_STATUS
;
629 diff_setup_done(&rev
.diffopt
);
630 add_pending_object(&rev
, head
, NULL
);
631 run_diff_index(&rev
, 0);
632 object_array_clear(&rev
.pending
);
635 static void describe_detached_head(const char *msg
, struct commit
*commit
)
637 struct strbuf sb
= STRBUF_INIT
;
639 if (!parse_commit(commit
))
640 pp_commit_easy(CMIT_FMT_ONELINE
, commit
, &sb
);
641 if (print_sha1_ellipsis()) {
642 fprintf(stderr
, "%s %s... %s\n", msg
,
643 find_unique_abbrev(&commit
->object
.oid
, DEFAULT_ABBREV
), sb
.buf
);
645 fprintf(stderr
, "%s %s %s\n", msg
,
646 find_unique_abbrev(&commit
->object
.oid
, DEFAULT_ABBREV
), sb
.buf
);
651 static int reset_tree(struct tree
*tree
, const struct checkout_opts
*o
,
652 int worktree
, int *writeout_error
,
653 struct branch_info
*info
)
655 struct unpack_trees_options opts
;
656 struct tree_desc tree_desc
;
658 memset(&opts
, 0, sizeof(opts
));
660 opts
.update
= worktree
;
661 opts
.skip_unmerged
= !worktree
;
662 opts
.reset
= o
->force
? UNPACK_RESET_OVERWRITE_UNTRACKED
:
663 UNPACK_RESET_PROTECT_UNTRACKED
;
664 opts
.preserve_ignored
= (!o
->force
&& !o
->overwrite_ignore
);
666 opts
.fn
= oneway_merge
;
667 opts
.verbose_update
= o
->show_progress
;
668 opts
.src_index
= &the_index
;
669 opts
.dst_index
= &the_index
;
670 init_checkout_metadata(&opts
.meta
, info
->refname
,
671 info
->commit
? &info
->commit
->object
.oid
: null_oid(),
674 init_tree_desc(&tree_desc
, tree
->buffer
, tree
->size
);
675 switch (unpack_trees(1, &tree_desc
, &opts
)) {
679 * We return 0 nevertheless, as the index is all right
680 * and more importantly we have made best efforts to
681 * update paths in the work tree, and we cannot revert
692 static void setup_branch_path(struct branch_info
*branch
)
694 struct strbuf buf
= STRBUF_INIT
;
697 * If this is a ref, resolve it; otherwise, look up the OID for our
698 * expression. Failure here is okay.
700 if (!dwim_ref(branch
->name
, strlen(branch
->name
), &branch
->oid
, &branch
->refname
, 0))
701 repo_get_oid_committish(the_repository
, branch
->name
, &branch
->oid
);
703 strbuf_branchname(&buf
, branch
->name
, INTERPRET_BRANCH_LOCAL
);
704 if (strcmp(buf
.buf
, branch
->name
)) {
706 branch
->name
= xstrdup(buf
.buf
);
708 strbuf_splice(&buf
, 0, 0, "refs/heads/", 11);
710 branch
->path
= strbuf_detach(&buf
, NULL
);
713 static int merge_working_tree(const struct checkout_opts
*opts
,
714 struct branch_info
*old_branch_info
,
715 struct branch_info
*new_branch_info
,
719 struct lock_file lock_file
= LOCK_INIT
;
720 struct tree
*new_tree
;
722 hold_locked_index(&lock_file
, LOCK_DIE_ON_ERROR
);
723 if (read_cache_preload(NULL
) < 0)
724 return error(_("index file corrupt"));
726 resolve_undo_clear();
727 if (opts
->new_orphan_branch
&& opts
->orphan_from_empty_tree
) {
728 if (new_branch_info
->commit
)
729 BUG("'switch --orphan' should never accept a commit as starting point");
730 new_tree
= parse_tree_indirect(the_hash_algo
->empty_tree
);
732 new_tree
= get_commit_tree(new_branch_info
->commit
);
733 if (opts
->discard_changes
) {
734 ret
= reset_tree(new_tree
, opts
, 1, writeout_error
, new_branch_info
);
738 struct tree_desc trees
[2];
740 struct unpack_trees_options topts
;
742 memset(&topts
, 0, sizeof(topts
));
744 topts
.src_index
= &the_index
;
745 topts
.dst_index
= &the_index
;
747 setup_unpack_trees_porcelain(&topts
, "checkout");
749 refresh_cache(REFRESH_QUIET
);
751 if (unmerged_cache()) {
752 error(_("you need to resolve your current index first"));
756 /* 2-way merge to the new branch */
757 topts
.initial_checkout
= is_cache_unborn();
760 topts
.quiet
= opts
->merge
&& old_branch_info
->commit
;
761 topts
.verbose_update
= opts
->show_progress
;
762 topts
.fn
= twoway_merge
;
763 init_checkout_metadata(&topts
.meta
, new_branch_info
->refname
,
764 new_branch_info
->commit
?
765 &new_branch_info
->commit
->object
.oid
:
766 &new_branch_info
->oid
, NULL
);
767 topts
.preserve_ignored
= !opts
->overwrite_ignore
;
768 tree
= parse_tree_indirect(old_branch_info
->commit
?
769 &old_branch_info
->commit
->object
.oid
:
770 the_hash_algo
->empty_tree
);
771 init_tree_desc(&trees
[0], tree
->buffer
, tree
->size
);
772 parse_tree(new_tree
);
774 init_tree_desc(&trees
[1], tree
->buffer
, tree
->size
);
776 ret
= unpack_trees(2, trees
, &topts
);
777 clear_unpack_trees_porcelain(&topts
);
780 * Unpack couldn't do a trivial merge; either
781 * give up or do a real merge, depending on
782 * whether the merge flag was used.
785 struct tree
*old_tree
;
786 struct merge_options o
;
787 struct strbuf sb
= STRBUF_INIT
;
788 struct strbuf old_commit_shortname
= STRBUF_INIT
;
794 * Without old_branch_info->commit, the below is the same as
795 * the two-tree unpack we already tried and failed.
797 if (!old_branch_info
->commit
)
799 old_tree
= get_commit_tree(old_branch_info
->commit
);
801 if (repo_index_has_changes(the_repository
, old_tree
, &sb
))
802 die(_("cannot continue with staged changes in "
803 "the following files:\n%s"), sb
.buf
);
806 /* Do more real merge */
809 * We update the index fully, then write the
810 * tree from the index, then merge the new
811 * branch with the current tree, with the old
812 * branch as the base. Then we reset the index
813 * (but not the working tree) to the new
814 * branch, leaving the working tree as the
815 * merged version, but skipping unmerged
816 * entries in the index.
819 add_files_to_cache(NULL
, NULL
, 0);
820 init_merge_options(&o
, the_repository
);
822 work
= write_in_core_index_as_tree(the_repository
);
824 ret
= reset_tree(new_tree
,
826 writeout_error
, new_branch_info
);
829 o
.ancestor
= old_branch_info
->name
;
830 if (old_branch_info
->name
== NULL
) {
831 strbuf_add_unique_abbrev(&old_commit_shortname
,
832 &old_branch_info
->commit
->object
.oid
,
834 o
.ancestor
= old_commit_shortname
.buf
;
836 o
.branch1
= new_branch_info
->name
;
838 ret
= merge_trees(&o
,
844 ret
= reset_tree(new_tree
,
846 writeout_error
, new_branch_info
);
847 strbuf_release(&o
.obuf
);
848 strbuf_release(&old_commit_shortname
);
854 if (!cache_tree_fully_valid(active_cache_tree
))
855 cache_tree_update(&the_index
, WRITE_TREE_SILENT
| WRITE_TREE_REPAIR
);
857 if (write_locked_index(&the_index
, &lock_file
, COMMIT_LOCK
))
858 die(_("unable to write new index file"));
860 if (!opts
->discard_changes
&& !opts
->quiet
&& new_branch_info
->commit
)
861 show_local_changes(&new_branch_info
->commit
->object
, &opts
->diff_options
);
866 static void report_tracking(struct branch_info
*new_branch_info
)
868 struct strbuf sb
= STRBUF_INIT
;
869 struct branch
*branch
= branch_get(new_branch_info
->name
);
871 if (!format_tracking_info(branch
, &sb
, AHEAD_BEHIND_FULL
))
873 fputs(sb
.buf
, stdout
);
877 static void update_refs_for_switch(const struct checkout_opts
*opts
,
878 struct branch_info
*old_branch_info
,
879 struct branch_info
*new_branch_info
)
881 struct strbuf msg
= STRBUF_INIT
;
882 const char *old_desc
, *reflog_msg
;
883 if (opts
->new_branch
) {
884 if (opts
->new_orphan_branch
) {
887 refname
= mkpathdup("refs/heads/%s", opts
->new_orphan_branch
);
888 if (opts
->new_branch_log
&&
889 !should_autocreate_reflog(refname
)) {
891 struct strbuf err
= STRBUF_INIT
;
893 ret
= safe_create_reflog(refname
, &err
);
895 fprintf(stderr
, _("Can not do reflog for '%s': %s\n"),
896 opts
->new_orphan_branch
, err
.buf
);
897 strbuf_release(&err
);
901 strbuf_release(&err
);
906 create_branch(the_repository
,
907 opts
->new_branch
, new_branch_info
->name
,
908 opts
->new_branch_force
? 1 : 0,
909 opts
->new_branch_force
? 1 : 0,
910 opts
->new_branch_log
,
914 free(new_branch_info
->name
);
915 free(new_branch_info
->refname
);
916 new_branch_info
->name
= xstrdup(opts
->new_branch
);
917 setup_branch_path(new_branch_info
);
920 old_desc
= old_branch_info
->name
;
921 if (!old_desc
&& old_branch_info
->commit
)
922 old_desc
= oid_to_hex(&old_branch_info
->commit
->object
.oid
);
924 reflog_msg
= getenv("GIT_REFLOG_ACTION");
926 strbuf_addf(&msg
, "checkout: moving from %s to %s",
927 old_desc
? old_desc
: "(invalid)", new_branch_info
->name
);
929 strbuf_insertstr(&msg
, 0, reflog_msg
);
931 if (!strcmp(new_branch_info
->name
, "HEAD") && !new_branch_info
->path
&& !opts
->force_detach
) {
933 } else if (opts
->force_detach
|| !new_branch_info
->path
) { /* No longer on any branch. */
934 update_ref(msg
.buf
, "HEAD", &new_branch_info
->commit
->object
.oid
, NULL
,
935 REF_NO_DEREF
, UPDATE_REFS_DIE_ON_ERR
);
937 if (old_branch_info
->path
&&
938 advice_enabled(ADVICE_DETACHED_HEAD
) && !opts
->force_detach
)
939 detach_advice(new_branch_info
->name
);
940 describe_detached_head(_("HEAD is now at"), new_branch_info
->commit
);
942 } else if (new_branch_info
->path
) { /* Switch branches. */
943 if (create_symref("HEAD", new_branch_info
->path
, msg
.buf
) < 0)
944 die(_("unable to update HEAD"));
946 if (old_branch_info
->path
&& !strcmp(new_branch_info
->path
, old_branch_info
->path
)) {
947 if (opts
->new_branch_force
)
948 fprintf(stderr
, _("Reset branch '%s'\n"),
949 new_branch_info
->name
);
951 fprintf(stderr
, _("Already on '%s'\n"),
952 new_branch_info
->name
);
953 } else if (opts
->new_branch
) {
954 if (opts
->branch_exists
)
955 fprintf(stderr
, _("Switched to and reset branch '%s'\n"), new_branch_info
->name
);
957 fprintf(stderr
, _("Switched to a new branch '%s'\n"), new_branch_info
->name
);
959 fprintf(stderr
, _("Switched to branch '%s'\n"),
960 new_branch_info
->name
);
963 if (old_branch_info
->path
&& old_branch_info
->name
) {
964 if (!ref_exists(old_branch_info
->path
) && reflog_exists(old_branch_info
->path
))
965 delete_reflog(old_branch_info
->path
);
968 remove_branch_state(the_repository
, !opts
->quiet
);
969 strbuf_release(&msg
);
971 (new_branch_info
->path
|| (!opts
->force_detach
&& !strcmp(new_branch_info
->name
, "HEAD"))))
972 report_tracking(new_branch_info
);
975 static int add_pending_uninteresting_ref(const char *refname
,
976 const struct object_id
*oid
,
977 int flags
, void *cb_data
)
979 add_pending_oid(cb_data
, refname
, oid
, UNINTERESTING
);
983 static void describe_one_orphan(struct strbuf
*sb
, struct commit
*commit
)
985 strbuf_addstr(sb
, " ");
986 strbuf_add_unique_abbrev(sb
, &commit
->object
.oid
, DEFAULT_ABBREV
);
987 strbuf_addch(sb
, ' ');
988 if (!parse_commit(commit
))
989 pp_commit_easy(CMIT_FMT_ONELINE
, commit
, sb
);
990 strbuf_addch(sb
, '\n');
993 #define ORPHAN_CUTOFF 4
994 static void suggest_reattach(struct commit
*commit
, struct rev_info
*revs
)
996 struct commit
*c
, *last
= NULL
;
997 struct strbuf sb
= STRBUF_INIT
;
999 while ((c
= get_revision(revs
)) != NULL
) {
1000 if (lost
< ORPHAN_CUTOFF
)
1001 describe_one_orphan(&sb
, c
);
1005 if (ORPHAN_CUTOFF
< lost
) {
1006 int more
= lost
- ORPHAN_CUTOFF
;
1008 describe_one_orphan(&sb
, last
);
1010 strbuf_addf(&sb
, _(" ... and %d more.\n"), more
);
1015 /* The singular version */
1016 "Warning: you are leaving %d commit behind, "
1017 "not connected to\n"
1018 "any of your branches:\n\n"
1020 /* The plural version */
1021 "Warning: you are leaving %d commits behind, "
1022 "not connected to\n"
1023 "any of your branches:\n\n"
1025 /* Give ngettext() the count */
1029 strbuf_release(&sb
);
1031 if (advice_enabled(ADVICE_DETACHED_HEAD
))
1034 /* The singular version */
1035 "If you want to keep it by creating a new branch, "
1036 "this may be a good time\nto do so with:\n\n"
1037 " git branch <new-branch-name> %s\n\n",
1038 /* The plural version */
1039 "If you want to keep them by creating a new branch, "
1040 "this may be a good time\nto do so with:\n\n"
1041 " git branch <new-branch-name> %s\n\n",
1042 /* Give ngettext() the count */
1044 find_unique_abbrev(&commit
->object
.oid
, DEFAULT_ABBREV
));
1048 * We are about to leave commit that was at the tip of a detached
1049 * HEAD. If it is not reachable from any ref, this is the last chance
1050 * for the user to do so without resorting to reflog.
1052 static void orphaned_commit_warning(struct commit
*old_commit
, struct commit
*new_commit
)
1054 struct rev_info revs
;
1055 struct object
*object
= &old_commit
->object
;
1057 repo_init_revisions(the_repository
, &revs
, NULL
);
1058 setup_revisions(0, NULL
, &revs
, NULL
);
1060 object
->flags
&= ~UNINTERESTING
;
1061 add_pending_object(&revs
, object
, oid_to_hex(&object
->oid
));
1063 for_each_ref(add_pending_uninteresting_ref
, &revs
);
1065 add_pending_oid(&revs
, "HEAD",
1066 &new_commit
->object
.oid
,
1069 if (prepare_revision_walk(&revs
))
1070 die(_("internal error in revision walk"));
1071 if (!(old_commit
->object
.flags
& UNINTERESTING
))
1072 suggest_reattach(old_commit
, &revs
);
1074 describe_detached_head(_("Previous HEAD position was"), old_commit
);
1076 /* Clean up objects used, as they will be reused. */
1077 repo_clear_commit_marks(the_repository
, ALL_REV_FLAGS
);
1080 static int switch_branches(const struct checkout_opts
*opts
,
1081 struct branch_info
*new_branch_info
)
1084 struct branch_info old_branch_info
= { 0 };
1085 struct object_id rev
;
1086 int flag
, writeout_error
= 0;
1089 trace2_cmd_mode("branch");
1091 memset(&old_branch_info
, 0, sizeof(old_branch_info
));
1092 old_branch_info
.path
= resolve_refdup("HEAD", 0, &rev
, &flag
);
1093 if (old_branch_info
.path
)
1094 old_branch_info
.commit
= lookup_commit_reference_gently(the_repository
, &rev
, 1);
1095 if (!(flag
& REF_ISSYMREF
))
1096 FREE_AND_NULL(old_branch_info
.path
);
1098 if (old_branch_info
.path
) {
1099 const char *const prefix
= "refs/heads/";
1101 if (skip_prefix(old_branch_info
.path
, prefix
, &p
))
1102 old_branch_info
.name
= xstrdup(p
);
1105 if (opts
->new_orphan_branch
&& opts
->orphan_from_empty_tree
) {
1106 if (new_branch_info
->name
)
1107 BUG("'switch --orphan' should never accept a commit as starting point");
1108 new_branch_info
->commit
= NULL
;
1109 new_branch_info
->name
= xstrdup("(empty)");
1113 if (!new_branch_info
->name
) {
1114 new_branch_info
->name
= xstrdup("HEAD");
1115 new_branch_info
->commit
= old_branch_info
.commit
;
1116 if (!new_branch_info
->commit
)
1117 die(_("You are on a branch yet to be born"));
1118 parse_commit_or_die(new_branch_info
->commit
);
1120 if (opts
->only_merge_on_switching_branches
)
1125 ret
= merge_working_tree(opts
, &old_branch_info
, new_branch_info
, &writeout_error
);
1127 branch_info_release(&old_branch_info
);
1132 if (!opts
->quiet
&& !old_branch_info
.path
&& old_branch_info
.commit
&& new_branch_info
->commit
!= old_branch_info
.commit
)
1133 orphaned_commit_warning(old_branch_info
.commit
, new_branch_info
->commit
);
1135 update_refs_for_switch(opts
, &old_branch_info
, new_branch_info
);
1137 ret
= post_checkout_hook(old_branch_info
.commit
, new_branch_info
->commit
, 1);
1138 branch_info_release(&old_branch_info
);
1140 return ret
|| writeout_error
;
1143 static int git_checkout_config(const char *var
, const char *value
, void *cb
)
1145 struct checkout_opts
*opts
= cb
;
1147 if (!strcmp(var
, "diff.ignoresubmodules")) {
1148 handle_ignore_submodules_arg(&opts
->diff_options
, value
);
1151 if (!strcmp(var
, "checkout.guess")) {
1152 opts
->dwim_new_local_branch
= git_config_bool(var
, value
);
1156 if (starts_with(var
, "submodule."))
1157 return git_default_submodule_config(var
, value
, NULL
);
1159 return git_xmerge_config(var
, value
, NULL
);
1162 static void setup_new_branch_info_and_source_tree(
1163 struct branch_info
*new_branch_info
,
1164 struct checkout_opts
*opts
,
1165 struct object_id
*rev
,
1168 struct tree
**source_tree
= &opts
->source_tree
;
1169 struct object_id branch_rev
;
1171 new_branch_info
->name
= xstrdup(arg
);
1172 setup_branch_path(new_branch_info
);
1174 if (!check_refname_format(new_branch_info
->path
, 0) &&
1175 !read_ref(new_branch_info
->path
, &branch_rev
))
1176 oidcpy(rev
, &branch_rev
);
1178 /* not an existing branch */
1179 FREE_AND_NULL(new_branch_info
->path
);
1181 new_branch_info
->commit
= lookup_commit_reference_gently(the_repository
, rev
, 1);
1182 if (!new_branch_info
->commit
) {
1184 *source_tree
= parse_tree_indirect(rev
);
1186 parse_commit_or_die(new_branch_info
->commit
);
1187 *source_tree
= get_commit_tree(new_branch_info
->commit
);
1191 static const char *parse_remote_branch(const char *arg
,
1192 struct object_id
*rev
,
1193 int could_be_checkout_paths
)
1195 int num_matches
= 0;
1196 const char *remote
= unique_tracking_name(arg
, rev
, &num_matches
);
1198 if (remote
&& could_be_checkout_paths
) {
1199 die(_("'%s' could be both a local file and a tracking branch.\n"
1200 "Please use -- (and optionally --no-guess) to disambiguate"),
1204 if (!remote
&& num_matches
> 1) {
1205 if (advice_enabled(ADVICE_CHECKOUT_AMBIGUOUS_REMOTE_BRANCH_NAME
)) {
1206 advise(_("If you meant to check out a remote tracking branch on, e.g. 'origin',\n"
1207 "you can do so by fully qualifying the name with the --track option:\n"
1209 " git checkout --track origin/<name>\n"
1211 "If you'd like to always have checkouts of an ambiguous <name> prefer\n"
1212 "one remote, e.g. the 'origin' remote, consider setting\n"
1213 "checkout.defaultRemote=origin in your config."));
1216 die(_("'%s' matched multiple (%d) remote tracking branches"),
1223 static int parse_branchname_arg(int argc
, const char **argv
,
1224 int dwim_new_local_branch_ok
,
1225 struct branch_info
*new_branch_info
,
1226 struct checkout_opts
*opts
,
1227 struct object_id
*rev
)
1229 const char **new_branch
= &opts
->new_branch
;
1233 int has_dash_dash
= 0;
1237 * case 1: git checkout <ref> -- [<paths>]
1239 * <ref> must be a valid tree, everything after the '--' must be
1242 * case 2: git checkout -- [<paths>]
1244 * everything after the '--' must be paths.
1246 * case 3: git checkout <something> [--]
1248 * (a) If <something> is a commit, that is to
1249 * switch to the branch or detach HEAD at it. As a special case,
1250 * if <something> is A...B (missing A or B means HEAD but you can
1251 * omit at most one side), and if there is a unique merge base
1252 * between A and B, A...B names that merge base.
1254 * (b) If <something> is _not_ a commit, either "--" is present
1255 * or <something> is not a path, no -t or -b was given, and
1256 * and there is a tracking branch whose name is <something>
1257 * in one and only one remote (or if the branch exists on the
1258 * remote named in checkout.defaultRemote), then this is a
1259 * short-hand to fork local <something> from that
1260 * remote-tracking branch.
1262 * (c) Otherwise, if "--" is present, treat it like case (1).
1265 * - if it's a reference, treat it like case (1)
1266 * - else if it's a path, treat it like case (2)
1269 * case 4: git checkout <something> <paths>
1271 * The first argument must not be ambiguous.
1272 * - If it's *only* a reference, treat it like case (1).
1273 * - If it's only a path, treat it like case (2).
1280 if (!opts
->accept_pathspec
) {
1282 die(_("only one reference expected"));
1283 has_dash_dash
= 1; /* helps disambiguate */
1288 for (i
= 0; i
< argc
; i
++) {
1289 if (opts
->accept_pathspec
&& !strcmp(argv
[i
], "--")) {
1294 if (dash_dash_pos
== 0)
1295 return 1; /* case (2) */
1296 else if (dash_dash_pos
== 1)
1297 has_dash_dash
= 1; /* case (3) or (1) */
1298 else if (dash_dash_pos
>= 2)
1299 die(_("only one reference expected, %d given."), dash_dash_pos
);
1300 opts
->count_checkout_paths
= !opts
->quiet
&& !has_dash_dash
;
1302 if (!strcmp(arg
, "-"))
1305 if (get_oid_mb(arg
, rev
)) {
1307 * Either case (3) or (4), with <something> not being
1308 * a commit, or an attempt to use case (1) with an
1311 * It's likely an error, but we need to find out if
1312 * we should auto-create the branch, case (3).(b).
1314 int recover_with_dwim
= dwim_new_local_branch_ok
;
1316 int could_be_checkout_paths
= !has_dash_dash
&&
1317 check_filename(opts
->prefix
, arg
);
1319 if (!has_dash_dash
&& !no_wildcard(arg
))
1320 recover_with_dwim
= 0;
1323 * Accept "git checkout foo", "git checkout foo --"
1324 * and "git switch foo" as candidates for dwim.
1326 if (!(argc
== 1 && !has_dash_dash
) &&
1327 !(argc
== 2 && has_dash_dash
) &&
1328 opts
->accept_pathspec
)
1329 recover_with_dwim
= 0;
1331 if (recover_with_dwim
) {
1332 const char *remote
= parse_remote_branch(arg
, rev
,
1333 could_be_checkout_paths
);
1337 /* DWIMmed to create local branch, case (3).(b) */
1339 recover_with_dwim
= 0;
1343 if (!recover_with_dwim
) {
1345 die(_("invalid reference: %s"), arg
);
1350 /* we can't end up being in (2) anymore, eat the argument */
1355 setup_new_branch_info_and_source_tree(new_branch_info
, opts
, rev
, arg
);
1357 if (!opts
->source_tree
) /* case (1): want a tree */
1358 die(_("reference is not a tree: %s"), arg
);
1360 if (!has_dash_dash
) { /* case (3).(d) -> (1) */
1362 * Do not complain the most common case
1363 * git checkout branch
1364 * even if there happen to be a file called 'branch';
1365 * it would be extremely annoying.
1368 verify_non_filename(opts
->prefix
, arg
);
1369 } else if (opts
->accept_pathspec
) {
1378 static int switch_unborn_to_new_branch(const struct checkout_opts
*opts
)
1381 struct strbuf branch_ref
= STRBUF_INIT
;
1383 trace2_cmd_mode("unborn");
1385 if (!opts
->new_branch
)
1386 die(_("You are on a branch yet to be born"));
1387 strbuf_addf(&branch_ref
, "refs/heads/%s", opts
->new_branch
);
1388 status
= create_symref("HEAD", branch_ref
.buf
, "checkout -b");
1389 strbuf_release(&branch_ref
);
1391 fprintf(stderr
, _("Switched to a new branch '%s'\n"),
1396 static void die_expecting_a_branch(const struct branch_info
*branch_info
)
1398 struct object_id oid
;
1401 if (dwim_ref(branch_info
->name
, strlen(branch_info
->name
), &oid
, &to_free
, 0) == 1) {
1402 const char *ref
= to_free
;
1404 if (skip_prefix(ref
, "refs/tags/", &ref
))
1405 die(_("a branch is expected, got tag '%s'"), ref
);
1406 if (skip_prefix(ref
, "refs/remotes/", &ref
))
1407 die(_("a branch is expected, got remote branch '%s'"), ref
);
1408 die(_("a branch is expected, got '%s'"), ref
);
1410 if (branch_info
->commit
)
1411 die(_("a branch is expected, got commit '%s'"), branch_info
->name
);
1413 * This case should never happen because we already die() on
1414 * non-commit, but just in case.
1416 die(_("a branch is expected, got '%s'"), branch_info
->name
);
1419 static void die_if_some_operation_in_progress(void)
1421 struct wt_status_state state
;
1423 memset(&state
, 0, sizeof(state
));
1424 wt_status_get_state(the_repository
, &state
, 0);
1426 if (state
.merge_in_progress
)
1427 die(_("cannot switch branch while merging\n"
1428 "Consider \"git merge --quit\" "
1429 "or \"git worktree add\"."));
1430 if (state
.am_in_progress
)
1431 die(_("cannot switch branch in the middle of an am session\n"
1432 "Consider \"git am --quit\" "
1433 "or \"git worktree add\"."));
1434 if (state
.rebase_interactive_in_progress
|| state
.rebase_in_progress
)
1435 die(_("cannot switch branch while rebasing\n"
1436 "Consider \"git rebase --quit\" "
1437 "or \"git worktree add\"."));
1438 if (state
.cherry_pick_in_progress
)
1439 die(_("cannot switch branch while cherry-picking\n"
1440 "Consider \"git cherry-pick --quit\" "
1441 "or \"git worktree add\"."));
1442 if (state
.revert_in_progress
)
1443 die(_("cannot switch branch while reverting\n"
1444 "Consider \"git revert --quit\" "
1445 "or \"git worktree add\"."));
1446 if (state
.bisect_in_progress
)
1447 warning(_("you are switching branch while bisecting"));
1450 static int checkout_branch(struct checkout_opts
*opts
,
1451 struct branch_info
*new_branch_info
)
1453 if (opts
->pathspec
.nr
)
1454 die(_("paths cannot be used with switching branches"));
1456 if (opts
->patch_mode
)
1457 die(_("'%s' cannot be used with switching branches"),
1460 if (opts
->overlay_mode
!= -1)
1461 die(_("'%s' cannot be used with switching branches"),
1464 if (opts
->writeout_stage
)
1465 die(_("'%s' cannot be used with switching branches"),
1468 if (opts
->force
&& opts
->merge
)
1469 die(_("'%s' cannot be used with '%s'"), "-f", "-m");
1471 if (opts
->discard_changes
&& opts
->merge
)
1472 die(_("'%s' cannot be used with '%s'"), "--discard-changes", "--merge");
1474 if (opts
->force_detach
&& opts
->new_branch
)
1475 die(_("'%s' cannot be used with '%s'"),
1476 "--detach", "-b/-B/--orphan");
1478 if (opts
->new_orphan_branch
) {
1479 if (opts
->track
!= BRANCH_TRACK_UNSPECIFIED
)
1480 die(_("'%s' cannot be used with '%s'"), "--orphan", "-t");
1481 if (opts
->orphan_from_empty_tree
&& new_branch_info
->name
)
1482 die(_("'%s' cannot take <start-point>"), "--orphan");
1483 } else if (opts
->force_detach
) {
1484 if (opts
->track
!= BRANCH_TRACK_UNSPECIFIED
)
1485 die(_("'%s' cannot be used with '%s'"), "--detach", "-t");
1486 } else if (opts
->track
== BRANCH_TRACK_UNSPECIFIED
)
1487 opts
->track
= git_branch_track
;
1489 if (new_branch_info
->name
&& !new_branch_info
->commit
)
1490 die(_("Cannot switch branch to a non-commit '%s'"),
1491 new_branch_info
->name
);
1493 if (!opts
->switch_branch_doing_nothing_is_ok
&&
1494 !new_branch_info
->name
&&
1495 !opts
->new_branch
&&
1496 !opts
->force_detach
)
1497 die(_("missing branch or commit argument"));
1499 if (!opts
->implicit_detach
&&
1500 !opts
->force_detach
&&
1501 !opts
->new_branch
&&
1502 !opts
->new_branch_force
&&
1503 new_branch_info
->name
&&
1504 !new_branch_info
->path
)
1505 die_expecting_a_branch(new_branch_info
);
1507 if (!opts
->can_switch_when_in_progress
)
1508 die_if_some_operation_in_progress();
1510 if (new_branch_info
->path
&& !opts
->force_detach
&& !opts
->new_branch
&&
1511 !opts
->ignore_other_worktrees
) {
1513 char *head_ref
= resolve_refdup("HEAD", 0, NULL
, &flag
);
1515 (!(flag
& REF_ISSYMREF
) || strcmp(head_ref
, new_branch_info
->path
)))
1516 die_if_checked_out(new_branch_info
->path
, 1);
1520 if (!new_branch_info
->commit
&& opts
->new_branch
) {
1521 struct object_id rev
;
1524 if (!read_ref_full("HEAD", 0, &rev
, &flag
) &&
1525 (flag
& REF_ISSYMREF
) && is_null_oid(&rev
))
1526 return switch_unborn_to_new_branch(opts
);
1528 return switch_branches(opts
, new_branch_info
);
1531 static struct option
*add_common_options(struct checkout_opts
*opts
,
1532 struct option
*prevopts
)
1534 struct option options
[] = {
1535 OPT__QUIET(&opts
->quiet
, N_("suppress progress reporting")),
1536 OPT_CALLBACK_F(0, "recurse-submodules", NULL
,
1537 "checkout", "control recursive updating of submodules",
1538 PARSE_OPT_OPTARG
, option_parse_recurse_submodules_worktree_updater
),
1539 OPT_BOOL(0, "progress", &opts
->show_progress
, N_("force progress reporting")),
1540 OPT_BOOL('m', "merge", &opts
->merge
, N_("perform a 3-way merge with the new branch")),
1541 OPT_STRING(0, "conflict", &opts
->conflict_style
, N_("style"),
1542 N_("conflict style (merge, diff3, or zdiff3)")),
1545 struct option
*newopts
= parse_options_concat(prevopts
, options
);
1550 static struct option
*add_common_switch_branch_options(
1551 struct checkout_opts
*opts
, struct option
*prevopts
)
1553 struct option options
[] = {
1554 OPT_BOOL('d', "detach", &opts
->force_detach
, N_("detach HEAD at named commit")),
1555 OPT_CALLBACK_F('t', "track", &opts
->track
, "(direct|inherit)",
1556 N_("set branch tracking configuration"),
1558 parse_opt_tracking_mode
),
1559 OPT__FORCE(&opts
->force
, N_("force checkout (throw away local modifications)"),
1560 PARSE_OPT_NOCOMPLETE
),
1561 OPT_STRING(0, "orphan", &opts
->new_orphan_branch
, N_("new-branch"), N_("new unparented branch")),
1562 OPT_BOOL_F(0, "overwrite-ignore", &opts
->overwrite_ignore
,
1563 N_("update ignored files (default)"),
1564 PARSE_OPT_NOCOMPLETE
),
1565 OPT_BOOL(0, "ignore-other-worktrees", &opts
->ignore_other_worktrees
,
1566 N_("do not check if another worktree is holding the given ref")),
1569 struct option
*newopts
= parse_options_concat(prevopts
, options
);
1574 static struct option
*add_checkout_path_options(struct checkout_opts
*opts
,
1575 struct option
*prevopts
)
1577 struct option options
[] = {
1578 OPT_SET_INT_F('2', "ours", &opts
->writeout_stage
,
1579 N_("checkout our version for unmerged files"),
1580 2, PARSE_OPT_NONEG
),
1581 OPT_SET_INT_F('3', "theirs", &opts
->writeout_stage
,
1582 N_("checkout their version for unmerged files"),
1583 3, PARSE_OPT_NONEG
),
1584 OPT_BOOL('p', "patch", &opts
->patch_mode
, N_("select hunks interactively")),
1585 OPT_BOOL(0, "ignore-skip-worktree-bits", &opts
->ignore_skipworktree
,
1586 N_("do not limit pathspecs to sparse entries only")),
1587 OPT_PATHSPEC_FROM_FILE(&opts
->pathspec_from_file
),
1588 OPT_PATHSPEC_FILE_NUL(&opts
->pathspec_file_nul
),
1591 struct option
*newopts
= parse_options_concat(prevopts
, options
);
1596 /* create-branch option (either b or c) */
1597 static char cb_option
= 'b';
1599 static int checkout_main(int argc
, const char **argv
, const char *prefix
,
1600 struct checkout_opts
*opts
, struct option
*options
,
1601 const char * const usagestr
[],
1602 struct branch_info
*new_branch_info
)
1604 int parseopt_flags
= 0;
1606 opts
->overwrite_ignore
= 1;
1607 opts
->prefix
= prefix
;
1608 opts
->show_progress
= -1;
1610 git_config(git_checkout_config
, opts
);
1611 if (the_repository
->gitdir
) {
1612 prepare_repo_settings(the_repository
);
1613 the_repository
->settings
.command_requires_full_index
= 0;
1616 opts
->track
= BRANCH_TRACK_UNSPECIFIED
;
1618 if (!opts
->accept_pathspec
&& !opts
->accept_ref
)
1619 BUG("make up your mind, you need to take _something_");
1620 if (opts
->accept_pathspec
&& opts
->accept_ref
)
1621 parseopt_flags
= PARSE_OPT_KEEP_DASHDASH
;
1623 argc
= parse_options(argc
, argv
, prefix
, options
,
1624 usagestr
, parseopt_flags
);
1626 if (opts
->show_progress
< 0) {
1628 opts
->show_progress
= 0;
1630 opts
->show_progress
= isatty(2);
1633 if (opts
->conflict_style
) {
1634 opts
->merge
= 1; /* implied */
1635 git_xmerge_config("merge.conflictstyle", opts
->conflict_style
, NULL
);
1638 opts
->discard_changes
= 1;
1639 opts
->ignore_unmerged_opt
= "--force";
1640 opts
->ignore_unmerged
= 1;
1643 if ((!!opts
->new_branch
+ !!opts
->new_branch_force
+ !!opts
->new_orphan_branch
) > 1)
1644 die(_("options '-%c', '-%c', and '%s' cannot be used together"),
1645 cb_option
, toupper(cb_option
), "--orphan");
1647 if (opts
->overlay_mode
== 1 && opts
->patch_mode
)
1648 die(_("options '%s' and '%s' cannot be used together"), "-p", "--overlay");
1650 if (opts
->checkout_index
>= 0 || opts
->checkout_worktree
>= 0) {
1651 if (opts
->checkout_index
< 0)
1652 opts
->checkout_index
= 0;
1653 if (opts
->checkout_worktree
< 0)
1654 opts
->checkout_worktree
= 0;
1656 if (opts
->checkout_index
< 0)
1657 opts
->checkout_index
= -opts
->checkout_index
- 1;
1658 if (opts
->checkout_worktree
< 0)
1659 opts
->checkout_worktree
= -opts
->checkout_worktree
- 1;
1661 if (opts
->checkout_index
< 0 || opts
->checkout_worktree
< 0)
1662 BUG("these flags should be non-negative by now");
1664 * convenient shortcut: "git restore --staged [--worktree]" equals
1665 * "git restore --staged [--worktree] --source HEAD"
1667 if (!opts
->from_treeish
&& opts
->checkout_index
)
1668 opts
->from_treeish
= "HEAD";
1671 * From here on, new_branch will contain the branch to be checked out,
1672 * and new_branch_force and new_orphan_branch will tell us which one of
1673 * -b/-B/-c/-C/--orphan is being used.
1675 if (opts
->new_branch_force
)
1676 opts
->new_branch
= opts
->new_branch_force
;
1678 if (opts
->new_orphan_branch
)
1679 opts
->new_branch
= opts
->new_orphan_branch
;
1681 /* --track without -c/-C/-b/-B/--orphan should DWIM */
1682 if (opts
->track
!= BRANCH_TRACK_UNSPECIFIED
&& !opts
->new_branch
) {
1683 const char *argv0
= argv
[0];
1684 if (!argc
|| !strcmp(argv0
, "--"))
1685 die(_("--track needs a branch name"));
1686 skip_prefix(argv0
, "refs/", &argv0
);
1687 skip_prefix(argv0
, "remotes/", &argv0
);
1688 argv0
= strchr(argv0
, '/');
1689 if (!argv0
|| !argv0
[1])
1690 die(_("missing branch name; try -%c"), cb_option
);
1691 opts
->new_branch
= argv0
+ 1;
1695 * Extract branch name from command line arguments, so
1696 * all that is left is pathspecs.
1700 * 1) git checkout <tree> -- [<paths>]
1701 * 2) git checkout -- [<paths>]
1702 * 3) git checkout <something> [<paths>]
1704 * including "last branch" syntax and DWIM-ery for names of
1705 * remote branches, erroring out for invalid or ambiguous cases.
1707 if (argc
&& opts
->accept_ref
) {
1708 struct object_id rev
;
1710 !opts
->patch_mode
&&
1711 opts
->dwim_new_local_branch
&&
1712 opts
->track
== BRANCH_TRACK_UNSPECIFIED
&&
1714 int n
= parse_branchname_arg(argc
, argv
, dwim_ok
,
1715 new_branch_info
, opts
, &rev
);
1718 } else if (!opts
->accept_ref
&& opts
->from_treeish
) {
1719 struct object_id rev
;
1721 if (get_oid_mb(opts
->from_treeish
, &rev
))
1722 die(_("could not resolve %s"), opts
->from_treeish
);
1724 setup_new_branch_info_and_source_tree(new_branch_info
,
1726 opts
->from_treeish
);
1728 if (!opts
->source_tree
)
1729 die(_("reference is not a tree: %s"), opts
->from_treeish
);
1733 parse_pathspec(&opts
->pathspec
, 0,
1734 opts
->patch_mode
? PATHSPEC_PREFIX_ORIGIN
: 0,
1737 if (!opts
->pathspec
.nr
)
1738 die(_("invalid path specification"));
1741 * Try to give more helpful suggestion.
1742 * new_branch && argc > 1 will be caught later.
1744 if (opts
->new_branch
&& argc
== 1 && !new_branch_info
->commit
)
1745 die(_("'%s' is not a commit and a branch '%s' cannot be created from it"),
1746 argv
[0], opts
->new_branch
);
1748 if (opts
->force_detach
)
1749 die(_("git checkout: --detach does not take a path argument '%s'"),
1753 if (opts
->pathspec_from_file
) {
1754 if (opts
->pathspec
.nr
)
1755 die(_("'%s' and pathspec arguments cannot be used together"), "--pathspec-from-file");
1757 if (opts
->force_detach
)
1758 die(_("options '%s' and '%s' cannot be used together"), "--pathspec-from-file", "--detach");
1760 if (opts
->patch_mode
)
1761 die(_("options '%s' and '%s' cannot be used together"), "--pathspec-from-file", "--patch");
1763 parse_pathspec_file(&opts
->pathspec
, 0,
1765 prefix
, opts
->pathspec_from_file
, opts
->pathspec_file_nul
);
1766 } else if (opts
->pathspec_file_nul
) {
1767 die(_("the option '%s' requires '%s'"), "--pathspec-file-nul", "--pathspec-from-file");
1770 opts
->pathspec
.recursive
= 1;
1772 if (opts
->pathspec
.nr
) {
1773 if (1 < !!opts
->writeout_stage
+ !!opts
->force
+ !!opts
->merge
)
1774 die(_("git checkout: --ours/--theirs, --force and --merge are incompatible when\n"
1775 "checking out of the index."));
1777 if (opts
->accept_pathspec
&& !opts
->empty_pathspec_ok
&&
1778 !opts
->patch_mode
) /* patch mode is special */
1779 die(_("you must specify path(s) to restore"));
1782 if (opts
->new_branch
) {
1783 struct strbuf buf
= STRBUF_INIT
;
1785 if (opts
->new_branch_force
)
1786 opts
->branch_exists
= validate_branchname(opts
->new_branch
, &buf
);
1788 opts
->branch_exists
=
1789 validate_new_branchname(opts
->new_branch
, &buf
, 0);
1790 strbuf_release(&buf
);
1793 if (opts
->patch_mode
|| opts
->pathspec
.nr
)
1794 return checkout_paths(opts
, new_branch_info
);
1796 return checkout_branch(opts
, new_branch_info
);
1799 int cmd_checkout(int argc
, const char **argv
, const char *prefix
)
1801 struct checkout_opts opts
;
1802 struct option
*options
;
1803 struct option checkout_options
[] = {
1804 OPT_STRING('b', NULL
, &opts
.new_branch
, N_("branch"),
1805 N_("create and checkout a new branch")),
1806 OPT_STRING('B', NULL
, &opts
.new_branch_force
, N_("branch"),
1807 N_("create/reset and checkout a branch")),
1808 OPT_BOOL('l', NULL
, &opts
.new_branch_log
, N_("create reflog for new branch")),
1809 OPT_BOOL(0, "guess", &opts
.dwim_new_local_branch
,
1810 N_("second guess 'git checkout <no-such-branch>' (default)")),
1811 OPT_BOOL(0, "overlay", &opts
.overlay_mode
, N_("use overlay mode (default)")),
1815 struct branch_info new_branch_info
= { 0 };
1817 memset(&opts
, 0, sizeof(opts
));
1818 opts
.dwim_new_local_branch
= 1;
1819 opts
.switch_branch_doing_nothing_is_ok
= 1;
1820 opts
.only_merge_on_switching_branches
= 0;
1821 opts
.accept_ref
= 1;
1822 opts
.accept_pathspec
= 1;
1823 opts
.implicit_detach
= 1;
1824 opts
.can_switch_when_in_progress
= 1;
1825 opts
.orphan_from_empty_tree
= 0;
1826 opts
.empty_pathspec_ok
= 1;
1827 opts
.overlay_mode
= -1;
1828 opts
.checkout_index
= -2; /* default on */
1829 opts
.checkout_worktree
= -2; /* default on */
1831 if (argc
== 3 && !strcmp(argv
[1], "-b")) {
1833 * User ran 'git checkout -b <branch>' and expects
1834 * the same behavior as 'git switch -c <branch>'.
1836 opts
.switch_branch_doing_nothing_is_ok
= 0;
1837 opts
.only_merge_on_switching_branches
= 1;
1840 options
= parse_options_dup(checkout_options
);
1841 options
= add_common_options(&opts
, options
);
1842 options
= add_common_switch_branch_options(&opts
, options
);
1843 options
= add_checkout_path_options(&opts
, options
);
1845 ret
= checkout_main(argc
, argv
, prefix
, &opts
,
1846 options
, checkout_usage
, &new_branch_info
);
1847 branch_info_release(&new_branch_info
);
1848 clear_pathspec(&opts
.pathspec
);
1849 FREE_AND_NULL(options
);
1853 int cmd_switch(int argc
, const char **argv
, const char *prefix
)
1855 struct checkout_opts opts
;
1856 struct option
*options
= NULL
;
1857 struct option switch_options
[] = {
1858 OPT_STRING('c', "create", &opts
.new_branch
, N_("branch"),
1859 N_("create and switch to a new branch")),
1860 OPT_STRING('C', "force-create", &opts
.new_branch_force
, N_("branch"),
1861 N_("create/reset and switch to a branch")),
1862 OPT_BOOL(0, "guess", &opts
.dwim_new_local_branch
,
1863 N_("second guess 'git switch <no-such-branch>'")),
1864 OPT_BOOL(0, "discard-changes", &opts
.discard_changes
,
1865 N_("throw away local modifications")),
1869 struct branch_info new_branch_info
= { 0 };
1871 memset(&opts
, 0, sizeof(opts
));
1872 opts
.dwim_new_local_branch
= 1;
1873 opts
.accept_ref
= 1;
1874 opts
.accept_pathspec
= 0;
1875 opts
.switch_branch_doing_nothing_is_ok
= 0;
1876 opts
.only_merge_on_switching_branches
= 1;
1877 opts
.implicit_detach
= 0;
1878 opts
.can_switch_when_in_progress
= 0;
1879 opts
.orphan_from_empty_tree
= 1;
1880 opts
.overlay_mode
= -1;
1882 options
= parse_options_dup(switch_options
);
1883 options
= add_common_options(&opts
, options
);
1884 options
= add_common_switch_branch_options(&opts
, options
);
1888 ret
= checkout_main(argc
, argv
, prefix
, &opts
,
1889 options
, switch_branch_usage
, &new_branch_info
);
1890 branch_info_release(&new_branch_info
);
1891 FREE_AND_NULL(options
);
1895 int cmd_restore(int argc
, const char **argv
, const char *prefix
)
1897 struct checkout_opts opts
;
1898 struct option
*options
;
1899 struct option restore_options
[] = {
1900 OPT_STRING('s', "source", &opts
.from_treeish
, "<tree-ish>",
1901 N_("which tree-ish to checkout from")),
1902 OPT_BOOL('S', "staged", &opts
.checkout_index
,
1903 N_("restore the index")),
1904 OPT_BOOL('W', "worktree", &opts
.checkout_worktree
,
1905 N_("restore the working tree (default)")),
1906 OPT_BOOL(0, "ignore-unmerged", &opts
.ignore_unmerged
,
1907 N_("ignore unmerged entries")),
1908 OPT_BOOL(0, "overlay", &opts
.overlay_mode
, N_("use overlay mode")),
1912 struct branch_info new_branch_info
= { 0 };
1914 memset(&opts
, 0, sizeof(opts
));
1915 opts
.accept_ref
= 0;
1916 opts
.accept_pathspec
= 1;
1917 opts
.empty_pathspec_ok
= 0;
1918 opts
.overlay_mode
= 0;
1919 opts
.checkout_index
= -1; /* default off */
1920 opts
.checkout_worktree
= -2; /* default on */
1921 opts
.ignore_unmerged_opt
= "--ignore-unmerged";
1923 options
= parse_options_dup(restore_options
);
1924 options
= add_common_options(&opts
, options
);
1925 options
= add_checkout_path_options(&opts
, options
);
1927 ret
= checkout_main(argc
, argv
, prefix
, &opts
,
1928 options
, restore_usage
, &new_branch_info
);
1929 branch_info_release(&new_branch_info
);
1930 FREE_AND_NULL(options
);