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 UNUSED
)
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
, OBJ_BLOB
, &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
, 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");
491 * Reject --staged option to the restore command when combined with
492 * merge-related options. Use the accept_ref flag to distinguish it
493 * from the checkout command, which does not accept --staged anyway.
495 * `restore --ours|--theirs --worktree --staged` could mean resolving
496 * conflicted paths to one side in both the worktree and the index,
497 * but does not currently.
499 * `restore --merge|--conflict=<style>` already recreates conflicts
500 * in both the worktree and the index, so adding --staged would be
503 if (!opts
->accept_ref
&& opts
->checkout_index
) {
504 if (opts
->writeout_stage
)
505 die(_("'%s' or '%s' cannot be used with %s"),
506 "--ours", "--theirs", "--staged");
509 die(_("'%s' or '%s' cannot be used with %s"),
510 "--merge", "--conflict", "--staged");
513 if (opts
->patch_mode
) {
514 const char *patch_mode
;
515 const char *rev
= new_branch_info
->name
;
516 char rev_oid
[GIT_MAX_HEXSZ
+ 1];
519 * Since rev can be in the form of `<a>...<b>` (which is not
520 * recognized by diff-index), we will always replace the name
521 * with the hex of the commit (whether it's in `...` form or
522 * not) for the run_add_interactive() machinery to work
523 * properly. However, there is special logic for the HEAD case
524 * so we mustn't replace that. Also, when we were given a
525 * tree-object, new_branch_info->commit would be NULL, but we
526 * do not have to do any replacement, either.
528 if (rev
&& new_branch_info
->commit
&& strcmp(rev
, "HEAD"))
529 rev
= oid_to_hex_r(rev_oid
, &new_branch_info
->commit
->object
.oid
);
531 if (opts
->checkout_index
&& opts
->checkout_worktree
)
532 patch_mode
= "--patch=checkout";
533 else if (opts
->checkout_index
&& !opts
->checkout_worktree
)
534 patch_mode
= "--patch=reset";
535 else if (!opts
->checkout_index
&& opts
->checkout_worktree
)
536 patch_mode
= "--patch=worktree";
538 BUG("either flag must have been set, worktree=%d, index=%d",
539 opts
->checkout_worktree
, opts
->checkout_index
);
540 return run_add_interactive(rev
, patch_mode
, &opts
->pathspec
);
543 repo_hold_locked_index(the_repository
, &lock_file
, LOCK_DIE_ON_ERROR
);
544 if (read_cache_preload(&opts
->pathspec
) < 0)
545 return error(_("index file corrupt"));
547 if (opts
->source_tree
)
548 read_tree_some(opts
->source_tree
, &opts
->pathspec
);
550 ps_matched
= xcalloc(opts
->pathspec
.nr
, 1);
553 * Make sure all pathspecs participated in locating the paths
556 for (pos
= 0; pos
< active_nr
; pos
++)
557 if (opts
->overlay_mode
)
558 mark_ce_for_checkout_overlay(active_cache
[pos
],
562 mark_ce_for_checkout_no_overlay(active_cache
[pos
],
566 if (report_path_error(ps_matched
, &opts
->pathspec
)) {
572 /* "checkout -m path" to recreate conflicted state */
574 unmerge_marked_index(&the_index
);
576 /* Any unmerged paths? */
577 for (pos
= 0; pos
< active_nr
; pos
++) {
578 const struct cache_entry
*ce
= active_cache
[pos
];
579 if (ce
->ce_flags
& CE_MATCHED
) {
582 if (opts
->ignore_unmerged
) {
584 warning(_("path '%s' is unmerged"), ce
->name
);
585 } else if (opts
->writeout_stage
) {
586 errs
|= check_stage(opts
->writeout_stage
, ce
, pos
, opts
->overlay_mode
);
587 } else if (opts
->merge
) {
588 errs
|= check_stages((1<<2) | (1<<3), ce
, pos
);
591 error(_("path '%s' is unmerged"), ce
->name
);
593 pos
= skip_same_name(ce
, pos
) - 1;
599 /* Now we are committed to check them out */
600 if (opts
->checkout_worktree
)
601 errs
|= checkout_worktree(opts
, new_branch_info
);
603 remove_marked_cache_entries(&the_index
, 1);
606 * Allow updating the index when checking out from the index.
607 * This is to save new stat info.
609 if (opts
->checkout_worktree
&& !opts
->checkout_index
&& !opts
->source_tree
)
612 checkout_index
= opts
->checkout_index
;
614 if (checkout_index
) {
615 if (write_locked_index(&the_index
, &lock_file
, COMMIT_LOCK
))
616 die(_("unable to write new index file"));
619 * NEEDSWORK: if --worktree is not specified, we
620 * should save stat info of checked out files in the
621 * index to avoid the next (potentially costly)
622 * refresh. But it's a bit tricker to do...
624 rollback_lock_file(&lock_file
);
627 read_ref_full("HEAD", 0, &rev
, NULL
);
628 head
= lookup_commit_reference_gently(the_repository
, &rev
, 1);
630 errs
|= post_checkout_hook(head
, head
, 0);
634 static void show_local_changes(struct object
*head
,
635 const struct diff_options
*opts
)
638 /* I think we want full paths, even if we're in a subdirectory. */
639 repo_init_revisions(the_repository
, &rev
, NULL
);
640 rev
.diffopt
.flags
= opts
->flags
;
641 rev
.diffopt
.output_format
|= DIFF_FORMAT_NAME_STATUS
;
642 rev
.diffopt
.flags
.recursive
= 1;
643 diff_setup_done(&rev
.diffopt
);
644 add_pending_object(&rev
, head
, NULL
);
645 run_diff_index(&rev
, 0);
646 release_revisions(&rev
);
649 static void describe_detached_head(const char *msg
, struct commit
*commit
)
651 struct strbuf sb
= STRBUF_INIT
;
653 if (!parse_commit(commit
))
654 pp_commit_easy(CMIT_FMT_ONELINE
, commit
, &sb
);
655 if (print_sha1_ellipsis()) {
656 fprintf(stderr
, "%s %s... %s\n", msg
,
657 find_unique_abbrev(&commit
->object
.oid
, DEFAULT_ABBREV
), sb
.buf
);
659 fprintf(stderr
, "%s %s %s\n", msg
,
660 find_unique_abbrev(&commit
->object
.oid
, DEFAULT_ABBREV
), sb
.buf
);
665 static int reset_tree(struct tree
*tree
, const struct checkout_opts
*o
,
666 int worktree
, int *writeout_error
,
667 struct branch_info
*info
)
669 struct unpack_trees_options opts
;
670 struct tree_desc tree_desc
;
672 memset(&opts
, 0, sizeof(opts
));
674 opts
.update
= worktree
;
675 opts
.skip_unmerged
= !worktree
;
676 opts
.reset
= o
->force
? UNPACK_RESET_OVERWRITE_UNTRACKED
:
677 UNPACK_RESET_PROTECT_UNTRACKED
;
678 opts
.preserve_ignored
= (!o
->force
&& !o
->overwrite_ignore
);
680 opts
.fn
= oneway_merge
;
681 opts
.verbose_update
= o
->show_progress
;
682 opts
.src_index
= &the_index
;
683 opts
.dst_index
= &the_index
;
684 init_checkout_metadata(&opts
.meta
, info
->refname
,
685 info
->commit
? &info
->commit
->object
.oid
: null_oid(),
688 init_tree_desc(&tree_desc
, tree
->buffer
, tree
->size
);
689 switch (unpack_trees(1, &tree_desc
, &opts
)) {
693 * We return 0 nevertheless, as the index is all right
694 * and more importantly we have made best efforts to
695 * update paths in the work tree, and we cannot revert
706 static void setup_branch_path(struct branch_info
*branch
)
708 struct strbuf buf
= STRBUF_INIT
;
711 * If this is a ref, resolve it; otherwise, look up the OID for our
712 * expression. Failure here is okay.
714 if (!dwim_ref(branch
->name
, strlen(branch
->name
), &branch
->oid
, &branch
->refname
, 0))
715 repo_get_oid_committish(the_repository
, branch
->name
, &branch
->oid
);
717 strbuf_branchname(&buf
, branch
->name
, INTERPRET_BRANCH_LOCAL
);
718 if (strcmp(buf
.buf
, branch
->name
)) {
720 branch
->name
= xstrdup(buf
.buf
);
722 strbuf_splice(&buf
, 0, 0, "refs/heads/", 11);
724 branch
->path
= strbuf_detach(&buf
, NULL
);
727 static void init_topts(struct unpack_trees_options
*topts
, int merge
,
728 int show_progress
, int overwrite_ignore
,
729 struct commit
*old_commit
)
731 memset(topts
, 0, sizeof(*topts
));
732 topts
->head_idx
= -1;
733 topts
->src_index
= &the_index
;
734 topts
->dst_index
= &the_index
;
736 setup_unpack_trees_porcelain(topts
, "checkout");
738 topts
->initial_checkout
= is_cache_unborn();
741 topts
->quiet
= merge
&& old_commit
;
742 topts
->verbose_update
= show_progress
;
743 topts
->fn
= twoway_merge
;
744 topts
->preserve_ignored
= !overwrite_ignore
;
747 static int merge_working_tree(const struct checkout_opts
*opts
,
748 struct branch_info
*old_branch_info
,
749 struct branch_info
*new_branch_info
,
753 struct lock_file lock_file
= LOCK_INIT
;
754 struct tree
*new_tree
;
756 hold_locked_index(&lock_file
, LOCK_DIE_ON_ERROR
);
757 if (read_cache_preload(NULL
) < 0)
758 return error(_("index file corrupt"));
760 resolve_undo_clear();
761 if (opts
->new_orphan_branch
&& opts
->orphan_from_empty_tree
) {
762 if (new_branch_info
->commit
)
763 BUG("'switch --orphan' should never accept a commit as starting point");
764 new_tree
= parse_tree_indirect(the_hash_algo
->empty_tree
);
766 new_tree
= get_commit_tree(new_branch_info
->commit
);
767 if (opts
->discard_changes
) {
768 ret
= reset_tree(new_tree
, opts
, 1, writeout_error
, new_branch_info
);
772 struct tree_desc trees
[2];
774 struct unpack_trees_options topts
;
775 const struct object_id
*old_commit_oid
;
777 refresh_cache(REFRESH_QUIET
);
779 if (unmerged_cache()) {
780 error(_("you need to resolve your current index first"));
784 /* 2-way merge to the new branch */
785 init_topts(&topts
, opts
->merge
, opts
->show_progress
,
786 opts
->overwrite_ignore
, old_branch_info
->commit
);
787 init_checkout_metadata(&topts
.meta
, new_branch_info
->refname
,
788 new_branch_info
->commit
?
789 &new_branch_info
->commit
->object
.oid
:
790 &new_branch_info
->oid
, NULL
);
792 old_commit_oid
= old_branch_info
->commit
?
793 &old_branch_info
->commit
->object
.oid
:
794 the_hash_algo
->empty_tree
;
795 tree
= parse_tree_indirect(old_commit_oid
);
797 die(_("unable to parse commit %s"),
798 oid_to_hex(old_commit_oid
));
800 init_tree_desc(&trees
[0], tree
->buffer
, tree
->size
);
801 parse_tree(new_tree
);
803 init_tree_desc(&trees
[1], tree
->buffer
, tree
->size
);
805 ret
= unpack_trees(2, trees
, &topts
);
806 clear_unpack_trees_porcelain(&topts
);
809 * Unpack couldn't do a trivial merge; either
810 * give up or do a real merge, depending on
811 * whether the merge flag was used.
814 struct tree
*old_tree
;
815 struct merge_options o
;
816 struct strbuf sb
= STRBUF_INIT
;
817 struct strbuf old_commit_shortname
= STRBUF_INIT
;
823 * Without old_branch_info->commit, the below is the same as
824 * the two-tree unpack we already tried and failed.
826 if (!old_branch_info
->commit
)
828 old_tree
= get_commit_tree(old_branch_info
->commit
);
830 if (repo_index_has_changes(the_repository
, old_tree
, &sb
))
831 die(_("cannot continue with staged changes in "
832 "the following files:\n%s"), sb
.buf
);
835 /* Do more real merge */
838 * We update the index fully, then write the
839 * tree from the index, then merge the new
840 * branch with the current tree, with the old
841 * branch as the base. Then we reset the index
842 * (but not the working tree) to the new
843 * branch, leaving the working tree as the
844 * merged version, but skipping unmerged
845 * entries in the index.
848 add_files_to_cache(NULL
, NULL
, 0);
849 init_merge_options(&o
, the_repository
);
851 work
= write_in_core_index_as_tree(the_repository
);
853 ret
= reset_tree(new_tree
,
855 writeout_error
, new_branch_info
);
858 o
.ancestor
= old_branch_info
->name
;
859 if (!old_branch_info
->name
) {
860 strbuf_add_unique_abbrev(&old_commit_shortname
,
861 &old_branch_info
->commit
->object
.oid
,
863 o
.ancestor
= old_commit_shortname
.buf
;
865 o
.branch1
= new_branch_info
->name
;
867 ret
= merge_trees(&o
,
873 ret
= reset_tree(new_tree
,
875 writeout_error
, new_branch_info
);
876 strbuf_release(&o
.obuf
);
877 strbuf_release(&old_commit_shortname
);
883 if (!cache_tree_fully_valid(active_cache_tree
))
884 cache_tree_update(&the_index
, WRITE_TREE_SILENT
| WRITE_TREE_REPAIR
);
886 if (write_locked_index(&the_index
, &lock_file
, COMMIT_LOCK
))
887 die(_("unable to write new index file"));
889 if (!opts
->discard_changes
&& !opts
->quiet
&& new_branch_info
->commit
)
890 show_local_changes(&new_branch_info
->commit
->object
, &opts
->diff_options
);
895 static void report_tracking(struct branch_info
*new_branch_info
)
897 struct strbuf sb
= STRBUF_INIT
;
898 struct branch
*branch
= branch_get(new_branch_info
->name
);
900 if (!format_tracking_info(branch
, &sb
, AHEAD_BEHIND_FULL
))
902 fputs(sb
.buf
, stdout
);
906 static void update_refs_for_switch(const struct checkout_opts
*opts
,
907 struct branch_info
*old_branch_info
,
908 struct branch_info
*new_branch_info
)
910 struct strbuf msg
= STRBUF_INIT
;
911 const char *old_desc
, *reflog_msg
;
912 if (opts
->new_branch
) {
913 if (opts
->new_orphan_branch
) {
916 refname
= mkpathdup("refs/heads/%s", opts
->new_orphan_branch
);
917 if (opts
->new_branch_log
&&
918 !should_autocreate_reflog(refname
)) {
920 struct strbuf err
= STRBUF_INIT
;
922 ret
= safe_create_reflog(refname
, &err
);
924 fprintf(stderr
, _("Can not do reflog for '%s': %s\n"),
925 opts
->new_orphan_branch
, err
.buf
);
926 strbuf_release(&err
);
930 strbuf_release(&err
);
935 create_branch(the_repository
,
936 opts
->new_branch
, new_branch_info
->name
,
937 opts
->new_branch_force
? 1 : 0,
938 opts
->new_branch_force
? 1 : 0,
939 opts
->new_branch_log
,
943 free(new_branch_info
->name
);
944 free(new_branch_info
->refname
);
945 new_branch_info
->name
= xstrdup(opts
->new_branch
);
946 setup_branch_path(new_branch_info
);
949 old_desc
= old_branch_info
->name
;
950 if (!old_desc
&& old_branch_info
->commit
)
951 old_desc
= oid_to_hex(&old_branch_info
->commit
->object
.oid
);
953 reflog_msg
= getenv("GIT_REFLOG_ACTION");
955 strbuf_addf(&msg
, "checkout: moving from %s to %s",
956 old_desc
? old_desc
: "(invalid)", new_branch_info
->name
);
958 strbuf_insertstr(&msg
, 0, reflog_msg
);
960 if (!strcmp(new_branch_info
->name
, "HEAD") && !new_branch_info
->path
&& !opts
->force_detach
) {
962 } else if (opts
->force_detach
|| !new_branch_info
->path
) { /* No longer on any branch. */
963 update_ref(msg
.buf
, "HEAD", &new_branch_info
->commit
->object
.oid
, NULL
,
964 REF_NO_DEREF
, UPDATE_REFS_DIE_ON_ERR
);
966 if (old_branch_info
->path
&&
967 advice_enabled(ADVICE_DETACHED_HEAD
) && !opts
->force_detach
)
968 detach_advice(new_branch_info
->name
);
969 describe_detached_head(_("HEAD is now at"), new_branch_info
->commit
);
971 } else if (new_branch_info
->path
) { /* Switch branches. */
972 if (create_symref("HEAD", new_branch_info
->path
, msg
.buf
) < 0)
973 die(_("unable to update HEAD"));
975 if (old_branch_info
->path
&& !strcmp(new_branch_info
->path
, old_branch_info
->path
)) {
976 if (opts
->new_branch_force
)
977 fprintf(stderr
, _("Reset branch '%s'\n"),
978 new_branch_info
->name
);
980 fprintf(stderr
, _("Already on '%s'\n"),
981 new_branch_info
->name
);
982 } else if (opts
->new_branch
) {
983 if (opts
->branch_exists
)
984 fprintf(stderr
, _("Switched to and reset branch '%s'\n"), new_branch_info
->name
);
986 fprintf(stderr
, _("Switched to a new branch '%s'\n"), new_branch_info
->name
);
988 fprintf(stderr
, _("Switched to branch '%s'\n"),
989 new_branch_info
->name
);
992 if (old_branch_info
->path
&& old_branch_info
->name
) {
993 if (!ref_exists(old_branch_info
->path
) && reflog_exists(old_branch_info
->path
))
994 delete_reflog(old_branch_info
->path
);
997 remove_branch_state(the_repository
, !opts
->quiet
);
998 strbuf_release(&msg
);
1000 (new_branch_info
->path
|| (!opts
->force_detach
&& !strcmp(new_branch_info
->name
, "HEAD"))))
1001 report_tracking(new_branch_info
);
1004 static int add_pending_uninteresting_ref(const char *refname
,
1005 const struct object_id
*oid
,
1006 int flags UNUSED
, void *cb_data
)
1008 add_pending_oid(cb_data
, refname
, oid
, UNINTERESTING
);
1012 static void describe_one_orphan(struct strbuf
*sb
, struct commit
*commit
)
1014 strbuf_addstr(sb
, " ");
1015 strbuf_add_unique_abbrev(sb
, &commit
->object
.oid
, DEFAULT_ABBREV
);
1016 strbuf_addch(sb
, ' ');
1017 if (!parse_commit(commit
))
1018 pp_commit_easy(CMIT_FMT_ONELINE
, commit
, sb
);
1019 strbuf_addch(sb
, '\n');
1022 #define ORPHAN_CUTOFF 4
1023 static void suggest_reattach(struct commit
*commit
, struct rev_info
*revs
)
1025 struct commit
*c
, *last
= NULL
;
1026 struct strbuf sb
= STRBUF_INIT
;
1028 while ((c
= get_revision(revs
)) != NULL
) {
1029 if (lost
< ORPHAN_CUTOFF
)
1030 describe_one_orphan(&sb
, c
);
1034 if (ORPHAN_CUTOFF
< lost
) {
1035 int more
= lost
- ORPHAN_CUTOFF
;
1037 describe_one_orphan(&sb
, last
);
1039 strbuf_addf(&sb
, _(" ... and %d more.\n"), more
);
1044 /* The singular version */
1045 "Warning: you are leaving %d commit behind, "
1046 "not connected to\n"
1047 "any of your branches:\n\n"
1049 /* The plural version */
1050 "Warning: you are leaving %d commits behind, "
1051 "not connected to\n"
1052 "any of your branches:\n\n"
1054 /* Give ngettext() the count */
1058 strbuf_release(&sb
);
1060 if (advice_enabled(ADVICE_DETACHED_HEAD
))
1063 /* The singular version */
1064 "If you want to keep it by creating a new branch, "
1065 "this may be a good time\nto do so with:\n\n"
1066 " git branch <new-branch-name> %s\n\n",
1067 /* The plural version */
1068 "If you want to keep them by creating a new branch, "
1069 "this may be a good time\nto do so with:\n\n"
1070 " git branch <new-branch-name> %s\n\n",
1071 /* Give ngettext() the count */
1073 find_unique_abbrev(&commit
->object
.oid
, DEFAULT_ABBREV
));
1077 * We are about to leave commit that was at the tip of a detached
1078 * HEAD. If it is not reachable from any ref, this is the last chance
1079 * for the user to do so without resorting to reflog.
1081 static void orphaned_commit_warning(struct commit
*old_commit
, struct commit
*new_commit
)
1083 struct rev_info revs
;
1084 struct object
*object
= &old_commit
->object
;
1086 repo_init_revisions(the_repository
, &revs
, NULL
);
1087 setup_revisions(0, NULL
, &revs
, NULL
);
1089 object
->flags
&= ~UNINTERESTING
;
1090 add_pending_object(&revs
, object
, oid_to_hex(&object
->oid
));
1092 for_each_ref(add_pending_uninteresting_ref
, &revs
);
1094 add_pending_oid(&revs
, "HEAD",
1095 &new_commit
->object
.oid
,
1098 if (prepare_revision_walk(&revs
))
1099 die(_("internal error in revision walk"));
1100 if (!(old_commit
->object
.flags
& UNINTERESTING
))
1101 suggest_reattach(old_commit
, &revs
);
1103 describe_detached_head(_("Previous HEAD position was"), old_commit
);
1105 /* Clean up objects used, as they will be reused. */
1106 repo_clear_commit_marks(the_repository
, ALL_REV_FLAGS
);
1107 release_revisions(&revs
);
1110 static int switch_branches(const struct checkout_opts
*opts
,
1111 struct branch_info
*new_branch_info
)
1114 struct branch_info old_branch_info
= { 0 };
1115 struct object_id rev
;
1116 int flag
, writeout_error
= 0;
1119 trace2_cmd_mode("branch");
1121 memset(&old_branch_info
, 0, sizeof(old_branch_info
));
1122 old_branch_info
.path
= resolve_refdup("HEAD", 0, &rev
, &flag
);
1123 if (old_branch_info
.path
)
1124 old_branch_info
.commit
= lookup_commit_reference_gently(the_repository
, &rev
, 1);
1125 if (!(flag
& REF_ISSYMREF
))
1126 FREE_AND_NULL(old_branch_info
.path
);
1128 if (old_branch_info
.path
) {
1129 const char *const prefix
= "refs/heads/";
1131 if (skip_prefix(old_branch_info
.path
, prefix
, &p
))
1132 old_branch_info
.name
= xstrdup(p
);
1135 if (opts
->new_orphan_branch
&& opts
->orphan_from_empty_tree
) {
1136 if (new_branch_info
->name
)
1137 BUG("'switch --orphan' should never accept a commit as starting point");
1138 new_branch_info
->commit
= NULL
;
1139 new_branch_info
->name
= xstrdup("(empty)");
1143 if (!new_branch_info
->name
) {
1144 new_branch_info
->name
= xstrdup("HEAD");
1145 new_branch_info
->commit
= old_branch_info
.commit
;
1146 if (!new_branch_info
->commit
)
1147 die(_("You are on a branch yet to be born"));
1148 parse_commit_or_die(new_branch_info
->commit
);
1150 if (opts
->only_merge_on_switching_branches
)
1155 ret
= merge_working_tree(opts
, &old_branch_info
, new_branch_info
, &writeout_error
);
1157 branch_info_release(&old_branch_info
);
1162 if (!opts
->quiet
&& !old_branch_info
.path
&& old_branch_info
.commit
&& new_branch_info
->commit
!= old_branch_info
.commit
)
1163 orphaned_commit_warning(old_branch_info
.commit
, new_branch_info
->commit
);
1165 update_refs_for_switch(opts
, &old_branch_info
, new_branch_info
);
1167 ret
= post_checkout_hook(old_branch_info
.commit
, new_branch_info
->commit
, 1);
1168 branch_info_release(&old_branch_info
);
1170 return ret
|| writeout_error
;
1173 static int git_checkout_config(const char *var
, const char *value
, void *cb
)
1175 struct checkout_opts
*opts
= cb
;
1177 if (!strcmp(var
, "diff.ignoresubmodules")) {
1178 handle_ignore_submodules_arg(&opts
->diff_options
, value
);
1181 if (!strcmp(var
, "checkout.guess")) {
1182 opts
->dwim_new_local_branch
= git_config_bool(var
, value
);
1186 if (starts_with(var
, "submodule."))
1187 return git_default_submodule_config(var
, value
, NULL
);
1189 return git_xmerge_config(var
, value
, NULL
);
1192 static void setup_new_branch_info_and_source_tree(
1193 struct branch_info
*new_branch_info
,
1194 struct checkout_opts
*opts
,
1195 struct object_id
*rev
,
1198 struct tree
**source_tree
= &opts
->source_tree
;
1199 struct object_id branch_rev
;
1201 new_branch_info
->name
= xstrdup(arg
);
1202 setup_branch_path(new_branch_info
);
1204 if (!check_refname_format(new_branch_info
->path
, 0) &&
1205 !read_ref(new_branch_info
->path
, &branch_rev
))
1206 oidcpy(rev
, &branch_rev
);
1208 /* not an existing branch */
1209 FREE_AND_NULL(new_branch_info
->path
);
1211 new_branch_info
->commit
= lookup_commit_reference_gently(the_repository
, rev
, 1);
1212 if (!new_branch_info
->commit
) {
1214 *source_tree
= parse_tree_indirect(rev
);
1216 parse_commit_or_die(new_branch_info
->commit
);
1217 *source_tree
= get_commit_tree(new_branch_info
->commit
);
1221 static const char *parse_remote_branch(const char *arg
,
1222 struct object_id
*rev
,
1223 int could_be_checkout_paths
)
1225 int num_matches
= 0;
1226 const char *remote
= unique_tracking_name(arg
, rev
, &num_matches
);
1228 if (remote
&& could_be_checkout_paths
) {
1229 die(_("'%s' could be both a local file and a tracking branch.\n"
1230 "Please use -- (and optionally --no-guess) to disambiguate"),
1234 if (!remote
&& num_matches
> 1) {
1235 if (advice_enabled(ADVICE_CHECKOUT_AMBIGUOUS_REMOTE_BRANCH_NAME
)) {
1236 advise(_("If you meant to check out a remote tracking branch on, e.g. 'origin',\n"
1237 "you can do so by fully qualifying the name with the --track option:\n"
1239 " git checkout --track origin/<name>\n"
1241 "If you'd like to always have checkouts of an ambiguous <name> prefer\n"
1242 "one remote, e.g. the 'origin' remote, consider setting\n"
1243 "checkout.defaultRemote=origin in your config."));
1246 die(_("'%s' matched multiple (%d) remote tracking branches"),
1253 static int parse_branchname_arg(int argc
, const char **argv
,
1254 int dwim_new_local_branch_ok
,
1255 struct branch_info
*new_branch_info
,
1256 struct checkout_opts
*opts
,
1257 struct object_id
*rev
)
1259 const char **new_branch
= &opts
->new_branch
;
1263 int has_dash_dash
= 0;
1267 * case 1: git checkout <ref> -- [<paths>]
1269 * <ref> must be a valid tree, everything after the '--' must be
1272 * case 2: git checkout -- [<paths>]
1274 * everything after the '--' must be paths.
1276 * case 3: git checkout <something> [--]
1278 * (a) If <something> is a commit, that is to
1279 * switch to the branch or detach HEAD at it. As a special case,
1280 * if <something> is A...B (missing A or B means HEAD but you can
1281 * omit at most one side), and if there is a unique merge base
1282 * between A and B, A...B names that merge base.
1284 * (b) If <something> is _not_ a commit, either "--" is present
1285 * or <something> is not a path, no -t or -b was given, and
1286 * and there is a tracking branch whose name is <something>
1287 * in one and only one remote (or if the branch exists on the
1288 * remote named in checkout.defaultRemote), then this is a
1289 * short-hand to fork local <something> from that
1290 * remote-tracking branch.
1292 * (c) Otherwise, if "--" is present, treat it like case (1).
1295 * - if it's a reference, treat it like case (1)
1296 * - else if it's a path, treat it like case (2)
1299 * case 4: git checkout <something> <paths>
1301 * The first argument must not be ambiguous.
1302 * - If it's *only* a reference, treat it like case (1).
1303 * - If it's only a path, treat it like case (2).
1310 if (!opts
->accept_pathspec
) {
1312 die(_("only one reference expected"));
1313 has_dash_dash
= 1; /* helps disambiguate */
1318 for (i
= 0; i
< argc
; i
++) {
1319 if (opts
->accept_pathspec
&& !strcmp(argv
[i
], "--")) {
1324 if (dash_dash_pos
== 0)
1325 return 1; /* case (2) */
1326 else if (dash_dash_pos
== 1)
1327 has_dash_dash
= 1; /* case (3) or (1) */
1328 else if (dash_dash_pos
>= 2)
1329 die(_("only one reference expected, %d given."), dash_dash_pos
);
1330 opts
->count_checkout_paths
= !opts
->quiet
&& !has_dash_dash
;
1332 if (!strcmp(arg
, "-"))
1335 if (get_oid_mb(arg
, rev
)) {
1337 * Either case (3) or (4), with <something> not being
1338 * a commit, or an attempt to use case (1) with an
1341 * It's likely an error, but we need to find out if
1342 * we should auto-create the branch, case (3).(b).
1344 int recover_with_dwim
= dwim_new_local_branch_ok
;
1346 int could_be_checkout_paths
= !has_dash_dash
&&
1347 check_filename(opts
->prefix
, arg
);
1349 if (!has_dash_dash
&& !no_wildcard(arg
))
1350 recover_with_dwim
= 0;
1353 * Accept "git checkout foo", "git checkout foo --"
1354 * and "git switch foo" as candidates for dwim.
1356 if (!(argc
== 1 && !has_dash_dash
) &&
1357 !(argc
== 2 && has_dash_dash
) &&
1358 opts
->accept_pathspec
)
1359 recover_with_dwim
= 0;
1361 if (recover_with_dwim
) {
1362 const char *remote
= parse_remote_branch(arg
, rev
,
1363 could_be_checkout_paths
);
1367 /* DWIMmed to create local branch, case (3).(b) */
1369 recover_with_dwim
= 0;
1373 if (!recover_with_dwim
) {
1375 die(_("invalid reference: %s"), arg
);
1380 /* we can't end up being in (2) anymore, eat the argument */
1385 setup_new_branch_info_and_source_tree(new_branch_info
, opts
, rev
, arg
);
1387 if (!opts
->source_tree
) /* case (1): want a tree */
1388 die(_("reference is not a tree: %s"), arg
);
1390 if (!has_dash_dash
) { /* case (3).(d) -> (1) */
1392 * Do not complain the most common case
1393 * git checkout branch
1394 * even if there happen to be a file called 'branch';
1395 * it would be extremely annoying.
1398 verify_non_filename(opts
->prefix
, arg
);
1399 } else if (opts
->accept_pathspec
) {
1408 static int switch_unborn_to_new_branch(const struct checkout_opts
*opts
)
1411 struct strbuf branch_ref
= STRBUF_INIT
;
1413 trace2_cmd_mode("unborn");
1415 if (!opts
->new_branch
)
1416 die(_("You are on a branch yet to be born"));
1417 strbuf_addf(&branch_ref
, "refs/heads/%s", opts
->new_branch
);
1418 status
= create_symref("HEAD", branch_ref
.buf
, "checkout -b");
1419 strbuf_release(&branch_ref
);
1421 fprintf(stderr
, _("Switched to a new branch '%s'\n"),
1426 static void die_expecting_a_branch(const struct branch_info
*branch_info
)
1428 struct object_id oid
;
1432 if (dwim_ref(branch_info
->name
, strlen(branch_info
->name
), &oid
, &to_free
, 0) == 1) {
1433 const char *ref
= to_free
;
1435 if (skip_prefix(ref
, "refs/tags/", &ref
))
1436 code
= die_message(_("a branch is expected, got tag '%s'"), ref
);
1437 else if (skip_prefix(ref
, "refs/remotes/", &ref
))
1438 code
= die_message(_("a branch is expected, got remote branch '%s'"), ref
);
1440 code
= die_message(_("a branch is expected, got '%s'"), ref
);
1442 else if (branch_info
->commit
)
1443 code
= die_message(_("a branch is expected, got commit '%s'"), branch_info
->name
);
1446 * This case should never happen because we already die() on
1447 * non-commit, but just in case.
1449 code
= die_message(_("a branch is expected, got '%s'"), branch_info
->name
);
1451 if (advice_enabled(ADVICE_SUGGEST_DETACHING_HEAD
))
1452 advise(_("If you want to detach HEAD at the commit, try again with the --detach option."));
1457 static void die_if_some_operation_in_progress(void)
1459 struct wt_status_state state
;
1461 memset(&state
, 0, sizeof(state
));
1462 wt_status_get_state(the_repository
, &state
, 0);
1464 if (state
.merge_in_progress
)
1465 die(_("cannot switch branch while merging\n"
1466 "Consider \"git merge --quit\" "
1467 "or \"git worktree add\"."));
1468 if (state
.am_in_progress
)
1469 die(_("cannot switch branch in the middle of an am session\n"
1470 "Consider \"git am --quit\" "
1471 "or \"git worktree add\"."));
1472 if (state
.rebase_interactive_in_progress
|| state
.rebase_in_progress
)
1473 die(_("cannot switch branch while rebasing\n"
1474 "Consider \"git rebase --quit\" "
1475 "or \"git worktree add\"."));
1476 if (state
.cherry_pick_in_progress
)
1477 die(_("cannot switch branch while cherry-picking\n"
1478 "Consider \"git cherry-pick --quit\" "
1479 "or \"git worktree add\"."));
1480 if (state
.revert_in_progress
)
1481 die(_("cannot switch branch while reverting\n"
1482 "Consider \"git revert --quit\" "
1483 "or \"git worktree add\"."));
1484 if (state
.bisect_in_progress
)
1485 warning(_("you are switching branch while bisecting"));
1488 static int checkout_branch(struct checkout_opts
*opts
,
1489 struct branch_info
*new_branch_info
)
1491 if (opts
->pathspec
.nr
)
1492 die(_("paths cannot be used with switching branches"));
1494 if (opts
->patch_mode
)
1495 die(_("'%s' cannot be used with switching branches"),
1498 if (opts
->overlay_mode
!= -1)
1499 die(_("'%s' cannot be used with switching branches"),
1502 if (opts
->writeout_stage
)
1503 die(_("'%s' cannot be used with switching branches"),
1506 if (opts
->force
&& opts
->merge
)
1507 die(_("'%s' cannot be used with '%s'"), "-f", "-m");
1509 if (opts
->discard_changes
&& opts
->merge
)
1510 die(_("'%s' cannot be used with '%s'"), "--discard-changes", "--merge");
1512 if (opts
->force_detach
&& opts
->new_branch
)
1513 die(_("'%s' cannot be used with '%s'"),
1514 "--detach", "-b/-B/--orphan");
1516 if (opts
->new_orphan_branch
) {
1517 if (opts
->track
!= BRANCH_TRACK_UNSPECIFIED
)
1518 die(_("'%s' cannot be used with '%s'"), "--orphan", "-t");
1519 if (opts
->orphan_from_empty_tree
&& new_branch_info
->name
)
1520 die(_("'%s' cannot take <start-point>"), "--orphan");
1521 } else if (opts
->force_detach
) {
1522 if (opts
->track
!= BRANCH_TRACK_UNSPECIFIED
)
1523 die(_("'%s' cannot be used with '%s'"), "--detach", "-t");
1524 } else if (opts
->track
== BRANCH_TRACK_UNSPECIFIED
)
1525 opts
->track
= git_branch_track
;
1527 if (new_branch_info
->name
&& !new_branch_info
->commit
)
1528 die(_("Cannot switch branch to a non-commit '%s'"),
1529 new_branch_info
->name
);
1531 if (!opts
->switch_branch_doing_nothing_is_ok
&&
1532 !new_branch_info
->name
&&
1533 !opts
->new_branch
&&
1534 !opts
->force_detach
)
1535 die(_("missing branch or commit argument"));
1537 if (!opts
->implicit_detach
&&
1538 !opts
->force_detach
&&
1539 !opts
->new_branch
&&
1540 !opts
->new_branch_force
&&
1541 new_branch_info
->name
&&
1542 !new_branch_info
->path
)
1543 die_expecting_a_branch(new_branch_info
);
1545 if (!opts
->can_switch_when_in_progress
)
1546 die_if_some_operation_in_progress();
1548 if (new_branch_info
->path
&& !opts
->force_detach
&& !opts
->new_branch
&&
1549 !opts
->ignore_other_worktrees
) {
1551 char *head_ref
= resolve_refdup("HEAD", 0, NULL
, &flag
);
1553 (!(flag
& REF_ISSYMREF
) || strcmp(head_ref
, new_branch_info
->path
)))
1554 die_if_checked_out(new_branch_info
->path
, 1);
1558 if (!new_branch_info
->commit
&& opts
->new_branch
) {
1559 struct object_id rev
;
1562 if (!read_ref_full("HEAD", 0, &rev
, &flag
) &&
1563 (flag
& REF_ISSYMREF
) && is_null_oid(&rev
))
1564 return switch_unborn_to_new_branch(opts
);
1566 return switch_branches(opts
, new_branch_info
);
1569 static struct option
*add_common_options(struct checkout_opts
*opts
,
1570 struct option
*prevopts
)
1572 struct option options
[] = {
1573 OPT__QUIET(&opts
->quiet
, N_("suppress progress reporting")),
1574 OPT_CALLBACK_F(0, "recurse-submodules", NULL
,
1575 "checkout", "control recursive updating of submodules",
1576 PARSE_OPT_OPTARG
, option_parse_recurse_submodules_worktree_updater
),
1577 OPT_BOOL(0, "progress", &opts
->show_progress
, N_("force progress reporting")),
1578 OPT_BOOL('m', "merge", &opts
->merge
, N_("perform a 3-way merge with the new branch")),
1579 OPT_STRING(0, "conflict", &opts
->conflict_style
, N_("style"),
1580 N_("conflict style (merge, diff3, or zdiff3)")),
1583 struct option
*newopts
= parse_options_concat(prevopts
, options
);
1588 static struct option
*add_common_switch_branch_options(
1589 struct checkout_opts
*opts
, struct option
*prevopts
)
1591 struct option options
[] = {
1592 OPT_BOOL('d', "detach", &opts
->force_detach
, N_("detach HEAD at named commit")),
1593 OPT_CALLBACK_F('t', "track", &opts
->track
, "(direct|inherit)",
1594 N_("set branch tracking configuration"),
1596 parse_opt_tracking_mode
),
1597 OPT__FORCE(&opts
->force
, N_("force checkout (throw away local modifications)"),
1598 PARSE_OPT_NOCOMPLETE
),
1599 OPT_STRING(0, "orphan", &opts
->new_orphan_branch
, N_("new-branch"), N_("new unparented branch")),
1600 OPT_BOOL_F(0, "overwrite-ignore", &opts
->overwrite_ignore
,
1601 N_("update ignored files (default)"),
1602 PARSE_OPT_NOCOMPLETE
),
1603 OPT_BOOL(0, "ignore-other-worktrees", &opts
->ignore_other_worktrees
,
1604 N_("do not check if another worktree is holding the given ref")),
1607 struct option
*newopts
= parse_options_concat(prevopts
, options
);
1612 static struct option
*add_checkout_path_options(struct checkout_opts
*opts
,
1613 struct option
*prevopts
)
1615 struct option options
[] = {
1616 OPT_SET_INT_F('2', "ours", &opts
->writeout_stage
,
1617 N_("checkout our version for unmerged files"),
1618 2, PARSE_OPT_NONEG
),
1619 OPT_SET_INT_F('3', "theirs", &opts
->writeout_stage
,
1620 N_("checkout their version for unmerged files"),
1621 3, PARSE_OPT_NONEG
),
1622 OPT_BOOL('p', "patch", &opts
->patch_mode
, N_("select hunks interactively")),
1623 OPT_BOOL(0, "ignore-skip-worktree-bits", &opts
->ignore_skipworktree
,
1624 N_("do not limit pathspecs to sparse entries only")),
1625 OPT_PATHSPEC_FROM_FILE(&opts
->pathspec_from_file
),
1626 OPT_PATHSPEC_FILE_NUL(&opts
->pathspec_file_nul
),
1629 struct option
*newopts
= parse_options_concat(prevopts
, options
);
1634 /* create-branch option (either b or c) */
1635 static char cb_option
= 'b';
1637 static int checkout_main(int argc
, const char **argv
, const char *prefix
,
1638 struct checkout_opts
*opts
, struct option
*options
,
1639 const char * const usagestr
[],
1640 struct branch_info
*new_branch_info
)
1642 int parseopt_flags
= 0;
1644 opts
->overwrite_ignore
= 1;
1645 opts
->prefix
= prefix
;
1646 opts
->show_progress
= -1;
1648 git_config(git_checkout_config
, opts
);
1649 if (the_repository
->gitdir
) {
1650 prepare_repo_settings(the_repository
);
1651 the_repository
->settings
.command_requires_full_index
= 0;
1654 opts
->track
= BRANCH_TRACK_UNSPECIFIED
;
1656 if (!opts
->accept_pathspec
&& !opts
->accept_ref
)
1657 BUG("make up your mind, you need to take _something_");
1658 if (opts
->accept_pathspec
&& opts
->accept_ref
)
1659 parseopt_flags
= PARSE_OPT_KEEP_DASHDASH
;
1661 argc
= parse_options(argc
, argv
, prefix
, options
,
1662 usagestr
, parseopt_flags
);
1664 if (opts
->show_progress
< 0) {
1666 opts
->show_progress
= 0;
1668 opts
->show_progress
= isatty(2);
1671 if (opts
->conflict_style
) {
1672 opts
->merge
= 1; /* implied */
1673 git_xmerge_config("merge.conflictstyle", opts
->conflict_style
, NULL
);
1676 opts
->discard_changes
= 1;
1677 opts
->ignore_unmerged_opt
= "--force";
1678 opts
->ignore_unmerged
= 1;
1681 if ((!!opts
->new_branch
+ !!opts
->new_branch_force
+ !!opts
->new_orphan_branch
) > 1)
1682 die(_("options '-%c', '-%c', and '%s' cannot be used together"),
1683 cb_option
, toupper(cb_option
), "--orphan");
1685 if (opts
->overlay_mode
== 1 && opts
->patch_mode
)
1686 die(_("options '%s' and '%s' cannot be used together"), "-p", "--overlay");
1688 if (opts
->checkout_index
>= 0 || opts
->checkout_worktree
>= 0) {
1689 if (opts
->checkout_index
< 0)
1690 opts
->checkout_index
= 0;
1691 if (opts
->checkout_worktree
< 0)
1692 opts
->checkout_worktree
= 0;
1694 if (opts
->checkout_index
< 0)
1695 opts
->checkout_index
= -opts
->checkout_index
- 1;
1696 if (opts
->checkout_worktree
< 0)
1697 opts
->checkout_worktree
= -opts
->checkout_worktree
- 1;
1699 if (opts
->checkout_index
< 0 || opts
->checkout_worktree
< 0)
1700 BUG("these flags should be non-negative by now");
1702 * convenient shortcut: "git restore --staged [--worktree]" equals
1703 * "git restore --staged [--worktree] --source HEAD"
1705 if (!opts
->from_treeish
&& opts
->checkout_index
)
1706 opts
->from_treeish
= "HEAD";
1709 * From here on, new_branch will contain the branch to be checked out,
1710 * and new_branch_force and new_orphan_branch will tell us which one of
1711 * -b/-B/-c/-C/--orphan is being used.
1713 if (opts
->new_branch_force
)
1714 opts
->new_branch
= opts
->new_branch_force
;
1716 if (opts
->new_orphan_branch
)
1717 opts
->new_branch
= opts
->new_orphan_branch
;
1719 /* --track without -c/-C/-b/-B/--orphan should DWIM */
1720 if (opts
->track
!= BRANCH_TRACK_UNSPECIFIED
&& !opts
->new_branch
) {
1721 const char *argv0
= argv
[0];
1722 if (!argc
|| !strcmp(argv0
, "--"))
1723 die(_("--track needs a branch name"));
1724 skip_prefix(argv0
, "refs/", &argv0
);
1725 skip_prefix(argv0
, "remotes/", &argv0
);
1726 argv0
= strchr(argv0
, '/');
1727 if (!argv0
|| !argv0
[1])
1728 die(_("missing branch name; try -%c"), cb_option
);
1729 opts
->new_branch
= argv0
+ 1;
1733 * Extract branch name from command line arguments, so
1734 * all that is left is pathspecs.
1738 * 1) git checkout <tree> -- [<paths>]
1739 * 2) git checkout -- [<paths>]
1740 * 3) git checkout <something> [<paths>]
1742 * including "last branch" syntax and DWIM-ery for names of
1743 * remote branches, erroring out for invalid or ambiguous cases.
1745 if (argc
&& opts
->accept_ref
) {
1746 struct object_id rev
;
1748 !opts
->patch_mode
&&
1749 opts
->dwim_new_local_branch
&&
1750 opts
->track
== BRANCH_TRACK_UNSPECIFIED
&&
1752 int n
= parse_branchname_arg(argc
, argv
, dwim_ok
,
1753 new_branch_info
, opts
, &rev
);
1756 } else if (!opts
->accept_ref
&& opts
->from_treeish
) {
1757 struct object_id rev
;
1759 if (get_oid_mb(opts
->from_treeish
, &rev
))
1760 die(_("could not resolve %s"), opts
->from_treeish
);
1762 setup_new_branch_info_and_source_tree(new_branch_info
,
1764 opts
->from_treeish
);
1766 if (!opts
->source_tree
)
1767 die(_("reference is not a tree: %s"), opts
->from_treeish
);
1771 parse_pathspec(&opts
->pathspec
, 0,
1772 opts
->patch_mode
? PATHSPEC_PREFIX_ORIGIN
: 0,
1775 if (!opts
->pathspec
.nr
)
1776 die(_("invalid path specification"));
1779 * Try to give more helpful suggestion.
1780 * new_branch && argc > 1 will be caught later.
1782 if (opts
->new_branch
&& argc
== 1 && !new_branch_info
->commit
)
1783 die(_("'%s' is not a commit and a branch '%s' cannot be created from it"),
1784 argv
[0], opts
->new_branch
);
1786 if (opts
->force_detach
)
1787 die(_("git checkout: --detach does not take a path argument '%s'"),
1791 if (opts
->pathspec_from_file
) {
1792 if (opts
->pathspec
.nr
)
1793 die(_("'%s' and pathspec arguments cannot be used together"), "--pathspec-from-file");
1795 if (opts
->force_detach
)
1796 die(_("options '%s' and '%s' cannot be used together"), "--pathspec-from-file", "--detach");
1798 if (opts
->patch_mode
)
1799 die(_("options '%s' and '%s' cannot be used together"), "--pathspec-from-file", "--patch");
1801 parse_pathspec_file(&opts
->pathspec
, 0,
1803 prefix
, opts
->pathspec_from_file
, opts
->pathspec_file_nul
);
1804 } else if (opts
->pathspec_file_nul
) {
1805 die(_("the option '%s' requires '%s'"), "--pathspec-file-nul", "--pathspec-from-file");
1808 opts
->pathspec
.recursive
= 1;
1810 if (opts
->pathspec
.nr
) {
1811 if (1 < !!opts
->writeout_stage
+ !!opts
->force
+ !!opts
->merge
)
1812 die(_("git checkout: --ours/--theirs, --force and --merge are incompatible when\n"
1813 "checking out of the index."));
1815 if (opts
->accept_pathspec
&& !opts
->empty_pathspec_ok
&&
1816 !opts
->patch_mode
) /* patch mode is special */
1817 die(_("you must specify path(s) to restore"));
1820 if (opts
->new_branch
) {
1821 struct strbuf buf
= STRBUF_INIT
;
1823 if (opts
->new_branch_force
)
1824 opts
->branch_exists
= validate_branchname(opts
->new_branch
, &buf
);
1826 opts
->branch_exists
=
1827 validate_new_branchname(opts
->new_branch
, &buf
, 0);
1828 strbuf_release(&buf
);
1831 if (opts
->patch_mode
|| opts
->pathspec
.nr
)
1832 return checkout_paths(opts
, new_branch_info
);
1834 return checkout_branch(opts
, new_branch_info
);
1837 int cmd_checkout(int argc
, const char **argv
, const char *prefix
)
1839 struct checkout_opts opts
;
1840 struct option
*options
;
1841 struct option checkout_options
[] = {
1842 OPT_STRING('b', NULL
, &opts
.new_branch
, N_("branch"),
1843 N_("create and checkout a new branch")),
1844 OPT_STRING('B', NULL
, &opts
.new_branch_force
, N_("branch"),
1845 N_("create/reset and checkout a branch")),
1846 OPT_BOOL('l', NULL
, &opts
.new_branch_log
, N_("create reflog for new branch")),
1847 OPT_BOOL(0, "guess", &opts
.dwim_new_local_branch
,
1848 N_("second guess 'git checkout <no-such-branch>' (default)")),
1849 OPT_BOOL(0, "overlay", &opts
.overlay_mode
, N_("use overlay mode (default)")),
1853 struct branch_info new_branch_info
= { 0 };
1855 memset(&opts
, 0, sizeof(opts
));
1856 opts
.dwim_new_local_branch
= 1;
1857 opts
.switch_branch_doing_nothing_is_ok
= 1;
1858 opts
.only_merge_on_switching_branches
= 0;
1859 opts
.accept_ref
= 1;
1860 opts
.accept_pathspec
= 1;
1861 opts
.implicit_detach
= 1;
1862 opts
.can_switch_when_in_progress
= 1;
1863 opts
.orphan_from_empty_tree
= 0;
1864 opts
.empty_pathspec_ok
= 1;
1865 opts
.overlay_mode
= -1;
1866 opts
.checkout_index
= -2; /* default on */
1867 opts
.checkout_worktree
= -2; /* default on */
1869 if (argc
== 3 && !strcmp(argv
[1], "-b")) {
1871 * User ran 'git checkout -b <branch>' and expects
1872 * the same behavior as 'git switch -c <branch>'.
1874 opts
.switch_branch_doing_nothing_is_ok
= 0;
1875 opts
.only_merge_on_switching_branches
= 1;
1878 options
= parse_options_dup(checkout_options
);
1879 options
= add_common_options(&opts
, options
);
1880 options
= add_common_switch_branch_options(&opts
, options
);
1881 options
= add_checkout_path_options(&opts
, options
);
1883 ret
= checkout_main(argc
, argv
, prefix
, &opts
,
1884 options
, checkout_usage
, &new_branch_info
);
1885 branch_info_release(&new_branch_info
);
1886 clear_pathspec(&opts
.pathspec
);
1887 FREE_AND_NULL(options
);
1891 int cmd_switch(int argc
, const char **argv
, const char *prefix
)
1893 struct checkout_opts opts
;
1894 struct option
*options
= NULL
;
1895 struct option switch_options
[] = {
1896 OPT_STRING('c', "create", &opts
.new_branch
, N_("branch"),
1897 N_("create and switch to a new branch")),
1898 OPT_STRING('C', "force-create", &opts
.new_branch_force
, N_("branch"),
1899 N_("create/reset and switch to a branch")),
1900 OPT_BOOL(0, "guess", &opts
.dwim_new_local_branch
,
1901 N_("second guess 'git switch <no-such-branch>'")),
1902 OPT_BOOL(0, "discard-changes", &opts
.discard_changes
,
1903 N_("throw away local modifications")),
1907 struct branch_info new_branch_info
= { 0 };
1909 memset(&opts
, 0, sizeof(opts
));
1910 opts
.dwim_new_local_branch
= 1;
1911 opts
.accept_ref
= 1;
1912 opts
.accept_pathspec
= 0;
1913 opts
.switch_branch_doing_nothing_is_ok
= 0;
1914 opts
.only_merge_on_switching_branches
= 1;
1915 opts
.implicit_detach
= 0;
1916 opts
.can_switch_when_in_progress
= 0;
1917 opts
.orphan_from_empty_tree
= 1;
1918 opts
.overlay_mode
= -1;
1920 options
= parse_options_dup(switch_options
);
1921 options
= add_common_options(&opts
, options
);
1922 options
= add_common_switch_branch_options(&opts
, options
);
1926 ret
= checkout_main(argc
, argv
, prefix
, &opts
,
1927 options
, switch_branch_usage
, &new_branch_info
);
1928 branch_info_release(&new_branch_info
);
1929 FREE_AND_NULL(options
);
1933 int cmd_restore(int argc
, const char **argv
, const char *prefix
)
1935 struct checkout_opts opts
;
1936 struct option
*options
;
1937 struct option restore_options
[] = {
1938 OPT_STRING('s', "source", &opts
.from_treeish
, "<tree-ish>",
1939 N_("which tree-ish to checkout from")),
1940 OPT_BOOL('S', "staged", &opts
.checkout_index
,
1941 N_("restore the index")),
1942 OPT_BOOL('W', "worktree", &opts
.checkout_worktree
,
1943 N_("restore the working tree (default)")),
1944 OPT_BOOL(0, "ignore-unmerged", &opts
.ignore_unmerged
,
1945 N_("ignore unmerged entries")),
1946 OPT_BOOL(0, "overlay", &opts
.overlay_mode
, N_("use overlay mode")),
1950 struct branch_info new_branch_info
= { 0 };
1952 memset(&opts
, 0, sizeof(opts
));
1953 opts
.accept_ref
= 0;
1954 opts
.accept_pathspec
= 1;
1955 opts
.empty_pathspec_ok
= 0;
1956 opts
.overlay_mode
= 0;
1957 opts
.checkout_index
= -1; /* default off */
1958 opts
.checkout_worktree
= -2; /* default on */
1959 opts
.ignore_unmerged_opt
= "--ignore-unmerged";
1961 options
= parse_options_dup(restore_options
);
1962 options
= add_common_options(&opts
, options
);
1963 options
= add_checkout_path_options(&opts
, options
);
1965 ret
= checkout_main(argc
, argv
, prefix
, &opts
,
1966 options
, restore_usage
, &new_branch_info
);
1967 branch_info_release(&new_branch_info
);
1968 FREE_AND_NULL(options
);