1 #define USE_THE_INDEX_VARIABLE
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
= index_name_pos(&the_index
, ce
->name
, ce
->ce_namelen
);
153 struct cache_entry
*old
= the_index
.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_index_entry(&the_index
, ce
,
164 ADD_CACHE_OK_TO_ADD
| ADD_CACHE_OK_TO_REPLACE
);
168 static int read_tree_some(struct tree
*tree
, const struct pathspec
*pathspec
)
170 read_tree(the_repository
, tree
,
171 pathspec
, update_some
, NULL
);
173 /* update the index with the given tree's info
174 * for all args, expanding wildcards, and exit
175 * with any non-zero return code.
180 static int skip_same_name(const struct cache_entry
*ce
, int pos
)
182 while (++pos
< the_index
.cache_nr
&&
183 !strcmp(the_index
.cache
[pos
]->name
, ce
->name
))
188 static int check_stage(int stage
, const struct cache_entry
*ce
, int pos
,
191 while (pos
< the_index
.cache_nr
&&
192 !strcmp(the_index
.cache
[pos
]->name
, ce
->name
)) {
193 if (ce_stage(the_index
.cache
[pos
]) == stage
)
200 return error(_("path '%s' does not have our version"), ce
->name
);
202 return error(_("path '%s' does not have their version"), ce
->name
);
205 static int check_stages(unsigned stages
, const struct cache_entry
*ce
, int pos
)
208 const char *name
= ce
->name
;
210 while (pos
< the_index
.cache_nr
) {
211 ce
= the_index
.cache
[pos
];
212 if (strcmp(name
, ce
->name
))
214 seen
|= (1 << ce_stage(ce
));
217 if ((stages
& seen
) != stages
)
218 return error(_("path '%s' does not have all necessary versions"),
223 static int checkout_stage(int stage
, const struct cache_entry
*ce
, int pos
,
224 const struct checkout
*state
, int *nr_checkouts
,
227 while (pos
< the_index
.cache_nr
&&
228 !strcmp(the_index
.cache
[pos
]->name
, ce
->name
)) {
229 if (ce_stage(the_index
.cache
[pos
]) == stage
)
230 return checkout_entry(the_index
.cache
[pos
], state
,
239 return error(_("path '%s' does not have our version"), ce
->name
);
241 return error(_("path '%s' does not have their version"), ce
->name
);
244 static int checkout_merged(int pos
, const struct checkout
*state
,
245 int *nr_checkouts
, struct mem_pool
*ce_mem_pool
)
247 struct cache_entry
*ce
= the_index
.cache
[pos
];
248 const char *path
= ce
->name
;
249 mmfile_t ancestor
, ours
, theirs
;
250 enum ll_merge_result merge_status
;
252 struct object_id oid
;
253 mmbuffer_t result_buf
;
254 struct object_id threeway
[3];
256 struct ll_merge_options ll_opts
;
259 memset(threeway
, 0, sizeof(threeway
));
260 while (pos
< the_index
.cache_nr
) {
262 stage
= ce_stage(ce
);
263 if (!stage
|| strcmp(path
, ce
->name
))
265 oidcpy(&threeway
[stage
- 1], &ce
->oid
);
267 mode
= create_ce_mode(ce
->ce_mode
);
269 ce
= the_index
.cache
[pos
];
271 if (is_null_oid(&threeway
[1]) || is_null_oid(&threeway
[2]))
272 return error(_("path '%s' does not have necessary versions"), path
);
274 read_mmblob(&ancestor
, &threeway
[0]);
275 read_mmblob(&ours
, &threeway
[1]);
276 read_mmblob(&theirs
, &threeway
[2]);
278 memset(&ll_opts
, 0, sizeof(ll_opts
));
279 git_config_get_bool("merge.renormalize", &renormalize
);
280 ll_opts
.renormalize
= renormalize
;
281 merge_status
= ll_merge(&result_buf
, path
, &ancestor
, "base",
282 &ours
, "ours", &theirs
, "theirs",
283 state
->istate
, &ll_opts
);
287 if (merge_status
== LL_MERGE_BINARY_CONFLICT
)
288 warning("Cannot merge binary files: %s (%s vs. %s)",
289 path
, "ours", "theirs");
290 if (merge_status
< 0 || !result_buf
.ptr
) {
291 free(result_buf
.ptr
);
292 return error(_("path '%s': cannot merge"), path
);
297 * There is absolutely no reason to write this as a blob object
298 * and create a phony cache entry. This hack is primarily to get
299 * to the write_entry() machinery that massages the contents to
300 * work-tree format and writes out which only allows it for a
301 * cache entry. The code in write_entry() needs to be refactored
302 * to allow us to feed a <buffer, size, mode> instead of a cache
303 * entry. Such a refactoring would help merge_recursive as well
304 * (it also writes the merge result to the object database even
305 * when it may contain conflicts).
307 if (write_object_file(result_buf
.ptr
, result_buf
.size
, OBJ_BLOB
, &oid
))
308 die(_("Unable to add merge result for '%s'"), path
);
309 free(result_buf
.ptr
);
310 ce
= make_transient_cache_entry(mode
, &oid
, path
, 2, ce_mem_pool
);
312 die(_("make_cache_entry failed for path '%s'"), path
);
313 status
= checkout_entry(ce
, state
, NULL
, nr_checkouts
);
317 static void mark_ce_for_checkout_overlay(struct cache_entry
*ce
,
319 const struct checkout_opts
*opts
)
321 ce
->ce_flags
&= ~CE_MATCHED
;
322 if (!opts
->ignore_skipworktree
&& ce_skip_worktree(ce
))
324 if (opts
->source_tree
&& !(ce
->ce_flags
& CE_UPDATE
))
326 * "git checkout tree-ish -- path", but this entry
327 * is in the original index but is not in tree-ish
328 * or does not match the pathspec; it will not be
329 * checked out to the working tree. We will not do
330 * anything to this entry at all.
334 * Either this entry came from the tree-ish we are
335 * checking the paths out of, or we are checking out
338 * If it comes from the tree-ish, we already know it
339 * matches the pathspec and could just stamp
340 * CE_MATCHED to it from update_some(). But we still
341 * need ps_matched and read_tree (and
342 * eventually tree_entry_interesting) cannot fill
343 * ps_matched yet. Once it can, we can avoid calling
344 * match_pathspec() for _all_ entries when
345 * opts->source_tree != NULL.
347 if (ce_path_match(&the_index
, ce
, &opts
->pathspec
, ps_matched
))
348 ce
->ce_flags
|= CE_MATCHED
;
351 static void mark_ce_for_checkout_no_overlay(struct cache_entry
*ce
,
353 const struct checkout_opts
*opts
)
355 ce
->ce_flags
&= ~CE_MATCHED
;
356 if (!opts
->ignore_skipworktree
&& ce_skip_worktree(ce
))
358 if (ce_path_match(&the_index
, ce
, &opts
->pathspec
, ps_matched
)) {
359 ce
->ce_flags
|= CE_MATCHED
;
360 if (opts
->source_tree
&& !(ce
->ce_flags
& CE_UPDATE
))
362 * In overlay mode, but the path is not in
363 * tree-ish, which means we should remove it
364 * from the index and the working tree.
366 ce
->ce_flags
|= CE_REMOVE
| CE_WT_REMOVE
;
370 static int checkout_worktree(const struct checkout_opts
*opts
,
371 const struct branch_info
*info
)
373 struct checkout state
= CHECKOUT_INIT
;
374 int nr_checkouts
= 0, nr_unmerged
= 0;
377 int pc_workers
, pc_threshold
;
378 struct mem_pool ce_mem_pool
;
381 state
.refresh_cache
= 1;
382 state
.istate
= &the_index
;
384 mem_pool_init(&ce_mem_pool
, 0);
385 get_parallel_checkout_configs(&pc_workers
, &pc_threshold
);
386 init_checkout_metadata(&state
.meta
, info
->refname
,
387 info
->commit
? &info
->commit
->object
.oid
: &info
->oid
,
390 enable_delayed_checkout(&state
);
393 init_parallel_checkout();
395 for (pos
= 0; pos
< the_index
.cache_nr
; pos
++) {
396 struct cache_entry
*ce
= the_index
.cache
[pos
];
397 if (ce
->ce_flags
& CE_MATCHED
) {
399 errs
|= checkout_entry(ce
, &state
,
400 NULL
, &nr_checkouts
);
403 if (opts
->writeout_stage
)
404 errs
|= checkout_stage(opts
->writeout_stage
,
407 &nr_checkouts
, opts
->overlay_mode
);
408 else if (opts
->merge
)
409 errs
|= checkout_merged(pos
, &state
,
412 pos
= skip_same_name(ce
, pos
) - 1;
416 errs
|= run_parallel_checkout(&state
, pc_workers
, pc_threshold
,
418 mem_pool_discard(&ce_mem_pool
, should_validate_cache_entries());
419 remove_marked_cache_entries(&the_index
, 1);
420 remove_scheduled_dirs();
421 errs
|= finish_delayed_checkout(&state
, opts
->show_progress
);
423 if (opts
->count_checkout_paths
) {
425 fprintf_ln(stderr
, Q_("Recreated %d merge conflict",
426 "Recreated %d merge conflicts",
429 if (opts
->source_tree
)
430 fprintf_ln(stderr
, Q_("Updated %d path from %s",
431 "Updated %d paths from %s",
434 find_unique_abbrev(&opts
->source_tree
->object
.oid
,
436 else if (!nr_unmerged
|| nr_checkouts
)
437 fprintf_ln(stderr
, Q_("Updated %d path from the index",
438 "Updated %d paths from the index",
446 static int checkout_paths(const struct checkout_opts
*opts
,
447 const struct branch_info
*new_branch_info
)
450 static char *ps_matched
;
451 struct object_id rev
;
454 struct lock_file lock_file
= LOCK_INIT
;
457 trace2_cmd_mode(opts
->patch_mode
? "patch" : "path");
459 if (opts
->track
!= BRANCH_TRACK_UNSPECIFIED
)
460 die(_("'%s' cannot be used with updating paths"), "--track");
462 if (opts
->new_branch_log
)
463 die(_("'%s' cannot be used with updating paths"), "-l");
465 if (opts
->ignore_unmerged
&& opts
->patch_mode
)
466 die(_("'%s' cannot be used with updating paths"),
467 opts
->ignore_unmerged_opt
);
469 if (opts
->force_detach
)
470 die(_("'%s' cannot be used with updating paths"), "--detach");
472 if (opts
->merge
&& opts
->patch_mode
)
473 die(_("options '%s' and '%s' cannot be used together"), "--merge", "--patch");
475 if (opts
->ignore_unmerged
&& opts
->merge
)
476 die(_("options '%s' and '%s' cannot be used together"),
477 opts
->ignore_unmerged_opt
, "-m");
479 if (opts
->new_branch
)
480 die(_("Cannot update paths and switch to branch '%s' at the same time."),
483 if (!opts
->checkout_worktree
&& !opts
->checkout_index
)
484 die(_("neither '%s' or '%s' is specified"),
485 "--staged", "--worktree");
487 if (!opts
->checkout_worktree
&& !opts
->from_treeish
)
488 die(_("'%s' must be used when '%s' is not specified"),
489 "--worktree", "--source");
491 if (opts
->checkout_index
&& !opts
->checkout_worktree
&&
492 opts
->writeout_stage
)
493 die(_("'%s' or '%s' cannot be used with %s"),
494 "--ours", "--theirs", "--staged");
496 if (opts
->checkout_index
&& !opts
->checkout_worktree
&&
498 die(_("'%s' or '%s' cannot be used with %s"),
499 "--merge", "--conflict", "--staged");
501 if (opts
->patch_mode
) {
502 const char *patch_mode
;
503 const char *rev
= new_branch_info
->name
;
504 char rev_oid
[GIT_MAX_HEXSZ
+ 1];
507 * Since rev can be in the form of `<a>...<b>` (which is not
508 * recognized by diff-index), we will always replace the name
509 * with the hex of the commit (whether it's in `...` form or
510 * not) for the run_add_interactive() machinery to work
511 * properly. However, there is special logic for the HEAD case
512 * so we mustn't replace that. Also, when we were given a
513 * tree-object, new_branch_info->commit would be NULL, but we
514 * do not have to do any replacement, either.
516 if (rev
&& new_branch_info
->commit
&& strcmp(rev
, "HEAD"))
517 rev
= oid_to_hex_r(rev_oid
, &new_branch_info
->commit
->object
.oid
);
519 if (opts
->checkout_index
&& opts
->checkout_worktree
)
520 patch_mode
= "--patch=checkout";
521 else if (opts
->checkout_index
&& !opts
->checkout_worktree
)
522 patch_mode
= "--patch=reset";
523 else if (!opts
->checkout_index
&& opts
->checkout_worktree
)
524 patch_mode
= "--patch=worktree";
526 BUG("either flag must have been set, worktree=%d, index=%d",
527 opts
->checkout_worktree
, opts
->checkout_index
);
528 return run_add_interactive(rev
, patch_mode
, &opts
->pathspec
);
531 repo_hold_locked_index(the_repository
, &lock_file
, LOCK_DIE_ON_ERROR
);
532 if (repo_read_index_preload(the_repository
, &opts
->pathspec
, 0) < 0)
533 return error(_("index file corrupt"));
535 if (opts
->source_tree
)
536 read_tree_some(opts
->source_tree
, &opts
->pathspec
);
538 ps_matched
= xcalloc(opts
->pathspec
.nr
, 1);
541 * Make sure all pathspecs participated in locating the paths
544 for (pos
= 0; pos
< the_index
.cache_nr
; pos
++)
545 if (opts
->overlay_mode
)
546 mark_ce_for_checkout_overlay(the_index
.cache
[pos
],
550 mark_ce_for_checkout_no_overlay(the_index
.cache
[pos
],
554 if (report_path_error(ps_matched
, &opts
->pathspec
)) {
560 /* "checkout -m path" to recreate conflicted state */
562 unmerge_marked_index(&the_index
);
564 /* Any unmerged paths? */
565 for (pos
= 0; pos
< the_index
.cache_nr
; pos
++) {
566 const struct cache_entry
*ce
= the_index
.cache
[pos
];
567 if (ce
->ce_flags
& CE_MATCHED
) {
570 if (opts
->ignore_unmerged
) {
572 warning(_("path '%s' is unmerged"), ce
->name
);
573 } else if (opts
->writeout_stage
) {
574 errs
|= check_stage(opts
->writeout_stage
, ce
, pos
, opts
->overlay_mode
);
575 } else if (opts
->merge
) {
576 errs
|= check_stages((1<<2) | (1<<3), ce
, pos
);
579 error(_("path '%s' is unmerged"), ce
->name
);
581 pos
= skip_same_name(ce
, pos
) - 1;
587 /* Now we are committed to check them out */
588 if (opts
->checkout_worktree
)
589 errs
|= checkout_worktree(opts
, new_branch_info
);
591 remove_marked_cache_entries(&the_index
, 1);
594 * Allow updating the index when checking out from the index.
595 * This is to save new stat info.
597 if (opts
->checkout_worktree
&& !opts
->checkout_index
&& !opts
->source_tree
)
600 checkout_index
= opts
->checkout_index
;
602 if (checkout_index
) {
603 if (write_locked_index(&the_index
, &lock_file
, COMMIT_LOCK
))
604 die(_("unable to write new index file"));
607 * NEEDSWORK: if --worktree is not specified, we
608 * should save stat info of checked out files in the
609 * index to avoid the next (potentially costly)
610 * refresh. But it's a bit tricker to do...
612 rollback_lock_file(&lock_file
);
615 read_ref_full("HEAD", 0, &rev
, NULL
);
616 head
= lookup_commit_reference_gently(the_repository
, &rev
, 1);
618 errs
|= post_checkout_hook(head
, head
, 0);
622 static void show_local_changes(struct object
*head
,
623 const struct diff_options
*opts
)
626 /* I think we want full paths, even if we're in a subdirectory. */
627 repo_init_revisions(the_repository
, &rev
, NULL
);
628 rev
.diffopt
.flags
= opts
->flags
;
629 rev
.diffopt
.output_format
|= DIFF_FORMAT_NAME_STATUS
;
630 rev
.diffopt
.flags
.recursive
= 1;
631 diff_setup_done(&rev
.diffopt
);
632 add_pending_object(&rev
, head
, NULL
);
633 run_diff_index(&rev
, 0);
634 release_revisions(&rev
);
637 static void describe_detached_head(const char *msg
, struct commit
*commit
)
639 struct strbuf sb
= STRBUF_INIT
;
641 if (!parse_commit(commit
))
642 pp_commit_easy(CMIT_FMT_ONELINE
, commit
, &sb
);
643 if (print_sha1_ellipsis()) {
644 fprintf(stderr
, "%s %s... %s\n", msg
,
645 find_unique_abbrev(&commit
->object
.oid
, DEFAULT_ABBREV
), sb
.buf
);
647 fprintf(stderr
, "%s %s %s\n", msg
,
648 find_unique_abbrev(&commit
->object
.oid
, DEFAULT_ABBREV
), sb
.buf
);
653 static int reset_tree(struct tree
*tree
, const struct checkout_opts
*o
,
654 int worktree
, int *writeout_error
,
655 struct branch_info
*info
)
657 struct unpack_trees_options opts
;
658 struct tree_desc tree_desc
;
660 memset(&opts
, 0, sizeof(opts
));
662 opts
.update
= worktree
;
663 opts
.skip_unmerged
= !worktree
;
664 opts
.reset
= o
->force
? UNPACK_RESET_OVERWRITE_UNTRACKED
:
665 UNPACK_RESET_PROTECT_UNTRACKED
;
666 opts
.preserve_ignored
= (!o
->force
&& !o
->overwrite_ignore
);
668 opts
.fn
= oneway_merge
;
669 opts
.verbose_update
= o
->show_progress
;
670 opts
.src_index
= &the_index
;
671 opts
.dst_index
= &the_index
;
672 init_checkout_metadata(&opts
.meta
, info
->refname
,
673 info
->commit
? &info
->commit
->object
.oid
: null_oid(),
676 init_tree_desc(&tree_desc
, tree
->buffer
, tree
->size
);
677 switch (unpack_trees(1, &tree_desc
, &opts
)) {
681 * We return 0 nevertheless, as the index is all right
682 * and more importantly we have made best efforts to
683 * update paths in the work tree, and we cannot revert
694 static void setup_branch_path(struct branch_info
*branch
)
696 struct strbuf buf
= STRBUF_INIT
;
699 * If this is a ref, resolve it; otherwise, look up the OID for our
700 * expression. Failure here is okay.
702 if (!dwim_ref(branch
->name
, strlen(branch
->name
), &branch
->oid
, &branch
->refname
, 0))
703 repo_get_oid_committish(the_repository
, branch
->name
, &branch
->oid
);
705 strbuf_branchname(&buf
, branch
->name
, INTERPRET_BRANCH_LOCAL
);
706 if (strcmp(buf
.buf
, branch
->name
)) {
708 branch
->name
= xstrdup(buf
.buf
);
710 strbuf_splice(&buf
, 0, 0, "refs/heads/", 11);
712 branch
->path
= strbuf_detach(&buf
, NULL
);
715 static void init_topts(struct unpack_trees_options
*topts
, int merge
,
716 int show_progress
, int overwrite_ignore
,
717 struct commit
*old_commit
)
719 memset(topts
, 0, sizeof(*topts
));
720 topts
->head_idx
= -1;
721 topts
->src_index
= &the_index
;
722 topts
->dst_index
= &the_index
;
724 setup_unpack_trees_porcelain(topts
, "checkout");
726 topts
->initial_checkout
= is_index_unborn(&the_index
);
729 topts
->quiet
= merge
&& old_commit
;
730 topts
->verbose_update
= show_progress
;
731 topts
->fn
= twoway_merge
;
732 topts
->preserve_ignored
= !overwrite_ignore
;
735 static int merge_working_tree(const struct checkout_opts
*opts
,
736 struct branch_info
*old_branch_info
,
737 struct branch_info
*new_branch_info
,
741 struct lock_file lock_file
= LOCK_INIT
;
742 struct tree
*new_tree
;
744 repo_hold_locked_index(the_repository
, &lock_file
, LOCK_DIE_ON_ERROR
);
745 if (repo_read_index_preload(the_repository
, NULL
, 0) < 0)
746 return error(_("index file corrupt"));
748 resolve_undo_clear_index(&the_index
);
749 if (opts
->new_orphan_branch
&& opts
->orphan_from_empty_tree
) {
750 if (new_branch_info
->commit
)
751 BUG("'switch --orphan' should never accept a commit as starting point");
752 new_tree
= parse_tree_indirect(the_hash_algo
->empty_tree
);
754 new_tree
= get_commit_tree(new_branch_info
->commit
);
755 if (opts
->discard_changes
) {
756 ret
= reset_tree(new_tree
, opts
, 1, writeout_error
, new_branch_info
);
760 struct tree_desc trees
[2];
762 struct unpack_trees_options topts
;
763 const struct object_id
*old_commit_oid
;
765 refresh_index(&the_index
, REFRESH_QUIET
, NULL
, NULL
, NULL
);
767 if (unmerged_index(&the_index
)) {
768 error(_("you need to resolve your current index first"));
772 /* 2-way merge to the new branch */
773 init_topts(&topts
, opts
->merge
, opts
->show_progress
,
774 opts
->overwrite_ignore
, old_branch_info
->commit
);
775 init_checkout_metadata(&topts
.meta
, new_branch_info
->refname
,
776 new_branch_info
->commit
?
777 &new_branch_info
->commit
->object
.oid
:
778 &new_branch_info
->oid
, NULL
);
780 old_commit_oid
= old_branch_info
->commit
?
781 &old_branch_info
->commit
->object
.oid
:
782 the_hash_algo
->empty_tree
;
783 tree
= parse_tree_indirect(old_commit_oid
);
785 die(_("unable to parse commit %s"),
786 oid_to_hex(old_commit_oid
));
788 init_tree_desc(&trees
[0], tree
->buffer
, tree
->size
);
789 parse_tree(new_tree
);
791 init_tree_desc(&trees
[1], tree
->buffer
, tree
->size
);
793 ret
= unpack_trees(2, trees
, &topts
);
794 clear_unpack_trees_porcelain(&topts
);
797 * Unpack couldn't do a trivial merge; either
798 * give up or do a real merge, depending on
799 * whether the merge flag was used.
802 struct tree
*old_tree
;
803 struct merge_options o
;
804 struct strbuf sb
= STRBUF_INIT
;
805 struct strbuf old_commit_shortname
= STRBUF_INIT
;
811 * Without old_branch_info->commit, the below is the same as
812 * the two-tree unpack we already tried and failed.
814 if (!old_branch_info
->commit
)
816 old_tree
= get_commit_tree(old_branch_info
->commit
);
818 if (repo_index_has_changes(the_repository
, old_tree
, &sb
))
819 die(_("cannot continue with staged changes in "
820 "the following files:\n%s"), sb
.buf
);
823 /* Do more real merge */
826 * We update the index fully, then write the
827 * tree from the index, then merge the new
828 * branch with the current tree, with the old
829 * branch as the base. Then we reset the index
830 * (but not the working tree) to the new
831 * branch, leaving the working tree as the
832 * merged version, but skipping unmerged
833 * entries in the index.
836 add_files_to_cache(NULL
, NULL
, 0);
837 init_merge_options(&o
, the_repository
);
839 work
= write_in_core_index_as_tree(the_repository
);
841 ret
= reset_tree(new_tree
,
843 writeout_error
, new_branch_info
);
846 o
.ancestor
= old_branch_info
->name
;
847 if (!old_branch_info
->name
) {
848 strbuf_add_unique_abbrev(&old_commit_shortname
,
849 &old_branch_info
->commit
->object
.oid
,
851 o
.ancestor
= old_commit_shortname
.buf
;
853 o
.branch1
= new_branch_info
->name
;
855 ret
= merge_trees(&o
,
861 ret
= reset_tree(new_tree
,
863 writeout_error
, new_branch_info
);
864 strbuf_release(&o
.obuf
);
865 strbuf_release(&old_commit_shortname
);
871 if (!cache_tree_fully_valid(the_index
.cache_tree
))
872 cache_tree_update(&the_index
, WRITE_TREE_SILENT
| WRITE_TREE_REPAIR
);
874 if (write_locked_index(&the_index
, &lock_file
, COMMIT_LOCK
))
875 die(_("unable to write new index file"));
877 if (!opts
->discard_changes
&& !opts
->quiet
&& new_branch_info
->commit
)
878 show_local_changes(&new_branch_info
->commit
->object
, &opts
->diff_options
);
883 static void report_tracking(struct branch_info
*new_branch_info
)
885 struct strbuf sb
= STRBUF_INIT
;
886 struct branch
*branch
= branch_get(new_branch_info
->name
);
888 if (!format_tracking_info(branch
, &sb
, AHEAD_BEHIND_FULL
))
890 fputs(sb
.buf
, stdout
);
894 static void update_refs_for_switch(const struct checkout_opts
*opts
,
895 struct branch_info
*old_branch_info
,
896 struct branch_info
*new_branch_info
)
898 struct strbuf msg
= STRBUF_INIT
;
899 const char *old_desc
, *reflog_msg
;
900 if (opts
->new_branch
) {
901 if (opts
->new_orphan_branch
) {
904 refname
= mkpathdup("refs/heads/%s", opts
->new_orphan_branch
);
905 if (opts
->new_branch_log
&&
906 !should_autocreate_reflog(refname
)) {
908 struct strbuf err
= STRBUF_INIT
;
910 ret
= safe_create_reflog(refname
, &err
);
912 fprintf(stderr
, _("Can not do reflog for '%s': %s\n"),
913 opts
->new_orphan_branch
, err
.buf
);
914 strbuf_release(&err
);
918 strbuf_release(&err
);
923 create_branch(the_repository
,
924 opts
->new_branch
, new_branch_info
->name
,
925 opts
->new_branch_force
? 1 : 0,
926 opts
->new_branch_force
? 1 : 0,
927 opts
->new_branch_log
,
931 free(new_branch_info
->name
);
932 free(new_branch_info
->refname
);
933 new_branch_info
->name
= xstrdup(opts
->new_branch
);
934 setup_branch_path(new_branch_info
);
937 old_desc
= old_branch_info
->name
;
938 if (!old_desc
&& old_branch_info
->commit
)
939 old_desc
= oid_to_hex(&old_branch_info
->commit
->object
.oid
);
941 reflog_msg
= getenv("GIT_REFLOG_ACTION");
943 strbuf_addf(&msg
, "checkout: moving from %s to %s",
944 old_desc
? old_desc
: "(invalid)", new_branch_info
->name
);
946 strbuf_insertstr(&msg
, 0, reflog_msg
);
948 if (!strcmp(new_branch_info
->name
, "HEAD") && !new_branch_info
->path
&& !opts
->force_detach
) {
950 } else if (opts
->force_detach
|| !new_branch_info
->path
) { /* No longer on any branch. */
951 update_ref(msg
.buf
, "HEAD", &new_branch_info
->commit
->object
.oid
, NULL
,
952 REF_NO_DEREF
, UPDATE_REFS_DIE_ON_ERR
);
954 if (old_branch_info
->path
&&
955 advice_enabled(ADVICE_DETACHED_HEAD
) && !opts
->force_detach
)
956 detach_advice(new_branch_info
->name
);
957 describe_detached_head(_("HEAD is now at"), new_branch_info
->commit
);
959 } else if (new_branch_info
->path
) { /* Switch branches. */
960 if (create_symref("HEAD", new_branch_info
->path
, msg
.buf
) < 0)
961 die(_("unable to update HEAD"));
963 if (old_branch_info
->path
&& !strcmp(new_branch_info
->path
, old_branch_info
->path
)) {
964 if (opts
->new_branch_force
)
965 fprintf(stderr
, _("Reset branch '%s'\n"),
966 new_branch_info
->name
);
968 fprintf(stderr
, _("Already on '%s'\n"),
969 new_branch_info
->name
);
970 } else if (opts
->new_branch
) {
971 if (opts
->branch_exists
)
972 fprintf(stderr
, _("Switched to and reset branch '%s'\n"), new_branch_info
->name
);
974 fprintf(stderr
, _("Switched to a new branch '%s'\n"), new_branch_info
->name
);
976 fprintf(stderr
, _("Switched to branch '%s'\n"),
977 new_branch_info
->name
);
980 if (old_branch_info
->path
&& old_branch_info
->name
) {
981 if (!ref_exists(old_branch_info
->path
) && reflog_exists(old_branch_info
->path
))
982 delete_reflog(old_branch_info
->path
);
985 remove_branch_state(the_repository
, !opts
->quiet
);
986 strbuf_release(&msg
);
988 (new_branch_info
->path
|| (!opts
->force_detach
&& !strcmp(new_branch_info
->name
, "HEAD"))))
989 report_tracking(new_branch_info
);
992 static int add_pending_uninteresting_ref(const char *refname
,
993 const struct object_id
*oid
,
994 int flags UNUSED
, void *cb_data
)
996 add_pending_oid(cb_data
, refname
, oid
, UNINTERESTING
);
1000 static void describe_one_orphan(struct strbuf
*sb
, struct commit
*commit
)
1002 strbuf_addstr(sb
, " ");
1003 strbuf_add_unique_abbrev(sb
, &commit
->object
.oid
, DEFAULT_ABBREV
);
1004 strbuf_addch(sb
, ' ');
1005 if (!parse_commit(commit
))
1006 pp_commit_easy(CMIT_FMT_ONELINE
, commit
, sb
);
1007 strbuf_addch(sb
, '\n');
1010 #define ORPHAN_CUTOFF 4
1011 static void suggest_reattach(struct commit
*commit
, struct rev_info
*revs
)
1013 struct commit
*c
, *last
= NULL
;
1014 struct strbuf sb
= STRBUF_INIT
;
1016 while ((c
= get_revision(revs
)) != NULL
) {
1017 if (lost
< ORPHAN_CUTOFF
)
1018 describe_one_orphan(&sb
, c
);
1022 if (ORPHAN_CUTOFF
< lost
) {
1023 int more
= lost
- ORPHAN_CUTOFF
;
1025 describe_one_orphan(&sb
, last
);
1027 strbuf_addf(&sb
, _(" ... and %d more.\n"), more
);
1032 /* The singular version */
1033 "Warning: you are leaving %d commit behind, "
1034 "not connected to\n"
1035 "any of your branches:\n\n"
1037 /* The plural version */
1038 "Warning: you are leaving %d commits behind, "
1039 "not connected to\n"
1040 "any of your branches:\n\n"
1042 /* Give ngettext() the count */
1046 strbuf_release(&sb
);
1048 if (advice_enabled(ADVICE_DETACHED_HEAD
))
1051 /* The singular version */
1052 "If you want to keep it by creating a new branch, "
1053 "this may be a good time\nto do so with:\n\n"
1054 " git branch <new-branch-name> %s\n\n",
1055 /* The plural version */
1056 "If you want to keep them by creating a new branch, "
1057 "this may be a good time\nto do so with:\n\n"
1058 " git branch <new-branch-name> %s\n\n",
1059 /* Give ngettext() the count */
1061 find_unique_abbrev(&commit
->object
.oid
, DEFAULT_ABBREV
));
1065 * We are about to leave commit that was at the tip of a detached
1066 * HEAD. If it is not reachable from any ref, this is the last chance
1067 * for the user to do so without resorting to reflog.
1069 static void orphaned_commit_warning(struct commit
*old_commit
, struct commit
*new_commit
)
1071 struct rev_info revs
;
1072 struct object
*object
= &old_commit
->object
;
1074 repo_init_revisions(the_repository
, &revs
, NULL
);
1075 setup_revisions(0, NULL
, &revs
, NULL
);
1077 object
->flags
&= ~UNINTERESTING
;
1078 add_pending_object(&revs
, object
, oid_to_hex(&object
->oid
));
1080 for_each_ref(add_pending_uninteresting_ref
, &revs
);
1082 add_pending_oid(&revs
, "HEAD",
1083 &new_commit
->object
.oid
,
1086 if (prepare_revision_walk(&revs
))
1087 die(_("internal error in revision walk"));
1088 if (!(old_commit
->object
.flags
& UNINTERESTING
))
1089 suggest_reattach(old_commit
, &revs
);
1091 describe_detached_head(_("Previous HEAD position was"), old_commit
);
1093 /* Clean up objects used, as they will be reused. */
1094 repo_clear_commit_marks(the_repository
, ALL_REV_FLAGS
);
1095 release_revisions(&revs
);
1098 static int switch_branches(const struct checkout_opts
*opts
,
1099 struct branch_info
*new_branch_info
)
1102 struct branch_info old_branch_info
= { 0 };
1103 struct object_id rev
;
1104 int flag
, writeout_error
= 0;
1107 trace2_cmd_mode("branch");
1109 memset(&old_branch_info
, 0, sizeof(old_branch_info
));
1110 old_branch_info
.path
= resolve_refdup("HEAD", 0, &rev
, &flag
);
1111 if (old_branch_info
.path
)
1112 old_branch_info
.commit
= lookup_commit_reference_gently(the_repository
, &rev
, 1);
1113 if (!(flag
& REF_ISSYMREF
))
1114 FREE_AND_NULL(old_branch_info
.path
);
1116 if (old_branch_info
.path
) {
1117 const char *const prefix
= "refs/heads/";
1119 if (skip_prefix(old_branch_info
.path
, prefix
, &p
))
1120 old_branch_info
.name
= xstrdup(p
);
1123 if (opts
->new_orphan_branch
&& opts
->orphan_from_empty_tree
) {
1124 if (new_branch_info
->name
)
1125 BUG("'switch --orphan' should never accept a commit as starting point");
1126 new_branch_info
->commit
= NULL
;
1127 new_branch_info
->name
= xstrdup("(empty)");
1131 if (!new_branch_info
->name
) {
1132 new_branch_info
->name
= xstrdup("HEAD");
1133 new_branch_info
->commit
= old_branch_info
.commit
;
1134 if (!new_branch_info
->commit
)
1135 die(_("You are on a branch yet to be born"));
1136 parse_commit_or_die(new_branch_info
->commit
);
1138 if (opts
->only_merge_on_switching_branches
)
1143 ret
= merge_working_tree(opts
, &old_branch_info
, new_branch_info
, &writeout_error
);
1145 branch_info_release(&old_branch_info
);
1150 if (!opts
->quiet
&& !old_branch_info
.path
&& old_branch_info
.commit
&& new_branch_info
->commit
!= old_branch_info
.commit
)
1151 orphaned_commit_warning(old_branch_info
.commit
, new_branch_info
->commit
);
1153 update_refs_for_switch(opts
, &old_branch_info
, new_branch_info
);
1155 ret
= post_checkout_hook(old_branch_info
.commit
, new_branch_info
->commit
, 1);
1156 branch_info_release(&old_branch_info
);
1158 return ret
|| writeout_error
;
1161 static int git_checkout_config(const char *var
, const char *value
, void *cb
)
1163 struct checkout_opts
*opts
= cb
;
1165 if (!strcmp(var
, "diff.ignoresubmodules")) {
1166 handle_ignore_submodules_arg(&opts
->diff_options
, value
);
1169 if (!strcmp(var
, "checkout.guess")) {
1170 opts
->dwim_new_local_branch
= git_config_bool(var
, value
);
1174 if (starts_with(var
, "submodule."))
1175 return git_default_submodule_config(var
, value
, NULL
);
1177 return git_xmerge_config(var
, value
, NULL
);
1180 static void setup_new_branch_info_and_source_tree(
1181 struct branch_info
*new_branch_info
,
1182 struct checkout_opts
*opts
,
1183 struct object_id
*rev
,
1186 struct tree
**source_tree
= &opts
->source_tree
;
1187 struct object_id branch_rev
;
1189 new_branch_info
->name
= xstrdup(arg
);
1190 setup_branch_path(new_branch_info
);
1192 if (!check_refname_format(new_branch_info
->path
, 0) &&
1193 !read_ref(new_branch_info
->path
, &branch_rev
))
1194 oidcpy(rev
, &branch_rev
);
1196 /* not an existing branch */
1197 FREE_AND_NULL(new_branch_info
->path
);
1199 new_branch_info
->commit
= lookup_commit_reference_gently(the_repository
, rev
, 1);
1200 if (!new_branch_info
->commit
) {
1202 *source_tree
= parse_tree_indirect(rev
);
1204 parse_commit_or_die(new_branch_info
->commit
);
1205 *source_tree
= get_commit_tree(new_branch_info
->commit
);
1209 static const char *parse_remote_branch(const char *arg
,
1210 struct object_id
*rev
,
1211 int could_be_checkout_paths
)
1213 int num_matches
= 0;
1214 const char *remote
= unique_tracking_name(arg
, rev
, &num_matches
);
1216 if (remote
&& could_be_checkout_paths
) {
1217 die(_("'%s' could be both a local file and a tracking branch.\n"
1218 "Please use -- (and optionally --no-guess) to disambiguate"),
1222 if (!remote
&& num_matches
> 1) {
1223 if (advice_enabled(ADVICE_CHECKOUT_AMBIGUOUS_REMOTE_BRANCH_NAME
)) {
1224 advise(_("If you meant to check out a remote tracking branch on, e.g. 'origin',\n"
1225 "you can do so by fully qualifying the name with the --track option:\n"
1227 " git checkout --track origin/<name>\n"
1229 "If you'd like to always have checkouts of an ambiguous <name> prefer\n"
1230 "one remote, e.g. the 'origin' remote, consider setting\n"
1231 "checkout.defaultRemote=origin in your config."));
1234 die(_("'%s' matched multiple (%d) remote tracking branches"),
1241 static int parse_branchname_arg(int argc
, const char **argv
,
1242 int dwim_new_local_branch_ok
,
1243 struct branch_info
*new_branch_info
,
1244 struct checkout_opts
*opts
,
1245 struct object_id
*rev
)
1247 const char **new_branch
= &opts
->new_branch
;
1251 int has_dash_dash
= 0;
1255 * case 1: git checkout <ref> -- [<paths>]
1257 * <ref> must be a valid tree, everything after the '--' must be
1260 * case 2: git checkout -- [<paths>]
1262 * everything after the '--' must be paths.
1264 * case 3: git checkout <something> [--]
1266 * (a) If <something> is a commit, that is to
1267 * switch to the branch or detach HEAD at it. As a special case,
1268 * if <something> is A...B (missing A or B means HEAD but you can
1269 * omit at most one side), and if there is a unique merge base
1270 * between A and B, A...B names that merge base.
1272 * (b) If <something> is _not_ a commit, either "--" is present
1273 * or <something> is not a path, no -t or -b was given, and
1274 * and there is a tracking branch whose name is <something>
1275 * in one and only one remote (or if the branch exists on the
1276 * remote named in checkout.defaultRemote), then this is a
1277 * short-hand to fork local <something> from that
1278 * remote-tracking branch.
1280 * (c) Otherwise, if "--" is present, treat it like case (1).
1283 * - if it's a reference, treat it like case (1)
1284 * - else if it's a path, treat it like case (2)
1287 * case 4: git checkout <something> <paths>
1289 * The first argument must not be ambiguous.
1290 * - If it's *only* a reference, treat it like case (1).
1291 * - If it's only a path, treat it like case (2).
1298 if (!opts
->accept_pathspec
) {
1300 die(_("only one reference expected"));
1301 has_dash_dash
= 1; /* helps disambiguate */
1306 for (i
= 0; i
< argc
; i
++) {
1307 if (opts
->accept_pathspec
&& !strcmp(argv
[i
], "--")) {
1312 if (dash_dash_pos
== 0)
1313 return 1; /* case (2) */
1314 else if (dash_dash_pos
== 1)
1315 has_dash_dash
= 1; /* case (3) or (1) */
1316 else if (dash_dash_pos
>= 2)
1317 die(_("only one reference expected, %d given."), dash_dash_pos
);
1318 opts
->count_checkout_paths
= !opts
->quiet
&& !has_dash_dash
;
1320 if (!strcmp(arg
, "-"))
1323 if (get_oid_mb(arg
, rev
)) {
1325 * Either case (3) or (4), with <something> not being
1326 * a commit, or an attempt to use case (1) with an
1329 * It's likely an error, but we need to find out if
1330 * we should auto-create the branch, case (3).(b).
1332 int recover_with_dwim
= dwim_new_local_branch_ok
;
1334 int could_be_checkout_paths
= !has_dash_dash
&&
1335 check_filename(opts
->prefix
, arg
);
1337 if (!has_dash_dash
&& !no_wildcard(arg
))
1338 recover_with_dwim
= 0;
1341 * Accept "git checkout foo", "git checkout foo --"
1342 * and "git switch foo" as candidates for dwim.
1344 if (!(argc
== 1 && !has_dash_dash
) &&
1345 !(argc
== 2 && has_dash_dash
) &&
1346 opts
->accept_pathspec
)
1347 recover_with_dwim
= 0;
1349 if (recover_with_dwim
) {
1350 const char *remote
= parse_remote_branch(arg
, rev
,
1351 could_be_checkout_paths
);
1355 /* DWIMmed to create local branch, case (3).(b) */
1357 recover_with_dwim
= 0;
1361 if (!recover_with_dwim
) {
1363 die(_("invalid reference: %s"), arg
);
1368 /* we can't end up being in (2) anymore, eat the argument */
1373 setup_new_branch_info_and_source_tree(new_branch_info
, opts
, rev
, arg
);
1375 if (!opts
->source_tree
) /* case (1): want a tree */
1376 die(_("reference is not a tree: %s"), arg
);
1378 if (!has_dash_dash
) { /* case (3).(d) -> (1) */
1380 * Do not complain the most common case
1381 * git checkout branch
1382 * even if there happen to be a file called 'branch';
1383 * it would be extremely annoying.
1386 verify_non_filename(opts
->prefix
, arg
);
1387 } else if (opts
->accept_pathspec
) {
1396 static int switch_unborn_to_new_branch(const struct checkout_opts
*opts
)
1399 struct strbuf branch_ref
= STRBUF_INIT
;
1401 trace2_cmd_mode("unborn");
1403 if (!opts
->new_branch
)
1404 die(_("You are on a branch yet to be born"));
1405 strbuf_addf(&branch_ref
, "refs/heads/%s", opts
->new_branch
);
1406 status
= create_symref("HEAD", branch_ref
.buf
, "checkout -b");
1407 strbuf_release(&branch_ref
);
1409 fprintf(stderr
, _("Switched to a new branch '%s'\n"),
1414 static void die_expecting_a_branch(const struct branch_info
*branch_info
)
1416 struct object_id oid
;
1420 if (dwim_ref(branch_info
->name
, strlen(branch_info
->name
), &oid
, &to_free
, 0) == 1) {
1421 const char *ref
= to_free
;
1423 if (skip_prefix(ref
, "refs/tags/", &ref
))
1424 code
= die_message(_("a branch is expected, got tag '%s'"), ref
);
1425 else if (skip_prefix(ref
, "refs/remotes/", &ref
))
1426 code
= die_message(_("a branch is expected, got remote branch '%s'"), ref
);
1428 code
= die_message(_("a branch is expected, got '%s'"), ref
);
1430 else if (branch_info
->commit
)
1431 code
= die_message(_("a branch is expected, got commit '%s'"), branch_info
->name
);
1434 * This case should never happen because we already die() on
1435 * non-commit, but just in case.
1437 code
= die_message(_("a branch is expected, got '%s'"), branch_info
->name
);
1439 if (advice_enabled(ADVICE_SUGGEST_DETACHING_HEAD
))
1440 advise(_("If you want to detach HEAD at the commit, try again with the --detach option."));
1445 static void die_if_some_operation_in_progress(void)
1447 struct wt_status_state state
;
1449 memset(&state
, 0, sizeof(state
));
1450 wt_status_get_state(the_repository
, &state
, 0);
1452 if (state
.merge_in_progress
)
1453 die(_("cannot switch branch while merging\n"
1454 "Consider \"git merge --quit\" "
1455 "or \"git worktree add\"."));
1456 if (state
.am_in_progress
)
1457 die(_("cannot switch branch in the middle of an am session\n"
1458 "Consider \"git am --quit\" "
1459 "or \"git worktree add\"."));
1460 if (state
.rebase_interactive_in_progress
|| state
.rebase_in_progress
)
1461 die(_("cannot switch branch while rebasing\n"
1462 "Consider \"git rebase --quit\" "
1463 "or \"git worktree add\"."));
1464 if (state
.cherry_pick_in_progress
)
1465 die(_("cannot switch branch while cherry-picking\n"
1466 "Consider \"git cherry-pick --quit\" "
1467 "or \"git worktree add\"."));
1468 if (state
.revert_in_progress
)
1469 die(_("cannot switch branch while reverting\n"
1470 "Consider \"git revert --quit\" "
1471 "or \"git worktree add\"."));
1472 if (state
.bisect_in_progress
)
1473 warning(_("you are switching branch while bisecting"));
1476 static int checkout_branch(struct checkout_opts
*opts
,
1477 struct branch_info
*new_branch_info
)
1479 if (opts
->pathspec
.nr
)
1480 die(_("paths cannot be used with switching branches"));
1482 if (opts
->patch_mode
)
1483 die(_("'%s' cannot be used with switching branches"),
1486 if (opts
->overlay_mode
!= -1)
1487 die(_("'%s' cannot be used with switching branches"),
1490 if (opts
->writeout_stage
)
1491 die(_("'%s' cannot be used with switching branches"),
1494 if (opts
->force
&& opts
->merge
)
1495 die(_("'%s' cannot be used with '%s'"), "-f", "-m");
1497 if (opts
->discard_changes
&& opts
->merge
)
1498 die(_("'%s' cannot be used with '%s'"), "--discard-changes", "--merge");
1500 if (opts
->force_detach
&& opts
->new_branch
)
1501 die(_("'%s' cannot be used with '%s'"),
1502 "--detach", "-b/-B/--orphan");
1504 if (opts
->new_orphan_branch
) {
1505 if (opts
->track
!= BRANCH_TRACK_UNSPECIFIED
)
1506 die(_("'%s' cannot be used with '%s'"), "--orphan", "-t");
1507 if (opts
->orphan_from_empty_tree
&& new_branch_info
->name
)
1508 die(_("'%s' cannot take <start-point>"), "--orphan");
1509 } else if (opts
->force_detach
) {
1510 if (opts
->track
!= BRANCH_TRACK_UNSPECIFIED
)
1511 die(_("'%s' cannot be used with '%s'"), "--detach", "-t");
1512 } else if (opts
->track
== BRANCH_TRACK_UNSPECIFIED
)
1513 opts
->track
= git_branch_track
;
1515 if (new_branch_info
->name
&& !new_branch_info
->commit
)
1516 die(_("Cannot switch branch to a non-commit '%s'"),
1517 new_branch_info
->name
);
1519 if (!opts
->switch_branch_doing_nothing_is_ok
&&
1520 !new_branch_info
->name
&&
1521 !opts
->new_branch
&&
1522 !opts
->force_detach
)
1523 die(_("missing branch or commit argument"));
1525 if (!opts
->implicit_detach
&&
1526 !opts
->force_detach
&&
1527 !opts
->new_branch
&&
1528 !opts
->new_branch_force
&&
1529 new_branch_info
->name
&&
1530 !new_branch_info
->path
)
1531 die_expecting_a_branch(new_branch_info
);
1533 if (!opts
->can_switch_when_in_progress
)
1534 die_if_some_operation_in_progress();
1536 if (new_branch_info
->path
&& !opts
->force_detach
&& !opts
->new_branch
&&
1537 !opts
->ignore_other_worktrees
) {
1539 char *head_ref
= resolve_refdup("HEAD", 0, NULL
, &flag
);
1541 (!(flag
& REF_ISSYMREF
) || strcmp(head_ref
, new_branch_info
->path
)))
1542 die_if_checked_out(new_branch_info
->path
, 1);
1546 if (!new_branch_info
->commit
&& opts
->new_branch
) {
1547 struct object_id rev
;
1550 if (!read_ref_full("HEAD", 0, &rev
, &flag
) &&
1551 (flag
& REF_ISSYMREF
) && is_null_oid(&rev
))
1552 return switch_unborn_to_new_branch(opts
);
1554 return switch_branches(opts
, new_branch_info
);
1557 static struct option
*add_common_options(struct checkout_opts
*opts
,
1558 struct option
*prevopts
)
1560 struct option options
[] = {
1561 OPT__QUIET(&opts
->quiet
, N_("suppress progress reporting")),
1562 OPT_CALLBACK_F(0, "recurse-submodules", NULL
,
1563 "checkout", "control recursive updating of submodules",
1564 PARSE_OPT_OPTARG
, option_parse_recurse_submodules_worktree_updater
),
1565 OPT_BOOL(0, "progress", &opts
->show_progress
, N_("force progress reporting")),
1566 OPT_BOOL('m', "merge", &opts
->merge
, N_("perform a 3-way merge with the new branch")),
1567 OPT_STRING(0, "conflict", &opts
->conflict_style
, N_("style"),
1568 N_("conflict style (merge, diff3, or zdiff3)")),
1571 struct option
*newopts
= parse_options_concat(prevopts
, options
);
1576 static struct option
*add_common_switch_branch_options(
1577 struct checkout_opts
*opts
, struct option
*prevopts
)
1579 struct option options
[] = {
1580 OPT_BOOL('d', "detach", &opts
->force_detach
, N_("detach HEAD at named commit")),
1581 OPT_CALLBACK_F('t', "track", &opts
->track
, "(direct|inherit)",
1582 N_("set branch tracking configuration"),
1584 parse_opt_tracking_mode
),
1585 OPT__FORCE(&opts
->force
, N_("force checkout (throw away local modifications)"),
1586 PARSE_OPT_NOCOMPLETE
),
1587 OPT_STRING(0, "orphan", &opts
->new_orphan_branch
, N_("new-branch"), N_("new unparented branch")),
1588 OPT_BOOL_F(0, "overwrite-ignore", &opts
->overwrite_ignore
,
1589 N_("update ignored files (default)"),
1590 PARSE_OPT_NOCOMPLETE
),
1591 OPT_BOOL(0, "ignore-other-worktrees", &opts
->ignore_other_worktrees
,
1592 N_("do not check if another worktree is holding the given ref")),
1595 struct option
*newopts
= parse_options_concat(prevopts
, options
);
1600 static struct option
*add_checkout_path_options(struct checkout_opts
*opts
,
1601 struct option
*prevopts
)
1603 struct option options
[] = {
1604 OPT_SET_INT_F('2', "ours", &opts
->writeout_stage
,
1605 N_("checkout our version for unmerged files"),
1606 2, PARSE_OPT_NONEG
),
1607 OPT_SET_INT_F('3', "theirs", &opts
->writeout_stage
,
1608 N_("checkout their version for unmerged files"),
1609 3, PARSE_OPT_NONEG
),
1610 OPT_BOOL('p', "patch", &opts
->patch_mode
, N_("select hunks interactively")),
1611 OPT_BOOL(0, "ignore-skip-worktree-bits", &opts
->ignore_skipworktree
,
1612 N_("do not limit pathspecs to sparse entries only")),
1613 OPT_PATHSPEC_FROM_FILE(&opts
->pathspec_from_file
),
1614 OPT_PATHSPEC_FILE_NUL(&opts
->pathspec_file_nul
),
1617 struct option
*newopts
= parse_options_concat(prevopts
, options
);
1622 /* create-branch option (either b or c) */
1623 static char cb_option
= 'b';
1625 static int checkout_main(int argc
, const char **argv
, const char *prefix
,
1626 struct checkout_opts
*opts
, struct option
*options
,
1627 const char * const usagestr
[],
1628 struct branch_info
*new_branch_info
)
1630 int parseopt_flags
= 0;
1632 opts
->overwrite_ignore
= 1;
1633 opts
->prefix
= prefix
;
1634 opts
->show_progress
= -1;
1636 git_config(git_checkout_config
, opts
);
1637 if (the_repository
->gitdir
) {
1638 prepare_repo_settings(the_repository
);
1639 the_repository
->settings
.command_requires_full_index
= 0;
1642 opts
->track
= BRANCH_TRACK_UNSPECIFIED
;
1644 if (!opts
->accept_pathspec
&& !opts
->accept_ref
)
1645 BUG("make up your mind, you need to take _something_");
1646 if (opts
->accept_pathspec
&& opts
->accept_ref
)
1647 parseopt_flags
= PARSE_OPT_KEEP_DASHDASH
;
1649 argc
= parse_options(argc
, argv
, prefix
, options
,
1650 usagestr
, parseopt_flags
);
1652 if (opts
->show_progress
< 0) {
1654 opts
->show_progress
= 0;
1656 opts
->show_progress
= isatty(2);
1659 if (opts
->conflict_style
) {
1660 opts
->merge
= 1; /* implied */
1661 git_xmerge_config("merge.conflictstyle", opts
->conflict_style
, NULL
);
1664 opts
->discard_changes
= 1;
1665 opts
->ignore_unmerged_opt
= "--force";
1666 opts
->ignore_unmerged
= 1;
1669 if ((!!opts
->new_branch
+ !!opts
->new_branch_force
+ !!opts
->new_orphan_branch
) > 1)
1670 die(_("options '-%c', '-%c', and '%s' cannot be used together"),
1671 cb_option
, toupper(cb_option
), "--orphan");
1673 if (opts
->overlay_mode
== 1 && opts
->patch_mode
)
1674 die(_("options '%s' and '%s' cannot be used together"), "-p", "--overlay");
1676 if (opts
->checkout_index
>= 0 || opts
->checkout_worktree
>= 0) {
1677 if (opts
->checkout_index
< 0)
1678 opts
->checkout_index
= 0;
1679 if (opts
->checkout_worktree
< 0)
1680 opts
->checkout_worktree
= 0;
1682 if (opts
->checkout_index
< 0)
1683 opts
->checkout_index
= -opts
->checkout_index
- 1;
1684 if (opts
->checkout_worktree
< 0)
1685 opts
->checkout_worktree
= -opts
->checkout_worktree
- 1;
1687 if (opts
->checkout_index
< 0 || opts
->checkout_worktree
< 0)
1688 BUG("these flags should be non-negative by now");
1690 * convenient shortcut: "git restore --staged [--worktree]" equals
1691 * "git restore --staged [--worktree] --source HEAD"
1693 if (!opts
->from_treeish
&& opts
->checkout_index
)
1694 opts
->from_treeish
= "HEAD";
1697 * From here on, new_branch will contain the branch to be checked out,
1698 * and new_branch_force and new_orphan_branch will tell us which one of
1699 * -b/-B/-c/-C/--orphan is being used.
1701 if (opts
->new_branch_force
)
1702 opts
->new_branch
= opts
->new_branch_force
;
1704 if (opts
->new_orphan_branch
)
1705 opts
->new_branch
= opts
->new_orphan_branch
;
1707 /* --track without -c/-C/-b/-B/--orphan should DWIM */
1708 if (opts
->track
!= BRANCH_TRACK_UNSPECIFIED
&& !opts
->new_branch
) {
1709 const char *argv0
= argv
[0];
1710 if (!argc
|| !strcmp(argv0
, "--"))
1711 die(_("--track needs a branch name"));
1712 skip_prefix(argv0
, "refs/", &argv0
);
1713 skip_prefix(argv0
, "remotes/", &argv0
);
1714 argv0
= strchr(argv0
, '/');
1715 if (!argv0
|| !argv0
[1])
1716 die(_("missing branch name; try -%c"), cb_option
);
1717 opts
->new_branch
= argv0
+ 1;
1721 * Extract branch name from command line arguments, so
1722 * all that is left is pathspecs.
1726 * 1) git checkout <tree> -- [<paths>]
1727 * 2) git checkout -- [<paths>]
1728 * 3) git checkout <something> [<paths>]
1730 * including "last branch" syntax and DWIM-ery for names of
1731 * remote branches, erroring out for invalid or ambiguous cases.
1733 if (argc
&& opts
->accept_ref
) {
1734 struct object_id rev
;
1736 !opts
->patch_mode
&&
1737 opts
->dwim_new_local_branch
&&
1738 opts
->track
== BRANCH_TRACK_UNSPECIFIED
&&
1740 int n
= parse_branchname_arg(argc
, argv
, dwim_ok
,
1741 new_branch_info
, opts
, &rev
);
1744 } else if (!opts
->accept_ref
&& opts
->from_treeish
) {
1745 struct object_id rev
;
1747 if (get_oid_mb(opts
->from_treeish
, &rev
))
1748 die(_("could not resolve %s"), opts
->from_treeish
);
1750 setup_new_branch_info_and_source_tree(new_branch_info
,
1752 opts
->from_treeish
);
1754 if (!opts
->source_tree
)
1755 die(_("reference is not a tree: %s"), opts
->from_treeish
);
1759 parse_pathspec(&opts
->pathspec
, 0,
1760 opts
->patch_mode
? PATHSPEC_PREFIX_ORIGIN
: 0,
1763 if (!opts
->pathspec
.nr
)
1764 die(_("invalid path specification"));
1767 * Try to give more helpful suggestion.
1768 * new_branch && argc > 1 will be caught later.
1770 if (opts
->new_branch
&& argc
== 1 && !new_branch_info
->commit
)
1771 die(_("'%s' is not a commit and a branch '%s' cannot be created from it"),
1772 argv
[0], opts
->new_branch
);
1774 if (opts
->force_detach
)
1775 die(_("git checkout: --detach does not take a path argument '%s'"),
1779 if (opts
->pathspec_from_file
) {
1780 if (opts
->pathspec
.nr
)
1781 die(_("'%s' and pathspec arguments cannot be used together"), "--pathspec-from-file");
1783 if (opts
->force_detach
)
1784 die(_("options '%s' and '%s' cannot be used together"), "--pathspec-from-file", "--detach");
1786 if (opts
->patch_mode
)
1787 die(_("options '%s' and '%s' cannot be used together"), "--pathspec-from-file", "--patch");
1789 parse_pathspec_file(&opts
->pathspec
, 0,
1791 prefix
, opts
->pathspec_from_file
, opts
->pathspec_file_nul
);
1792 } else if (opts
->pathspec_file_nul
) {
1793 die(_("the option '%s' requires '%s'"), "--pathspec-file-nul", "--pathspec-from-file");
1796 opts
->pathspec
.recursive
= 1;
1798 if (opts
->pathspec
.nr
) {
1799 if (1 < !!opts
->writeout_stage
+ !!opts
->force
+ !!opts
->merge
)
1800 die(_("git checkout: --ours/--theirs, --force and --merge are incompatible when\n"
1801 "checking out of the index."));
1803 if (opts
->accept_pathspec
&& !opts
->empty_pathspec_ok
&&
1804 !opts
->patch_mode
) /* patch mode is special */
1805 die(_("you must specify path(s) to restore"));
1808 if (opts
->new_branch
) {
1809 struct strbuf buf
= STRBUF_INIT
;
1811 if (opts
->new_branch_force
)
1812 opts
->branch_exists
= validate_branchname(opts
->new_branch
, &buf
);
1814 opts
->branch_exists
=
1815 validate_new_branchname(opts
->new_branch
, &buf
, 0);
1816 strbuf_release(&buf
);
1819 if (opts
->patch_mode
|| opts
->pathspec
.nr
)
1820 return checkout_paths(opts
, new_branch_info
);
1822 return checkout_branch(opts
, new_branch_info
);
1825 int cmd_checkout(int argc
, const char **argv
, const char *prefix
)
1827 struct checkout_opts opts
;
1828 struct option
*options
;
1829 struct option checkout_options
[] = {
1830 OPT_STRING('b', NULL
, &opts
.new_branch
, N_("branch"),
1831 N_("create and checkout a new branch")),
1832 OPT_STRING('B', NULL
, &opts
.new_branch_force
, N_("branch"),
1833 N_("create/reset and checkout a branch")),
1834 OPT_BOOL('l', NULL
, &opts
.new_branch_log
, N_("create reflog for new branch")),
1835 OPT_BOOL(0, "guess", &opts
.dwim_new_local_branch
,
1836 N_("second guess 'git checkout <no-such-branch>' (default)")),
1837 OPT_BOOL(0, "overlay", &opts
.overlay_mode
, N_("use overlay mode (default)")),
1841 struct branch_info new_branch_info
= { 0 };
1843 memset(&opts
, 0, sizeof(opts
));
1844 opts
.dwim_new_local_branch
= 1;
1845 opts
.switch_branch_doing_nothing_is_ok
= 1;
1846 opts
.only_merge_on_switching_branches
= 0;
1847 opts
.accept_ref
= 1;
1848 opts
.accept_pathspec
= 1;
1849 opts
.implicit_detach
= 1;
1850 opts
.can_switch_when_in_progress
= 1;
1851 opts
.orphan_from_empty_tree
= 0;
1852 opts
.empty_pathspec_ok
= 1;
1853 opts
.overlay_mode
= -1;
1854 opts
.checkout_index
= -2; /* default on */
1855 opts
.checkout_worktree
= -2; /* default on */
1857 if (argc
== 3 && !strcmp(argv
[1], "-b")) {
1859 * User ran 'git checkout -b <branch>' and expects
1860 * the same behavior as 'git switch -c <branch>'.
1862 opts
.switch_branch_doing_nothing_is_ok
= 0;
1863 opts
.only_merge_on_switching_branches
= 1;
1866 options
= parse_options_dup(checkout_options
);
1867 options
= add_common_options(&opts
, options
);
1868 options
= add_common_switch_branch_options(&opts
, options
);
1869 options
= add_checkout_path_options(&opts
, options
);
1871 ret
= checkout_main(argc
, argv
, prefix
, &opts
,
1872 options
, checkout_usage
, &new_branch_info
);
1873 branch_info_release(&new_branch_info
);
1874 clear_pathspec(&opts
.pathspec
);
1875 FREE_AND_NULL(options
);
1879 int cmd_switch(int argc
, const char **argv
, const char *prefix
)
1881 struct checkout_opts opts
;
1882 struct option
*options
= NULL
;
1883 struct option switch_options
[] = {
1884 OPT_STRING('c', "create", &opts
.new_branch
, N_("branch"),
1885 N_("create and switch to a new branch")),
1886 OPT_STRING('C', "force-create", &opts
.new_branch_force
, N_("branch"),
1887 N_("create/reset and switch to a branch")),
1888 OPT_BOOL(0, "guess", &opts
.dwim_new_local_branch
,
1889 N_("second guess 'git switch <no-such-branch>'")),
1890 OPT_BOOL(0, "discard-changes", &opts
.discard_changes
,
1891 N_("throw away local modifications")),
1895 struct branch_info new_branch_info
= { 0 };
1897 memset(&opts
, 0, sizeof(opts
));
1898 opts
.dwim_new_local_branch
= 1;
1899 opts
.accept_ref
= 1;
1900 opts
.accept_pathspec
= 0;
1901 opts
.switch_branch_doing_nothing_is_ok
= 0;
1902 opts
.only_merge_on_switching_branches
= 1;
1903 opts
.implicit_detach
= 0;
1904 opts
.can_switch_when_in_progress
= 0;
1905 opts
.orphan_from_empty_tree
= 1;
1906 opts
.overlay_mode
= -1;
1908 options
= parse_options_dup(switch_options
);
1909 options
= add_common_options(&opts
, options
);
1910 options
= add_common_switch_branch_options(&opts
, options
);
1914 ret
= checkout_main(argc
, argv
, prefix
, &opts
,
1915 options
, switch_branch_usage
, &new_branch_info
);
1916 branch_info_release(&new_branch_info
);
1917 FREE_AND_NULL(options
);
1921 int cmd_restore(int argc
, const char **argv
, const char *prefix
)
1923 struct checkout_opts opts
;
1924 struct option
*options
;
1925 struct option restore_options
[] = {
1926 OPT_STRING('s', "source", &opts
.from_treeish
, "<tree-ish>",
1927 N_("which tree-ish to checkout from")),
1928 OPT_BOOL('S', "staged", &opts
.checkout_index
,
1929 N_("restore the index")),
1930 OPT_BOOL('W', "worktree", &opts
.checkout_worktree
,
1931 N_("restore the working tree (default)")),
1932 OPT_BOOL(0, "ignore-unmerged", &opts
.ignore_unmerged
,
1933 N_("ignore unmerged entries")),
1934 OPT_BOOL(0, "overlay", &opts
.overlay_mode
, N_("use overlay mode")),
1938 struct branch_info new_branch_info
= { 0 };
1940 memset(&opts
, 0, sizeof(opts
));
1941 opts
.accept_ref
= 0;
1942 opts
.accept_pathspec
= 1;
1943 opts
.empty_pathspec_ok
= 0;
1944 opts
.overlay_mode
= 0;
1945 opts
.checkout_index
= -1; /* default off */
1946 opts
.checkout_worktree
= -2; /* default on */
1947 opts
.ignore_unmerged_opt
= "--ignore-unmerged";
1949 options
= parse_options_dup(restore_options
);
1950 options
= add_common_options(&opts
, options
);
1951 options
= add_checkout_path_options(&opts
, options
);
1953 ret
= checkout_main(argc
, argv
, prefix
, &opts
,
1954 options
, restore_usage
, &new_branch_info
);
1955 branch_info_release(&new_branch_info
);
1956 FREE_AND_NULL(options
);