1 #define USE_THE_INDEX_COMPATIBILITY_MACROS
6 #include "cache-tree.h"
14 #include "merge-recursive.h"
15 #include "object-store.h"
16 #include "parse-options.h"
19 #include "resolve-undo.h"
21 #include "run-command.h"
22 #include "submodule.h"
23 #include "submodule-config.h"
25 #include "tree-walk.h"
26 #include "unpack-trees.h"
27 #include "wt-status.h"
28 #include "xdiff-interface.h"
30 static const char * const checkout_usage
[] = {
31 N_("git checkout [<options>] <branch>"),
32 N_("git checkout [<options>] [<branch>] -- <file>..."),
36 static const char * const switch_branch_usage
[] = {
37 N_("git switch [<options>] [<branch>]"),
41 static const char * const restore_usage
[] = {
42 N_("git restore [<options>] [--source=<branch>] <file>..."),
46 struct checkout_opts
{
55 int ignore_skipworktree
;
56 int ignore_other_worktrees
;
58 int count_checkout_paths
;
60 int dwim_new_local_branch
;
64 int switch_branch_doing_nothing_is_ok
;
65 int only_merge_on_switching_branches
;
66 int can_switch_when_in_progress
;
67 int orphan_from_empty_tree
;
68 int empty_pathspec_ok
;
70 int checkout_worktree
;
71 const char *ignore_unmerged_opt
;
74 const char *new_branch
;
75 const char *new_branch_force
;
76 const char *new_orphan_branch
;
78 enum branch_track track
;
79 struct diff_options diff_options
;
84 struct pathspec pathspec
;
85 const char *from_treeish
;
86 struct tree
*source_tree
;
89 static int post_checkout_hook(struct commit
*old_commit
, struct commit
*new_commit
,
92 return run_hook_le(NULL
, "post-checkout",
93 oid_to_hex(old_commit
? &old_commit
->object
.oid
: &null_oid
),
94 oid_to_hex(new_commit
? &new_commit
->object
.oid
: &null_oid
),
95 changed
? "1" : "0", NULL
);
96 /* "new_commit" can be NULL when checking out from the index before
101 static int update_some(const struct object_id
*oid
, struct strbuf
*base
,
102 const char *pathname
, unsigned mode
, int stage
, void *context
)
105 struct cache_entry
*ce
;
109 return READ_TREE_RECURSIVE
;
111 len
= base
->len
+ strlen(pathname
);
112 ce
= make_empty_cache_entry(&the_index
, len
);
113 oidcpy(&ce
->oid
, oid
);
114 memcpy(ce
->name
, base
->buf
, base
->len
);
115 memcpy(ce
->name
+ base
->len
, pathname
, len
- base
->len
);
116 ce
->ce_flags
= create_ce_flags(0) | CE_UPDATE
;
117 ce
->ce_namelen
= len
;
118 ce
->ce_mode
= create_ce_mode(mode
);
121 * If the entry is the same as the current index, we can leave the old
122 * entry in place. Whether it is UPTODATE or not, checkout_entry will
123 * do the right thing.
125 pos
= cache_name_pos(ce
->name
, ce
->ce_namelen
);
127 struct cache_entry
*old
= active_cache
[pos
];
128 if (ce
->ce_mode
== old
->ce_mode
&&
129 oideq(&ce
->oid
, &old
->oid
)) {
130 old
->ce_flags
|= CE_UPDATE
;
131 discard_cache_entry(ce
);
136 add_cache_entry(ce
, ADD_CACHE_OK_TO_ADD
| ADD_CACHE_OK_TO_REPLACE
);
140 static int read_tree_some(struct tree
*tree
, const struct pathspec
*pathspec
)
142 read_tree_recursive(the_repository
, tree
, "", 0, 0,
143 pathspec
, update_some
, NULL
);
145 /* update the index with the given tree's info
146 * for all args, expanding wildcards, and exit
147 * with any non-zero return code.
152 static int skip_same_name(const struct cache_entry
*ce
, int pos
)
154 while (++pos
< active_nr
&&
155 !strcmp(active_cache
[pos
]->name
, ce
->name
))
160 static int check_stage(int stage
, const struct cache_entry
*ce
, int pos
,
163 while (pos
< active_nr
&&
164 !strcmp(active_cache
[pos
]->name
, ce
->name
)) {
165 if (ce_stage(active_cache
[pos
]) == stage
)
172 return error(_("path '%s' does not have our version"), ce
->name
);
174 return error(_("path '%s' does not have their version"), ce
->name
);
177 static int check_stages(unsigned stages
, const struct cache_entry
*ce
, int pos
)
180 const char *name
= ce
->name
;
182 while (pos
< active_nr
) {
183 ce
= active_cache
[pos
];
184 if (strcmp(name
, ce
->name
))
186 seen
|= (1 << ce_stage(ce
));
189 if ((stages
& seen
) != stages
)
190 return error(_("path '%s' does not have all necessary versions"),
195 static int checkout_stage(int stage
, const struct cache_entry
*ce
, int pos
,
196 const struct checkout
*state
, int *nr_checkouts
,
199 while (pos
< active_nr
&&
200 !strcmp(active_cache
[pos
]->name
, ce
->name
)) {
201 if (ce_stage(active_cache
[pos
]) == stage
)
202 return checkout_entry(active_cache
[pos
], state
,
211 return error(_("path '%s' does not have our version"), ce
->name
);
213 return error(_("path '%s' does not have their version"), ce
->name
);
216 static int checkout_merged(int pos
, const struct checkout
*state
, int *nr_checkouts
)
218 struct cache_entry
*ce
= active_cache
[pos
];
219 const char *path
= ce
->name
;
220 mmfile_t ancestor
, ours
, theirs
;
222 struct object_id oid
;
223 mmbuffer_t result_buf
;
224 struct object_id threeway
[3];
227 memset(threeway
, 0, sizeof(threeway
));
228 while (pos
< active_nr
) {
230 stage
= ce_stage(ce
);
231 if (!stage
|| strcmp(path
, ce
->name
))
233 oidcpy(&threeway
[stage
- 1], &ce
->oid
);
235 mode
= create_ce_mode(ce
->ce_mode
);
237 ce
= active_cache
[pos
];
239 if (is_null_oid(&threeway
[1]) || is_null_oid(&threeway
[2]))
240 return error(_("path '%s' does not have necessary versions"), path
);
242 read_mmblob(&ancestor
, &threeway
[0]);
243 read_mmblob(&ours
, &threeway
[1]);
244 read_mmblob(&theirs
, &threeway
[2]);
247 * NEEDSWORK: re-create conflicts from merges with
248 * merge.renormalize set, too
250 status
= ll_merge(&result_buf
, path
, &ancestor
, "base",
251 &ours
, "ours", &theirs
, "theirs",
252 state
->istate
, NULL
);
256 if (status
< 0 || !result_buf
.ptr
) {
257 free(result_buf
.ptr
);
258 return error(_("path '%s': cannot merge"), path
);
263 * There is absolutely no reason to write this as a blob object
264 * and create a phony cache entry. This hack is primarily to get
265 * to the write_entry() machinery that massages the contents to
266 * work-tree format and writes out which only allows it for a
267 * cache entry. The code in write_entry() needs to be refactored
268 * to allow us to feed a <buffer, size, mode> instead of a cache
269 * entry. Such a refactoring would help merge_recursive as well
270 * (it also writes the merge result to the object database even
271 * when it may contain conflicts).
273 if (write_object_file(result_buf
.ptr
, result_buf
.size
, blob_type
, &oid
))
274 die(_("Unable to add merge result for '%s'"), path
);
275 free(result_buf
.ptr
);
276 ce
= make_transient_cache_entry(mode
, &oid
, path
, 2);
278 die(_("make_cache_entry failed for path '%s'"), path
);
279 status
= checkout_entry(ce
, state
, NULL
, nr_checkouts
);
280 discard_cache_entry(ce
);
284 static void mark_ce_for_checkout_overlay(struct cache_entry
*ce
,
286 const struct checkout_opts
*opts
)
288 ce
->ce_flags
&= ~CE_MATCHED
;
289 if (!opts
->ignore_skipworktree
&& ce_skip_worktree(ce
))
291 if (opts
->source_tree
&& !(ce
->ce_flags
& CE_UPDATE
))
293 * "git checkout tree-ish -- path", but this entry
294 * is in the original index but is not in tree-ish
295 * or does not match the pathspec; it will not be
296 * checked out to the working tree. We will not do
297 * anything to this entry at all.
301 * Either this entry came from the tree-ish we are
302 * checking the paths out of, or we are checking out
305 * If it comes from the tree-ish, we already know it
306 * matches the pathspec and could just stamp
307 * CE_MATCHED to it from update_some(). But we still
308 * need ps_matched and read_tree_recursive (and
309 * eventually tree_entry_interesting) cannot fill
310 * ps_matched yet. Once it can, we can avoid calling
311 * match_pathspec() for _all_ entries when
312 * opts->source_tree != NULL.
314 if (ce_path_match(&the_index
, ce
, &opts
->pathspec
, ps_matched
))
315 ce
->ce_flags
|= CE_MATCHED
;
318 static void mark_ce_for_checkout_no_overlay(struct cache_entry
*ce
,
320 const struct checkout_opts
*opts
)
322 ce
->ce_flags
&= ~CE_MATCHED
;
323 if (!opts
->ignore_skipworktree
&& ce_skip_worktree(ce
))
325 if (ce_path_match(&the_index
, ce
, &opts
->pathspec
, ps_matched
)) {
326 ce
->ce_flags
|= CE_MATCHED
;
327 if (opts
->source_tree
&& !(ce
->ce_flags
& CE_UPDATE
))
329 * In overlay mode, but the path is not in
330 * tree-ish, which means we should remove it
331 * from the index and the working tree.
333 ce
->ce_flags
|= CE_REMOVE
| CE_WT_REMOVE
;
337 static int checkout_worktree(const struct checkout_opts
*opts
)
339 struct checkout state
= CHECKOUT_INIT
;
340 int nr_checkouts
= 0, nr_unmerged
= 0;
345 state
.refresh_cache
= 1;
346 state
.istate
= &the_index
;
348 enable_delayed_checkout(&state
);
349 for (pos
= 0; pos
< active_nr
; pos
++) {
350 struct cache_entry
*ce
= active_cache
[pos
];
351 if (ce
->ce_flags
& CE_MATCHED
) {
353 errs
|= checkout_entry(ce
, &state
,
354 NULL
, &nr_checkouts
);
357 if (opts
->writeout_stage
)
358 errs
|= checkout_stage(opts
->writeout_stage
,
361 &nr_checkouts
, opts
->overlay_mode
);
362 else if (opts
->merge
)
363 errs
|= checkout_merged(pos
, &state
,
365 pos
= skip_same_name(ce
, pos
) - 1;
368 remove_marked_cache_entries(&the_index
, 1);
369 remove_scheduled_dirs();
370 errs
|= finish_delayed_checkout(&state
, &nr_checkouts
);
372 if (opts
->count_checkout_paths
) {
374 fprintf_ln(stderr
, Q_("Recreated %d merge conflict",
375 "Recreated %d merge conflicts",
378 if (opts
->source_tree
)
379 fprintf_ln(stderr
, Q_("Updated %d path from %s",
380 "Updated %d paths from %s",
383 find_unique_abbrev(&opts
->source_tree
->object
.oid
,
385 else if (!nr_unmerged
|| nr_checkouts
)
386 fprintf_ln(stderr
, Q_("Updated %d path from the index",
387 "Updated %d paths from the index",
395 static int checkout_paths(const struct checkout_opts
*opts
,
396 const char *revision
)
399 static char *ps_matched
;
400 struct object_id rev
;
403 struct lock_file lock_file
= LOCK_INIT
;
406 trace2_cmd_mode(opts
->patch_mode
? "patch" : "path");
408 if (opts
->track
!= BRANCH_TRACK_UNSPECIFIED
)
409 die(_("'%s' cannot be used with updating paths"), "--track");
411 if (opts
->new_branch_log
)
412 die(_("'%s' cannot be used with updating paths"), "-l");
414 if (opts
->ignore_unmerged
&& opts
->patch_mode
)
415 die(_("'%s' cannot be used with updating paths"),
416 opts
->ignore_unmerged_opt
);
418 if (opts
->force_detach
)
419 die(_("'%s' cannot be used with updating paths"), "--detach");
421 if (opts
->merge
&& opts
->patch_mode
)
422 die(_("'%s' cannot be used with %s"), "--merge", "--patch");
424 if (opts
->ignore_unmerged
&& opts
->merge
)
425 die(_("'%s' cannot be used with %s"),
426 opts
->ignore_unmerged_opt
, "-m");
428 if (opts
->new_branch
)
429 die(_("Cannot update paths and switch to branch '%s' at the same time."),
432 if (!opts
->checkout_worktree
&& !opts
->checkout_index
)
433 die(_("neither '%s' or '%s' is specified"),
434 "--staged", "--worktree");
436 if (!opts
->checkout_worktree
&& !opts
->from_treeish
)
437 die(_("'%s' must be used when '%s' is not specified"),
438 "--worktree", "--source");
440 if (opts
->checkout_index
&& !opts
->checkout_worktree
&&
441 opts
->writeout_stage
)
442 die(_("'%s' or '%s' cannot be used with %s"),
443 "--ours", "--theirs", "--staged");
445 if (opts
->checkout_index
&& !opts
->checkout_worktree
&&
447 die(_("'%s' or '%s' cannot be used with %s"),
448 "--merge", "--conflict", "--staged");
450 if (opts
->patch_mode
) {
451 const char *patch_mode
;
453 if (opts
->checkout_index
&& opts
->checkout_worktree
)
454 patch_mode
= "--patch=checkout";
455 else if (opts
->checkout_index
&& !opts
->checkout_worktree
)
456 patch_mode
= "--patch=reset";
457 else if (!opts
->checkout_index
&& opts
->checkout_worktree
)
458 patch_mode
= "--patch=worktree";
460 BUG("either flag must have been set, worktree=%d, index=%d",
461 opts
->checkout_worktree
, opts
->checkout_index
);
462 return run_add_interactive(revision
, patch_mode
, &opts
->pathspec
);
465 repo_hold_locked_index(the_repository
, &lock_file
, LOCK_DIE_ON_ERROR
);
466 if (read_cache_preload(&opts
->pathspec
) < 0)
467 return error(_("index file corrupt"));
469 if (opts
->source_tree
)
470 read_tree_some(opts
->source_tree
, &opts
->pathspec
);
472 ps_matched
= xcalloc(opts
->pathspec
.nr
, 1);
475 * Make sure all pathspecs participated in locating the paths
478 for (pos
= 0; pos
< active_nr
; pos
++)
479 if (opts
->overlay_mode
)
480 mark_ce_for_checkout_overlay(active_cache
[pos
],
484 mark_ce_for_checkout_no_overlay(active_cache
[pos
],
488 if (report_path_error(ps_matched
, &opts
->pathspec
, opts
->prefix
)) {
494 /* "checkout -m path" to recreate conflicted state */
496 unmerge_marked_index(&the_index
);
498 /* Any unmerged paths? */
499 for (pos
= 0; pos
< active_nr
; pos
++) {
500 const struct cache_entry
*ce
= active_cache
[pos
];
501 if (ce
->ce_flags
& CE_MATCHED
) {
504 if (opts
->ignore_unmerged
) {
506 warning(_("path '%s' is unmerged"), ce
->name
);
507 } else if (opts
->writeout_stage
) {
508 errs
|= check_stage(opts
->writeout_stage
, ce
, pos
, opts
->overlay_mode
);
509 } else if (opts
->merge
) {
510 errs
|= check_stages((1<<2) | (1<<3), ce
, pos
);
513 error(_("path '%s' is unmerged"), ce
->name
);
515 pos
= skip_same_name(ce
, pos
) - 1;
521 /* Now we are committed to check them out */
522 if (opts
->checkout_worktree
)
523 errs
|= checkout_worktree(opts
);
526 * Allow updating the index when checking out from the index.
527 * This is to save new stat info.
529 if (opts
->checkout_worktree
&& !opts
->checkout_index
&& !opts
->source_tree
)
532 checkout_index
= opts
->checkout_index
;
534 if (checkout_index
) {
535 if (write_locked_index(&the_index
, &lock_file
, COMMIT_LOCK
))
536 die(_("unable to write new index file"));
539 * NEEDSWORK: if --worktree is not specified, we
540 * should save stat info of checked out files in the
541 * index to avoid the next (potentially costly)
542 * refresh. But it's a bit tricker to do...
544 rollback_lock_file(&lock_file
);
547 read_ref_full("HEAD", 0, &rev
, NULL
);
548 head
= lookup_commit_reference_gently(the_repository
, &rev
, 1);
550 errs
|= post_checkout_hook(head
, head
, 0);
554 static void show_local_changes(struct object
*head
,
555 const struct diff_options
*opts
)
558 /* I think we want full paths, even if we're in a subdirectory. */
559 repo_init_revisions(the_repository
, &rev
, NULL
);
560 rev
.diffopt
.flags
= opts
->flags
;
561 rev
.diffopt
.output_format
|= DIFF_FORMAT_NAME_STATUS
;
562 diff_setup_done(&rev
.diffopt
);
563 add_pending_object(&rev
, head
, NULL
);
564 run_diff_index(&rev
, 0);
567 static void describe_detached_head(const char *msg
, struct commit
*commit
)
569 struct strbuf sb
= STRBUF_INIT
;
571 if (!parse_commit(commit
))
572 pp_commit_easy(CMIT_FMT_ONELINE
, commit
, &sb
);
573 if (print_sha1_ellipsis()) {
574 fprintf(stderr
, "%s %s... %s\n", msg
,
575 find_unique_abbrev(&commit
->object
.oid
, DEFAULT_ABBREV
), sb
.buf
);
577 fprintf(stderr
, "%s %s %s\n", msg
,
578 find_unique_abbrev(&commit
->object
.oid
, DEFAULT_ABBREV
), sb
.buf
);
583 static int reset_tree(struct tree
*tree
, const struct checkout_opts
*o
,
584 int worktree
, int *writeout_error
)
586 struct unpack_trees_options opts
;
587 struct tree_desc tree_desc
;
589 memset(&opts
, 0, sizeof(opts
));
591 opts
.update
= worktree
;
592 opts
.skip_unmerged
= !worktree
;
595 opts
.fn
= oneway_merge
;
596 opts
.verbose_update
= o
->show_progress
;
597 opts
.src_index
= &the_index
;
598 opts
.dst_index
= &the_index
;
600 init_tree_desc(&tree_desc
, tree
->buffer
, tree
->size
);
601 switch (unpack_trees(1, &tree_desc
, &opts
)) {
605 * We return 0 nevertheless, as the index is all right
606 * and more importantly we have made best efforts to
607 * update paths in the work tree, and we cannot revert
619 const char *name
; /* The short name used */
620 const char *path
; /* The full name of a real branch */
621 struct commit
*commit
; /* The named commit */
623 * if not null the branch is detached because it's already
624 * checked out in this checkout
629 static void setup_branch_path(struct branch_info
*branch
)
631 struct strbuf buf
= STRBUF_INIT
;
633 strbuf_branchname(&buf
, branch
->name
, INTERPRET_BRANCH_LOCAL
);
634 if (strcmp(buf
.buf
, branch
->name
))
635 branch
->name
= xstrdup(buf
.buf
);
636 strbuf_splice(&buf
, 0, 0, "refs/heads/", 11);
637 branch
->path
= strbuf_detach(&buf
, NULL
);
640 static int merge_working_tree(const struct checkout_opts
*opts
,
641 struct branch_info
*old_branch_info
,
642 struct branch_info
*new_branch_info
,
646 struct lock_file lock_file
= LOCK_INIT
;
647 struct tree
*new_tree
;
649 hold_locked_index(&lock_file
, LOCK_DIE_ON_ERROR
);
650 if (read_cache_preload(NULL
) < 0)
651 return error(_("index file corrupt"));
653 resolve_undo_clear();
654 if (opts
->new_orphan_branch
&& opts
->orphan_from_empty_tree
) {
655 if (new_branch_info
->commit
)
656 BUG("'switch --orphan' should never accept a commit as starting point");
657 new_tree
= parse_tree_indirect(the_hash_algo
->empty_tree
);
659 new_tree
= get_commit_tree(new_branch_info
->commit
);
660 if (opts
->discard_changes
) {
661 ret
= reset_tree(new_tree
, opts
, 1, writeout_error
);
665 struct tree_desc trees
[2];
667 struct unpack_trees_options topts
;
669 memset(&topts
, 0, sizeof(topts
));
671 topts
.src_index
= &the_index
;
672 topts
.dst_index
= &the_index
;
674 setup_unpack_trees_porcelain(&topts
, "checkout");
676 refresh_cache(REFRESH_QUIET
);
678 if (unmerged_cache()) {
679 error(_("you need to resolve your current index first"));
683 /* 2-way merge to the new branch */
684 topts
.initial_checkout
= is_cache_unborn();
687 topts
.gently
= opts
->merge
&& old_branch_info
->commit
;
688 topts
.verbose_update
= opts
->show_progress
;
689 topts
.fn
= twoway_merge
;
690 if (opts
->overwrite_ignore
) {
691 topts
.dir
= xcalloc(1, sizeof(*topts
.dir
));
692 topts
.dir
->flags
|= DIR_SHOW_IGNORED
;
693 setup_standard_excludes(topts
.dir
);
695 tree
= parse_tree_indirect(old_branch_info
->commit
?
696 &old_branch_info
->commit
->object
.oid
:
697 the_hash_algo
->empty_tree
);
698 init_tree_desc(&trees
[0], tree
->buffer
, tree
->size
);
699 parse_tree(new_tree
);
701 init_tree_desc(&trees
[1], tree
->buffer
, tree
->size
);
703 ret
= unpack_trees(2, trees
, &topts
);
704 clear_unpack_trees_porcelain(&topts
);
707 * Unpack couldn't do a trivial merge; either
708 * give up or do a real merge, depending on
709 * whether the merge flag was used.
713 struct merge_options o
;
718 * Without old_branch_info->commit, the below is the same as
719 * the two-tree unpack we already tried and failed.
721 if (!old_branch_info
->commit
)
724 /* Do more real merge */
727 * We update the index fully, then write the
728 * tree from the index, then merge the new
729 * branch with the current tree, with the old
730 * branch as the base. Then we reset the index
731 * (but not the working tree) to the new
732 * branch, leaving the working tree as the
733 * merged version, but skipping unmerged
734 * entries in the index.
737 add_files_to_cache(NULL
, NULL
, 0);
739 * NEEDSWORK: carrying over local changes
740 * when branches have different end-of-line
741 * normalization (or clean+smudge rules) is
742 * a pain; plumb in an option to set
745 init_merge_options(&o
, the_repository
);
747 work
= write_tree_from_memory(&o
);
749 ret
= reset_tree(new_tree
,
754 o
.ancestor
= old_branch_info
->name
;
755 o
.branch1
= new_branch_info
->name
;
757 ret
= merge_trees(&o
,
760 get_commit_tree(old_branch_info
->commit
),
764 ret
= reset_tree(new_tree
,
767 strbuf_release(&o
.obuf
);
773 if (!active_cache_tree
)
774 active_cache_tree
= cache_tree();
776 if (!cache_tree_fully_valid(active_cache_tree
))
777 cache_tree_update(&the_index
, WRITE_TREE_SILENT
| WRITE_TREE_REPAIR
);
779 if (write_locked_index(&the_index
, &lock_file
, COMMIT_LOCK
))
780 die(_("unable to write new index file"));
782 if (!opts
->discard_changes
&& !opts
->quiet
&& new_branch_info
->commit
)
783 show_local_changes(&new_branch_info
->commit
->object
, &opts
->diff_options
);
788 static void report_tracking(struct branch_info
*new_branch_info
)
790 struct strbuf sb
= STRBUF_INIT
;
791 struct branch
*branch
= branch_get(new_branch_info
->name
);
793 if (!format_tracking_info(branch
, &sb
, AHEAD_BEHIND_FULL
))
795 fputs(sb
.buf
, stdout
);
799 static void update_refs_for_switch(const struct checkout_opts
*opts
,
800 struct branch_info
*old_branch_info
,
801 struct branch_info
*new_branch_info
)
803 struct strbuf msg
= STRBUF_INIT
;
804 const char *old_desc
, *reflog_msg
;
805 if (opts
->new_branch
) {
806 if (opts
->new_orphan_branch
) {
809 refname
= mkpathdup("refs/heads/%s", opts
->new_orphan_branch
);
810 if (opts
->new_branch_log
&&
811 !should_autocreate_reflog(refname
)) {
813 struct strbuf err
= STRBUF_INIT
;
815 ret
= safe_create_reflog(refname
, 1, &err
);
817 fprintf(stderr
, _("Can not do reflog for '%s': %s\n"),
818 opts
->new_orphan_branch
, err
.buf
);
819 strbuf_release(&err
);
823 strbuf_release(&err
);
828 create_branch(the_repository
,
829 opts
->new_branch
, new_branch_info
->name
,
830 opts
->new_branch_force
? 1 : 0,
831 opts
->new_branch_force
? 1 : 0,
832 opts
->new_branch_log
,
835 new_branch_info
->name
= opts
->new_branch
;
836 setup_branch_path(new_branch_info
);
839 old_desc
= old_branch_info
->name
;
840 if (!old_desc
&& old_branch_info
->commit
)
841 old_desc
= oid_to_hex(&old_branch_info
->commit
->object
.oid
);
843 reflog_msg
= getenv("GIT_REFLOG_ACTION");
845 strbuf_addf(&msg
, "checkout: moving from %s to %s",
846 old_desc
? old_desc
: "(invalid)", new_branch_info
->name
);
848 strbuf_insert(&msg
, 0, reflog_msg
, strlen(reflog_msg
));
850 if (!strcmp(new_branch_info
->name
, "HEAD") && !new_branch_info
->path
&& !opts
->force_detach
) {
852 } else if (opts
->force_detach
|| !new_branch_info
->path
) { /* No longer on any branch. */
853 update_ref(msg
.buf
, "HEAD", &new_branch_info
->commit
->object
.oid
, NULL
,
854 REF_NO_DEREF
, UPDATE_REFS_DIE_ON_ERR
);
856 if (old_branch_info
->path
&&
857 advice_detached_head
&& !opts
->force_detach
)
858 detach_advice(new_branch_info
->name
);
859 describe_detached_head(_("HEAD is now at"), new_branch_info
->commit
);
861 } else if (new_branch_info
->path
) { /* Switch branches. */
862 if (create_symref("HEAD", new_branch_info
->path
, msg
.buf
) < 0)
863 die(_("unable to update HEAD"));
865 if (old_branch_info
->path
&& !strcmp(new_branch_info
->path
, old_branch_info
->path
)) {
866 if (opts
->new_branch_force
)
867 fprintf(stderr
, _("Reset branch '%s'\n"),
868 new_branch_info
->name
);
870 fprintf(stderr
, _("Already on '%s'\n"),
871 new_branch_info
->name
);
872 } else if (opts
->new_branch
) {
873 if (opts
->branch_exists
)
874 fprintf(stderr
, _("Switched to and reset branch '%s'\n"), new_branch_info
->name
);
876 fprintf(stderr
, _("Switched to a new branch '%s'\n"), new_branch_info
->name
);
878 fprintf(stderr
, _("Switched to branch '%s'\n"),
879 new_branch_info
->name
);
882 if (old_branch_info
->path
&& old_branch_info
->name
) {
883 if (!ref_exists(old_branch_info
->path
) && reflog_exists(old_branch_info
->path
))
884 delete_reflog(old_branch_info
->path
);
887 remove_branch_state(the_repository
, !opts
->quiet
);
888 strbuf_release(&msg
);
890 (new_branch_info
->path
|| (!opts
->force_detach
&& !strcmp(new_branch_info
->name
, "HEAD"))))
891 report_tracking(new_branch_info
);
894 static int add_pending_uninteresting_ref(const char *refname
,
895 const struct object_id
*oid
,
896 int flags
, void *cb_data
)
898 add_pending_oid(cb_data
, refname
, oid
, UNINTERESTING
);
902 static void describe_one_orphan(struct strbuf
*sb
, struct commit
*commit
)
904 strbuf_addstr(sb
, " ");
905 strbuf_add_unique_abbrev(sb
, &commit
->object
.oid
, DEFAULT_ABBREV
);
906 strbuf_addch(sb
, ' ');
907 if (!parse_commit(commit
))
908 pp_commit_easy(CMIT_FMT_ONELINE
, commit
, sb
);
909 strbuf_addch(sb
, '\n');
912 #define ORPHAN_CUTOFF 4
913 static void suggest_reattach(struct commit
*commit
, struct rev_info
*revs
)
915 struct commit
*c
, *last
= NULL
;
916 struct strbuf sb
= STRBUF_INIT
;
918 while ((c
= get_revision(revs
)) != NULL
) {
919 if (lost
< ORPHAN_CUTOFF
)
920 describe_one_orphan(&sb
, c
);
924 if (ORPHAN_CUTOFF
< lost
) {
925 int more
= lost
- ORPHAN_CUTOFF
;
927 describe_one_orphan(&sb
, last
);
929 strbuf_addf(&sb
, _(" ... and %d more.\n"), more
);
934 /* The singular version */
935 "Warning: you are leaving %d commit behind, "
937 "any of your branches:\n\n"
939 /* The plural version */
940 "Warning: you are leaving %d commits behind, "
942 "any of your branches:\n\n"
944 /* Give ngettext() the count */
950 if (advice_detached_head
)
953 /* The singular version */
954 "If you want to keep it by creating a new branch, "
955 "this may be a good time\nto do so with:\n\n"
956 " git branch <new-branch-name> %s\n\n",
957 /* The plural version */
958 "If you want to keep them by creating a new branch, "
959 "this may be a good time\nto do so with:\n\n"
960 " git branch <new-branch-name> %s\n\n",
961 /* Give ngettext() the count */
963 find_unique_abbrev(&commit
->object
.oid
, DEFAULT_ABBREV
));
967 * We are about to leave commit that was at the tip of a detached
968 * HEAD. If it is not reachable from any ref, this is the last chance
969 * for the user to do so without resorting to reflog.
971 static void orphaned_commit_warning(struct commit
*old_commit
, struct commit
*new_commit
)
973 struct rev_info revs
;
974 struct object
*object
= &old_commit
->object
;
976 repo_init_revisions(the_repository
, &revs
, NULL
);
977 setup_revisions(0, NULL
, &revs
, NULL
);
979 object
->flags
&= ~UNINTERESTING
;
980 add_pending_object(&revs
, object
, oid_to_hex(&object
->oid
));
982 for_each_ref(add_pending_uninteresting_ref
, &revs
);
984 add_pending_oid(&revs
, "HEAD",
985 &new_commit
->object
.oid
,
988 if (prepare_revision_walk(&revs
))
989 die(_("internal error in revision walk"));
990 if (!(old_commit
->object
.flags
& UNINTERESTING
))
991 suggest_reattach(old_commit
, &revs
);
993 describe_detached_head(_("Previous HEAD position was"), old_commit
);
995 /* Clean up objects used, as they will be reused. */
996 clear_commit_marks_all(ALL_REV_FLAGS
);
999 static int switch_branches(const struct checkout_opts
*opts
,
1000 struct branch_info
*new_branch_info
)
1003 struct branch_info old_branch_info
;
1005 struct object_id rev
;
1006 int flag
, writeout_error
= 0;
1009 trace2_cmd_mode("branch");
1011 memset(&old_branch_info
, 0, sizeof(old_branch_info
));
1012 old_branch_info
.path
= path_to_free
= resolve_refdup("HEAD", 0, &rev
, &flag
);
1013 if (old_branch_info
.path
)
1014 old_branch_info
.commit
= lookup_commit_reference_gently(the_repository
, &rev
, 1);
1015 if (!(flag
& REF_ISSYMREF
))
1016 old_branch_info
.path
= NULL
;
1018 if (old_branch_info
.path
)
1019 skip_prefix(old_branch_info
.path
, "refs/heads/", &old_branch_info
.name
);
1021 if (opts
->new_orphan_branch
&& opts
->orphan_from_empty_tree
) {
1022 if (new_branch_info
->name
)
1023 BUG("'switch --orphan' should never accept a commit as starting point");
1024 new_branch_info
->commit
= NULL
;
1025 new_branch_info
->name
= "(empty)";
1029 if (!new_branch_info
->name
) {
1030 new_branch_info
->name
= "HEAD";
1031 new_branch_info
->commit
= old_branch_info
.commit
;
1032 if (!new_branch_info
->commit
)
1033 die(_("You are on a branch yet to be born"));
1034 parse_commit_or_die(new_branch_info
->commit
);
1036 if (opts
->only_merge_on_switching_branches
)
1041 ret
= merge_working_tree(opts
, &old_branch_info
, new_branch_info
, &writeout_error
);
1048 if (!opts
->quiet
&& !old_branch_info
.path
&& old_branch_info
.commit
&& new_branch_info
->commit
!= old_branch_info
.commit
)
1049 orphaned_commit_warning(old_branch_info
.commit
, new_branch_info
->commit
);
1051 update_refs_for_switch(opts
, &old_branch_info
, new_branch_info
);
1053 ret
= post_checkout_hook(old_branch_info
.commit
, new_branch_info
->commit
, 1);
1055 return ret
|| writeout_error
;
1058 static int git_checkout_config(const char *var
, const char *value
, void *cb
)
1060 if (!strcmp(var
, "diff.ignoresubmodules")) {
1061 struct checkout_opts
*opts
= cb
;
1062 handle_ignore_submodules_arg(&opts
->diff_options
, value
);
1066 if (starts_with(var
, "submodule."))
1067 return git_default_submodule_config(var
, value
, NULL
);
1069 return git_xmerge_config(var
, value
, NULL
);
1072 static void setup_new_branch_info_and_source_tree(
1073 struct branch_info
*new_branch_info
,
1074 struct checkout_opts
*opts
,
1075 struct object_id
*rev
,
1078 struct tree
**source_tree
= &opts
->source_tree
;
1079 struct object_id branch_rev
;
1081 new_branch_info
->name
= arg
;
1082 setup_branch_path(new_branch_info
);
1084 if (!check_refname_format(new_branch_info
->path
, 0) &&
1085 !read_ref(new_branch_info
->path
, &branch_rev
))
1086 oidcpy(rev
, &branch_rev
);
1088 new_branch_info
->path
= NULL
; /* not an existing branch */
1090 new_branch_info
->commit
= lookup_commit_reference_gently(the_repository
, rev
, 1);
1091 if (!new_branch_info
->commit
) {
1093 *source_tree
= parse_tree_indirect(rev
);
1095 parse_commit_or_die(new_branch_info
->commit
);
1096 *source_tree
= get_commit_tree(new_branch_info
->commit
);
1100 static int parse_branchname_arg(int argc
, const char **argv
,
1101 int dwim_new_local_branch_ok
,
1102 struct branch_info
*new_branch_info
,
1103 struct checkout_opts
*opts
,
1104 struct object_id
*rev
,
1105 int *dwim_remotes_matched
)
1107 const char **new_branch
= &opts
->new_branch
;
1111 int has_dash_dash
= 0;
1115 * case 1: git checkout <ref> -- [<paths>]
1117 * <ref> must be a valid tree, everything after the '--' must be
1120 * case 2: git checkout -- [<paths>]
1122 * everything after the '--' must be paths.
1124 * case 3: git checkout <something> [--]
1126 * (a) If <something> is a commit, that is to
1127 * switch to the branch or detach HEAD at it. As a special case,
1128 * if <something> is A...B (missing A or B means HEAD but you can
1129 * omit at most one side), and if there is a unique merge base
1130 * between A and B, A...B names that merge base.
1132 * (b) If <something> is _not_ a commit, either "--" is present
1133 * or <something> is not a path, no -t or -b was given, and
1134 * and there is a tracking branch whose name is <something>
1135 * in one and only one remote (or if the branch exists on the
1136 * remote named in checkout.defaultRemote), then this is a
1137 * short-hand to fork local <something> from that
1138 * remote-tracking branch.
1140 * (c) Otherwise, if "--" is present, treat it like case (1).
1143 * - if it's a reference, treat it like case (1)
1144 * - else if it's a path, treat it like case (2)
1147 * case 4: git checkout <something> <paths>
1149 * The first argument must not be ambiguous.
1150 * - If it's *only* a reference, treat it like case (1).
1151 * - If it's only a path, treat it like case (2).
1158 if (!opts
->accept_pathspec
) {
1160 die(_("only one reference expected"));
1161 has_dash_dash
= 1; /* helps disambiguate */
1166 for (i
= 0; i
< argc
; i
++) {
1167 if (opts
->accept_pathspec
&& !strcmp(argv
[i
], "--")) {
1172 if (dash_dash_pos
== 0)
1173 return 1; /* case (2) */
1174 else if (dash_dash_pos
== 1)
1175 has_dash_dash
= 1; /* case (3) or (1) */
1176 else if (dash_dash_pos
>= 2)
1177 die(_("only one reference expected, %d given."), dash_dash_pos
);
1178 opts
->count_checkout_paths
= !opts
->quiet
&& !has_dash_dash
;
1180 if (!strcmp(arg
, "-"))
1183 if (get_oid_mb(arg
, rev
)) {
1185 * Either case (3) or (4), with <something> not being
1186 * a commit, or an attempt to use case (1) with an
1189 * It's likely an error, but we need to find out if
1190 * we should auto-create the branch, case (3).(b).
1192 int recover_with_dwim
= dwim_new_local_branch_ok
;
1194 int could_be_checkout_paths
= !has_dash_dash
&&
1195 check_filename(opts
->prefix
, arg
);
1197 if (!has_dash_dash
&& !no_wildcard(arg
))
1198 recover_with_dwim
= 0;
1201 * Accept "git checkout foo", "git checkout foo --"
1202 * and "git switch foo" as candidates for dwim.
1204 if (!(argc
== 1 && !has_dash_dash
) &&
1205 !(argc
== 2 && has_dash_dash
) &&
1206 opts
->accept_pathspec
)
1207 recover_with_dwim
= 0;
1209 if (recover_with_dwim
) {
1210 const char *remote
= unique_tracking_name(arg
, rev
,
1211 dwim_remotes_matched
);
1213 if (could_be_checkout_paths
)
1214 die(_("'%s' could be both a local file and a tracking branch.\n"
1215 "Please use -- (and optionally --no-guess) to disambiguate"),
1219 /* DWIMmed to create local branch, case (3).(b) */
1221 recover_with_dwim
= 0;
1225 if (!recover_with_dwim
) {
1227 die(_("invalid reference: %s"), arg
);
1232 /* we can't end up being in (2) anymore, eat the argument */
1237 setup_new_branch_info_and_source_tree(new_branch_info
, opts
, rev
, arg
);
1239 if (!opts
->source_tree
) /* case (1): want a tree */
1240 die(_("reference is not a tree: %s"), arg
);
1242 if (!has_dash_dash
) { /* case (3).(d) -> (1) */
1244 * Do not complain the most common case
1245 * git checkout branch
1246 * even if there happen to be a file called 'branch';
1247 * it would be extremely annoying.
1250 verify_non_filename(opts
->prefix
, arg
);
1251 } else if (opts
->accept_pathspec
) {
1260 static int switch_unborn_to_new_branch(const struct checkout_opts
*opts
)
1263 struct strbuf branch_ref
= STRBUF_INIT
;
1265 trace2_cmd_mode("unborn");
1267 if (!opts
->new_branch
)
1268 die(_("You are on a branch yet to be born"));
1269 strbuf_addf(&branch_ref
, "refs/heads/%s", opts
->new_branch
);
1270 status
= create_symref("HEAD", branch_ref
.buf
, "checkout -b");
1271 strbuf_release(&branch_ref
);
1273 fprintf(stderr
, _("Switched to a new branch '%s'\n"),
1278 static void die_expecting_a_branch(const struct branch_info
*branch_info
)
1280 struct object_id oid
;
1283 if (dwim_ref(branch_info
->name
, strlen(branch_info
->name
), &oid
, &to_free
) == 1) {
1284 const char *ref
= to_free
;
1286 if (skip_prefix(ref
, "refs/tags/", &ref
))
1287 die(_("a branch is expected, got tag '%s'"), ref
);
1288 if (skip_prefix(ref
, "refs/remotes/", &ref
))
1289 die(_("a branch is expected, got remote branch '%s'"), ref
);
1290 die(_("a branch is expected, got '%s'"), ref
);
1292 if (branch_info
->commit
)
1293 die(_("a branch is expected, got commit '%s'"), branch_info
->name
);
1295 * This case should never happen because we already die() on
1296 * non-commit, but just in case.
1298 die(_("a branch is expected, got '%s'"), branch_info
->name
);
1301 static void die_if_some_operation_in_progress(void)
1303 struct wt_status_state state
;
1305 memset(&state
, 0, sizeof(state
));
1306 wt_status_get_state(the_repository
, &state
, 0);
1308 if (state
.merge_in_progress
)
1309 die(_("cannot switch branch while merging\n"
1310 "Consider \"git merge --quit\" "
1311 "or \"git worktree add\"."));
1312 if (state
.am_in_progress
)
1313 die(_("cannot switch branch in the middle of an am session\n"
1314 "Consider \"git am --quit\" "
1315 "or \"git worktree add\"."));
1316 if (state
.rebase_interactive_in_progress
|| state
.rebase_in_progress
)
1317 die(_("cannot switch branch while rebasing\n"
1318 "Consider \"git rebase --quit\" "
1319 "or \"git worktree add\"."));
1320 if (state
.cherry_pick_in_progress
)
1321 die(_("cannot switch branch while cherry-picking\n"
1322 "Consider \"git cherry-pick --quit\" "
1323 "or \"git worktree add\"."));
1324 if (state
.revert_in_progress
)
1325 die(_("cannot switch branch while reverting\n"
1326 "Consider \"git revert --quit\" "
1327 "or \"git worktree add\"."));
1328 if (state
.bisect_in_progress
)
1329 warning(_("you are switching branch while bisecting"));
1332 static int checkout_branch(struct checkout_opts
*opts
,
1333 struct branch_info
*new_branch_info
)
1335 if (opts
->pathspec
.nr
)
1336 die(_("paths cannot be used with switching branches"));
1338 if (opts
->patch_mode
)
1339 die(_("'%s' cannot be used with switching branches"),
1342 if (opts
->overlay_mode
!= -1)
1343 die(_("'%s' cannot be used with switching branches"),
1346 if (opts
->writeout_stage
)
1347 die(_("'%s' cannot be used with switching branches"),
1350 if (opts
->force
&& opts
->merge
)
1351 die(_("'%s' cannot be used with '%s'"), "-f", "-m");
1353 if (opts
->discard_changes
&& opts
->merge
)
1354 die(_("'%s' cannot be used with '%s'"), "--discard-changes", "--merge");
1356 if (opts
->force_detach
&& opts
->new_branch
)
1357 die(_("'%s' cannot be used with '%s'"),
1358 "--detach", "-b/-B/--orphan");
1360 if (opts
->new_orphan_branch
) {
1361 if (opts
->track
!= BRANCH_TRACK_UNSPECIFIED
)
1362 die(_("'%s' cannot be used with '%s'"), "--orphan", "-t");
1363 if (opts
->orphan_from_empty_tree
&& new_branch_info
->name
)
1364 die(_("'%s' cannot take <start-point>"), "--orphan");
1365 } else if (opts
->force_detach
) {
1366 if (opts
->track
!= BRANCH_TRACK_UNSPECIFIED
)
1367 die(_("'%s' cannot be used with '%s'"), "--detach", "-t");
1368 } else if (opts
->track
== BRANCH_TRACK_UNSPECIFIED
)
1369 opts
->track
= git_branch_track
;
1371 if (new_branch_info
->name
&& !new_branch_info
->commit
)
1372 die(_("Cannot switch branch to a non-commit '%s'"),
1373 new_branch_info
->name
);
1375 if (!opts
->switch_branch_doing_nothing_is_ok
&&
1376 !new_branch_info
->name
&&
1377 !opts
->new_branch
&&
1378 !opts
->force_detach
)
1379 die(_("missing branch or commit argument"));
1381 if (!opts
->implicit_detach
&&
1382 !opts
->force_detach
&&
1383 !opts
->new_branch
&&
1384 !opts
->new_branch_force
&&
1385 new_branch_info
->name
&&
1386 !new_branch_info
->path
)
1387 die_expecting_a_branch(new_branch_info
);
1389 if (!opts
->can_switch_when_in_progress
)
1390 die_if_some_operation_in_progress();
1392 if (new_branch_info
->path
&& !opts
->force_detach
&& !opts
->new_branch
&&
1393 !opts
->ignore_other_worktrees
) {
1395 char *head_ref
= resolve_refdup("HEAD", 0, NULL
, &flag
);
1397 (!(flag
& REF_ISSYMREF
) || strcmp(head_ref
, new_branch_info
->path
)))
1398 die_if_checked_out(new_branch_info
->path
, 1);
1402 if (!new_branch_info
->commit
&& opts
->new_branch
) {
1403 struct object_id rev
;
1406 if (!read_ref_full("HEAD", 0, &rev
, &flag
) &&
1407 (flag
& REF_ISSYMREF
) && is_null_oid(&rev
))
1408 return switch_unborn_to_new_branch(opts
);
1410 return switch_branches(opts
, new_branch_info
);
1413 static struct option
*add_common_options(struct checkout_opts
*opts
,
1414 struct option
*prevopts
)
1416 struct option options
[] = {
1417 OPT__QUIET(&opts
->quiet
, N_("suppress progress reporting")),
1418 { OPTION_CALLBACK
, 0, "recurse-submodules", NULL
,
1419 "checkout", "control recursive updating of submodules",
1420 PARSE_OPT_OPTARG
, option_parse_recurse_submodules_worktree_updater
},
1421 OPT_BOOL(0, "progress", &opts
->show_progress
, N_("force progress reporting")),
1422 OPT_BOOL('m', "merge", &opts
->merge
, N_("perform a 3-way merge with the new branch")),
1423 OPT_STRING(0, "conflict", &opts
->conflict_style
, N_("style"),
1424 N_("conflict style (merge or diff3)")),
1427 struct option
*newopts
= parse_options_concat(prevopts
, options
);
1432 static struct option
*add_common_switch_branch_options(
1433 struct checkout_opts
*opts
, struct option
*prevopts
)
1435 struct option options
[] = {
1436 OPT_BOOL('d', "detach", &opts
->force_detach
, N_("detach HEAD at named commit")),
1437 OPT_SET_INT('t', "track", &opts
->track
, N_("set upstream info for new branch"),
1438 BRANCH_TRACK_EXPLICIT
),
1439 OPT__FORCE(&opts
->force
, N_("force checkout (throw away local modifications)"),
1440 PARSE_OPT_NOCOMPLETE
),
1441 OPT_STRING(0, "orphan", &opts
->new_orphan_branch
, N_("new-branch"), N_("new unparented branch")),
1442 OPT_BOOL_F(0, "overwrite-ignore", &opts
->overwrite_ignore
,
1443 N_("update ignored files (default)"),
1444 PARSE_OPT_NOCOMPLETE
),
1445 OPT_BOOL(0, "ignore-other-worktrees", &opts
->ignore_other_worktrees
,
1446 N_("do not check if another worktree is holding the given ref")),
1449 struct option
*newopts
= parse_options_concat(prevopts
, options
);
1454 static struct option
*add_checkout_path_options(struct checkout_opts
*opts
,
1455 struct option
*prevopts
)
1457 struct option options
[] = {
1458 OPT_SET_INT_F('2', "ours", &opts
->writeout_stage
,
1459 N_("checkout our version for unmerged files"),
1460 2, PARSE_OPT_NONEG
),
1461 OPT_SET_INT_F('3', "theirs", &opts
->writeout_stage
,
1462 N_("checkout their version for unmerged files"),
1463 3, PARSE_OPT_NONEG
),
1464 OPT_BOOL('p', "patch", &opts
->patch_mode
, N_("select hunks interactively")),
1465 OPT_BOOL(0, "ignore-skip-worktree-bits", &opts
->ignore_skipworktree
,
1466 N_("do not limit pathspecs to sparse entries only")),
1469 struct option
*newopts
= parse_options_concat(prevopts
, options
);
1474 static int checkout_main(int argc
, const char **argv
, const char *prefix
,
1475 struct checkout_opts
*opts
, struct option
*options
,
1476 const char * const usagestr
[])
1478 struct branch_info new_branch_info
;
1479 int dwim_remotes_matched
= 0;
1480 int parseopt_flags
= 0;
1482 memset(&new_branch_info
, 0, sizeof(new_branch_info
));
1483 opts
->overwrite_ignore
= 1;
1484 opts
->prefix
= prefix
;
1485 opts
->show_progress
= -1;
1487 git_config(git_checkout_config
, opts
);
1489 opts
->track
= BRANCH_TRACK_UNSPECIFIED
;
1491 if (!opts
->accept_pathspec
&& !opts
->accept_ref
)
1492 BUG("make up your mind, you need to take _something_");
1493 if (opts
->accept_pathspec
&& opts
->accept_ref
)
1494 parseopt_flags
= PARSE_OPT_KEEP_DASHDASH
;
1496 argc
= parse_options(argc
, argv
, prefix
, options
,
1497 usagestr
, parseopt_flags
);
1499 if (opts
->show_progress
< 0) {
1501 opts
->show_progress
= 0;
1503 opts
->show_progress
= isatty(2);
1506 if (opts
->conflict_style
) {
1507 opts
->merge
= 1; /* implied */
1508 git_xmerge_config("merge.conflictstyle", opts
->conflict_style
, NULL
);
1511 opts
->discard_changes
= 1;
1512 opts
->ignore_unmerged_opt
= "--force";
1513 opts
->ignore_unmerged
= 1;
1516 if ((!!opts
->new_branch
+ !!opts
->new_branch_force
+ !!opts
->new_orphan_branch
) > 1)
1517 die(_("-b, -B and --orphan are mutually exclusive"));
1519 if (opts
->overlay_mode
== 1 && opts
->patch_mode
)
1520 die(_("-p and --overlay are mutually exclusive"));
1522 if (opts
->checkout_index
>= 0 || opts
->checkout_worktree
>= 0) {
1523 if (opts
->checkout_index
< 0)
1524 opts
->checkout_index
= 0;
1525 if (opts
->checkout_worktree
< 0)
1526 opts
->checkout_worktree
= 0;
1528 if (opts
->checkout_index
< 0)
1529 opts
->checkout_index
= -opts
->checkout_index
- 1;
1530 if (opts
->checkout_worktree
< 0)
1531 opts
->checkout_worktree
= -opts
->checkout_worktree
- 1;
1533 if (opts
->checkout_index
< 0 || opts
->checkout_worktree
< 0)
1534 BUG("these flags should be non-negative by now");
1536 * convenient shortcut: "git restore --staged" equals
1537 * "git restore --staged --source HEAD"
1539 if (!opts
->from_treeish
&& opts
->checkout_index
&& !opts
->checkout_worktree
)
1540 opts
->from_treeish
= "HEAD";
1543 * From here on, new_branch will contain the branch to be checked out,
1544 * and new_branch_force and new_orphan_branch will tell us which one of
1545 * -b/-B/--orphan is being used.
1547 if (opts
->new_branch_force
)
1548 opts
->new_branch
= opts
->new_branch_force
;
1550 if (opts
->new_orphan_branch
)
1551 opts
->new_branch
= opts
->new_orphan_branch
;
1553 /* --track without -b/-B/--orphan should DWIM */
1554 if (opts
->track
!= BRANCH_TRACK_UNSPECIFIED
&& !opts
->new_branch
) {
1555 const char *argv0
= argv
[0];
1556 if (!argc
|| !strcmp(argv0
, "--"))
1557 die(_("--track needs a branch name"));
1558 skip_prefix(argv0
, "refs/", &argv0
);
1559 skip_prefix(argv0
, "remotes/", &argv0
);
1560 argv0
= strchr(argv0
, '/');
1561 if (!argv0
|| !argv0
[1])
1562 die(_("missing branch name; try -b"));
1563 opts
->new_branch
= argv0
+ 1;
1567 * Extract branch name from command line arguments, so
1568 * all that is left is pathspecs.
1572 * 1) git checkout <tree> -- [<paths>]
1573 * 2) git checkout -- [<paths>]
1574 * 3) git checkout <something> [<paths>]
1576 * including "last branch" syntax and DWIM-ery for names of
1577 * remote branches, erroring out for invalid or ambiguous cases.
1579 if (argc
&& opts
->accept_ref
) {
1580 struct object_id rev
;
1582 !opts
->patch_mode
&&
1583 opts
->dwim_new_local_branch
&&
1584 opts
->track
== BRANCH_TRACK_UNSPECIFIED
&&
1586 int n
= parse_branchname_arg(argc
, argv
, dwim_ok
,
1587 &new_branch_info
, opts
, &rev
,
1588 &dwim_remotes_matched
);
1591 } else if (!opts
->accept_ref
&& opts
->from_treeish
) {
1592 struct object_id rev
;
1594 if (get_oid_mb(opts
->from_treeish
, &rev
))
1595 die(_("could not resolve %s"), opts
->from_treeish
);
1597 setup_new_branch_info_and_source_tree(&new_branch_info
,
1599 opts
->from_treeish
);
1601 if (!opts
->source_tree
)
1602 die(_("reference is not a tree: %s"), opts
->from_treeish
);
1605 if (opts
->accept_pathspec
&& !opts
->empty_pathspec_ok
&& !argc
&&
1606 !opts
->patch_mode
) /* patch mode is special */
1607 die(_("you must specify path(s) to restore"));
1610 parse_pathspec(&opts
->pathspec
, 0,
1611 opts
->patch_mode
? PATHSPEC_PREFIX_ORIGIN
: 0,
1614 if (!opts
->pathspec
.nr
)
1615 die(_("invalid path specification"));
1618 * Try to give more helpful suggestion.
1619 * new_branch && argc > 1 will be caught later.
1621 if (opts
->new_branch
&& argc
== 1)
1622 die(_("'%s' is not a commit and a branch '%s' cannot be created from it"),
1623 argv
[0], opts
->new_branch
);
1625 if (opts
->force_detach
)
1626 die(_("git checkout: --detach does not take a path argument '%s'"),
1629 if (1 < !!opts
->writeout_stage
+ !!opts
->force
+ !!opts
->merge
)
1630 die(_("git checkout: --ours/--theirs, --force and --merge are incompatible when\n"
1631 "checking out of the index."));
1634 if (opts
->new_branch
) {
1635 struct strbuf buf
= STRBUF_INIT
;
1637 if (opts
->new_branch_force
)
1638 opts
->branch_exists
= validate_branchname(opts
->new_branch
, &buf
);
1640 opts
->branch_exists
=
1641 validate_new_branchname(opts
->new_branch
, &buf
, 0);
1642 strbuf_release(&buf
);
1646 if (opts
->patch_mode
|| opts
->pathspec
.nr
) {
1647 int ret
= checkout_paths(opts
, new_branch_info
.name
);
1648 if (ret
&& dwim_remotes_matched
> 1 &&
1649 advice_checkout_ambiguous_remote_branch_name
)
1650 advise(_("'%s' matched more than one remote tracking branch.\n"
1651 "We found %d remotes with a reference that matched. So we fell back\n"
1652 "on trying to resolve the argument as a path, but failed there too!\n"
1654 "If you meant to check out a remote tracking branch on, e.g. 'origin',\n"
1655 "you can do so by fully qualifying the name with the --track option:\n"
1657 " git checkout --track origin/<name>\n"
1659 "If you'd like to always have checkouts of an ambiguous <name> prefer\n"
1660 "one remote, e.g. the 'origin' remote, consider setting\n"
1661 "checkout.defaultRemote=origin in your config."),
1663 dwim_remotes_matched
);
1666 return checkout_branch(opts
, &new_branch_info
);
1670 int cmd_checkout(int argc
, const char **argv
, const char *prefix
)
1672 struct checkout_opts opts
;
1673 struct option
*options
;
1674 struct option checkout_options
[] = {
1675 OPT_STRING('b', NULL
, &opts
.new_branch
, N_("branch"),
1676 N_("create and checkout a new branch")),
1677 OPT_STRING('B', NULL
, &opts
.new_branch_force
, N_("branch"),
1678 N_("create/reset and checkout a branch")),
1679 OPT_BOOL('l', NULL
, &opts
.new_branch_log
, N_("create reflog for new branch")),
1680 OPT_BOOL(0, "guess", &opts
.dwim_new_local_branch
,
1681 N_("second guess 'git checkout <no-such-branch>' (default)")),
1682 OPT_BOOL(0, "overlay", &opts
.overlay_mode
, N_("use overlay mode (default)")),
1687 memset(&opts
, 0, sizeof(opts
));
1688 opts
.dwim_new_local_branch
= 1;
1689 opts
.switch_branch_doing_nothing_is_ok
= 1;
1690 opts
.only_merge_on_switching_branches
= 0;
1691 opts
.accept_ref
= 1;
1692 opts
.accept_pathspec
= 1;
1693 opts
.implicit_detach
= 1;
1694 opts
.can_switch_when_in_progress
= 1;
1695 opts
.orphan_from_empty_tree
= 0;
1696 opts
.empty_pathspec_ok
= 1;
1697 opts
.overlay_mode
= -1;
1698 opts
.checkout_index
= -2; /* default on */
1699 opts
.checkout_worktree
= -2; /* default on */
1701 if (argc
== 3 && !strcmp(argv
[1], "-b")) {
1703 * User ran 'git checkout -b <branch>' and expects
1704 * the same behavior as 'git switch -c <branch>'.
1706 opts
.switch_branch_doing_nothing_is_ok
= 0;
1707 opts
.only_merge_on_switching_branches
= 1;
1710 options
= parse_options_dup(checkout_options
);
1711 options
= add_common_options(&opts
, options
);
1712 options
= add_common_switch_branch_options(&opts
, options
);
1713 options
= add_checkout_path_options(&opts
, options
);
1715 ret
= checkout_main(argc
, argv
, prefix
, &opts
,
1716 options
, checkout_usage
);
1717 FREE_AND_NULL(options
);
1721 int cmd_switch(int argc
, const char **argv
, const char *prefix
)
1723 struct checkout_opts opts
;
1724 struct option
*options
= NULL
;
1725 struct option switch_options
[] = {
1726 OPT_STRING('c', "create", &opts
.new_branch
, N_("branch"),
1727 N_("create and switch to a new branch")),
1728 OPT_STRING('C', "force-create", &opts
.new_branch_force
, N_("branch"),
1729 N_("create/reset and switch to a branch")),
1730 OPT_BOOL(0, "guess", &opts
.dwim_new_local_branch
,
1731 N_("second guess 'git switch <no-such-branch>'")),
1732 OPT_BOOL(0, "discard-changes", &opts
.discard_changes
,
1733 N_("throw away local modifications")),
1738 memset(&opts
, 0, sizeof(opts
));
1739 opts
.dwim_new_local_branch
= 1;
1740 opts
.accept_ref
= 1;
1741 opts
.accept_pathspec
= 0;
1742 opts
.switch_branch_doing_nothing_is_ok
= 0;
1743 opts
.only_merge_on_switching_branches
= 1;
1744 opts
.implicit_detach
= 0;
1745 opts
.can_switch_when_in_progress
= 0;
1746 opts
.orphan_from_empty_tree
= 1;
1747 opts
.overlay_mode
= -1;
1749 options
= parse_options_dup(switch_options
);
1750 options
= add_common_options(&opts
, options
);
1751 options
= add_common_switch_branch_options(&opts
, options
);
1753 ret
= checkout_main(argc
, argv
, prefix
, &opts
,
1754 options
, switch_branch_usage
);
1755 FREE_AND_NULL(options
);
1759 int cmd_restore(int argc
, const char **argv
, const char *prefix
)
1761 struct checkout_opts opts
;
1762 struct option
*options
;
1763 struct option restore_options
[] = {
1764 OPT_STRING('s', "source", &opts
.from_treeish
, "<tree-ish>",
1765 N_("where the checkout from")),
1766 OPT_BOOL('S', "staged", &opts
.checkout_index
,
1767 N_("restore the index")),
1768 OPT_BOOL('W', "worktree", &opts
.checkout_worktree
,
1769 N_("restore the working tree (default)")),
1770 OPT_BOOL(0, "ignore-unmerged", &opts
.ignore_unmerged
,
1771 N_("ignore unmerged entries")),
1772 OPT_BOOL(0, "overlay", &opts
.overlay_mode
, N_("use overlay mode")),
1777 memset(&opts
, 0, sizeof(opts
));
1778 opts
.accept_ref
= 0;
1779 opts
.accept_pathspec
= 1;
1780 opts
.empty_pathspec_ok
= 0;
1781 opts
.overlay_mode
= 0;
1782 opts
.checkout_index
= -1; /* default off */
1783 opts
.checkout_worktree
= -2; /* default on */
1784 opts
.ignore_unmerged_opt
= "--ignore-unmerged";
1786 options
= parse_options_dup(restore_options
);
1787 options
= add_common_options(&opts
, options
);
1788 options
= add_checkout_path_options(&opts
, options
);
1790 ret
= checkout_main(argc
, argv
, prefix
, &opts
,
1791 options
, restore_usage
);
1792 FREE_AND_NULL(options
);