1 #define USE_THE_INDEX_VARIABLE
6 #include "cache-tree.h"
12 #include "environment.h"
19 #include "merge-recursive.h"
20 #include "object-name.h"
21 #include "object-store.h"
22 #include "parse-options.h"
25 #include "resolve-undo.h"
27 #include "run-command.h"
29 #include "submodule.h"
30 #include "submodule-config.h"
34 #include "tree-walk.h"
35 #include "unpack-trees.h"
36 #include "wt-status.h"
37 #include "xdiff-interface.h"
39 #include "parallel-checkout.h"
40 #include "add-interactive.h"
42 static const char * const checkout_usage
[] = {
43 N_("git checkout [<options>] <branch>"),
44 N_("git checkout [<options>] [<branch>] -- <file>..."),
48 static const char * const switch_branch_usage
[] = {
49 N_("git switch [<options>] [<branch>]"),
53 static const char * const restore_usage
[] = {
54 N_("git restore [<options>] [--source=<branch>] <file>..."),
58 struct checkout_opts
{
67 int ignore_skipworktree
;
68 int ignore_other_worktrees
;
70 int count_checkout_paths
;
72 int dwim_new_local_branch
;
76 int switch_branch_doing_nothing_is_ok
;
77 int only_merge_on_switching_branches
;
78 int can_switch_when_in_progress
;
79 int orphan_from_empty_tree
;
80 int empty_pathspec_ok
;
82 int checkout_worktree
;
83 const char *ignore_unmerged_opt
;
85 int pathspec_file_nul
;
86 char *pathspec_from_file
;
88 const char *new_branch
;
89 const char *new_branch_force
;
90 const char *new_orphan_branch
;
92 enum branch_track track
;
93 struct diff_options diff_options
;
98 struct pathspec pathspec
;
99 const char *from_treeish
;
100 struct tree
*source_tree
;
104 char *name
; /* The short name used */
105 char *path
; /* The full name of a real branch */
106 struct commit
*commit
; /* The named commit */
107 char *refname
; /* The full name of the ref being checked out. */
108 struct object_id oid
; /* The object ID of the commit being checked out. */
110 * if not null the branch is detached because it's already
111 * checked out in this checkout
116 static void branch_info_release(struct branch_info
*info
)
121 free(info
->checkout
);
124 static int post_checkout_hook(struct commit
*old_commit
, struct commit
*new_commit
,
127 return run_hooks_l("post-checkout",
128 oid_to_hex(old_commit
? &old_commit
->object
.oid
: null_oid()),
129 oid_to_hex(new_commit
? &new_commit
->object
.oid
: null_oid()),
130 changed
? "1" : "0", NULL
);
131 /* "new_commit" can be NULL when checking out from the index before
136 static int update_some(const struct object_id
*oid
, struct strbuf
*base
,
137 const char *pathname
, unsigned mode
, void *context UNUSED
)
140 struct cache_entry
*ce
;
144 return READ_TREE_RECURSIVE
;
146 len
= base
->len
+ strlen(pathname
);
147 ce
= make_empty_cache_entry(&the_index
, len
);
148 oidcpy(&ce
->oid
, oid
);
149 memcpy(ce
->name
, base
->buf
, base
->len
);
150 memcpy(ce
->name
+ base
->len
, pathname
, len
- base
->len
);
151 ce
->ce_flags
= create_ce_flags(0) | CE_UPDATE
;
152 ce
->ce_namelen
= len
;
153 ce
->ce_mode
= create_ce_mode(mode
);
156 * If the entry is the same as the current index, we can leave the old
157 * entry in place. Whether it is UPTODATE or not, checkout_entry will
158 * do the right thing.
160 pos
= index_name_pos(&the_index
, ce
->name
, ce
->ce_namelen
);
162 struct cache_entry
*old
= the_index
.cache
[pos
];
163 if (ce
->ce_mode
== old
->ce_mode
&&
164 !ce_intent_to_add(old
) &&
165 oideq(&ce
->oid
, &old
->oid
)) {
166 old
->ce_flags
|= CE_UPDATE
;
167 discard_cache_entry(ce
);
172 add_index_entry(&the_index
, ce
,
173 ADD_CACHE_OK_TO_ADD
| ADD_CACHE_OK_TO_REPLACE
);
177 static int read_tree_some(struct tree
*tree
, const struct pathspec
*pathspec
)
179 read_tree(the_repository
, tree
,
180 pathspec
, update_some
, NULL
);
182 /* update the index with the given tree's info
183 * for all args, expanding wildcards, and exit
184 * with any non-zero return code.
189 static int skip_same_name(const struct cache_entry
*ce
, int pos
)
191 while (++pos
< the_index
.cache_nr
&&
192 !strcmp(the_index
.cache
[pos
]->name
, ce
->name
))
197 static int check_stage(int stage
, const struct cache_entry
*ce
, int pos
,
200 while (pos
< the_index
.cache_nr
&&
201 !strcmp(the_index
.cache
[pos
]->name
, ce
->name
)) {
202 if (ce_stage(the_index
.cache
[pos
]) == stage
)
209 return error(_("path '%s' does not have our version"), ce
->name
);
211 return error(_("path '%s' does not have their version"), ce
->name
);
214 static int check_stages(unsigned stages
, const struct cache_entry
*ce
, int pos
)
217 const char *name
= ce
->name
;
219 while (pos
< the_index
.cache_nr
) {
220 ce
= the_index
.cache
[pos
];
221 if (strcmp(name
, ce
->name
))
223 seen
|= (1 << ce_stage(ce
));
226 if ((stages
& seen
) != stages
)
227 return error(_("path '%s' does not have all necessary versions"),
232 static int checkout_stage(int stage
, const struct cache_entry
*ce
, int pos
,
233 const struct checkout
*state
, int *nr_checkouts
,
236 while (pos
< the_index
.cache_nr
&&
237 !strcmp(the_index
.cache
[pos
]->name
, ce
->name
)) {
238 if (ce_stage(the_index
.cache
[pos
]) == stage
)
239 return checkout_entry(the_index
.cache
[pos
], state
,
244 unlink_entry(ce
, NULL
);
248 return error(_("path '%s' does not have our version"), ce
->name
);
250 return error(_("path '%s' does not have their version"), ce
->name
);
253 static int checkout_merged(int pos
, const struct checkout
*state
,
254 int *nr_checkouts
, struct mem_pool
*ce_mem_pool
)
256 struct cache_entry
*ce
= the_index
.cache
[pos
];
257 const char *path
= ce
->name
;
258 mmfile_t ancestor
, ours
, theirs
;
259 enum ll_merge_result merge_status
;
261 struct object_id oid
;
262 mmbuffer_t result_buf
;
263 struct object_id threeway
[3];
265 struct ll_merge_options ll_opts
;
268 memset(threeway
, 0, sizeof(threeway
));
269 while (pos
< the_index
.cache_nr
) {
271 stage
= ce_stage(ce
);
272 if (!stage
|| strcmp(path
, ce
->name
))
274 oidcpy(&threeway
[stage
- 1], &ce
->oid
);
276 mode
= create_ce_mode(ce
->ce_mode
);
278 ce
= the_index
.cache
[pos
];
280 if (is_null_oid(&threeway
[1]) || is_null_oid(&threeway
[2]))
281 return error(_("path '%s' does not have necessary versions"), path
);
283 read_mmblob(&ancestor
, &threeway
[0]);
284 read_mmblob(&ours
, &threeway
[1]);
285 read_mmblob(&theirs
, &threeway
[2]);
287 memset(&ll_opts
, 0, sizeof(ll_opts
));
288 git_config_get_bool("merge.renormalize", &renormalize
);
289 ll_opts
.renormalize
= renormalize
;
290 merge_status
= ll_merge(&result_buf
, path
, &ancestor
, "base",
291 &ours
, "ours", &theirs
, "theirs",
292 state
->istate
, &ll_opts
);
296 if (merge_status
== LL_MERGE_BINARY_CONFLICT
)
297 warning("Cannot merge binary files: %s (%s vs. %s)",
298 path
, "ours", "theirs");
299 if (merge_status
< 0 || !result_buf
.ptr
) {
300 free(result_buf
.ptr
);
301 return error(_("path '%s': cannot merge"), path
);
306 * There is absolutely no reason to write this as a blob object
307 * and create a phony cache entry. This hack is primarily to get
308 * to the write_entry() machinery that massages the contents to
309 * work-tree format and writes out which only allows it for a
310 * cache entry. The code in write_entry() needs to be refactored
311 * to allow us to feed a <buffer, size, mode> instead of a cache
312 * entry. Such a refactoring would help merge_recursive as well
313 * (it also writes the merge result to the object database even
314 * when it may contain conflicts).
316 if (write_object_file(result_buf
.ptr
, result_buf
.size
, OBJ_BLOB
, &oid
))
317 die(_("Unable to add merge result for '%s'"), path
);
318 free(result_buf
.ptr
);
319 ce
= make_transient_cache_entry(mode
, &oid
, path
, 2, ce_mem_pool
);
321 die(_("make_cache_entry failed for path '%s'"), path
);
322 status
= checkout_entry(ce
, state
, NULL
, nr_checkouts
);
326 static void mark_ce_for_checkout_overlay(struct cache_entry
*ce
,
328 const struct checkout_opts
*opts
)
330 ce
->ce_flags
&= ~CE_MATCHED
;
331 if (!opts
->ignore_skipworktree
&& ce_skip_worktree(ce
))
333 if (opts
->source_tree
&& !(ce
->ce_flags
& CE_UPDATE
))
335 * "git checkout tree-ish -- path", but this entry
336 * is in the original index but is not in tree-ish
337 * or does not match the pathspec; it will not be
338 * checked out to the working tree. We will not do
339 * anything to this entry at all.
343 * Either this entry came from the tree-ish we are
344 * checking the paths out of, or we are checking out
347 * If it comes from the tree-ish, we already know it
348 * matches the pathspec and could just stamp
349 * CE_MATCHED to it from update_some(). But we still
350 * need ps_matched and read_tree (and
351 * eventually tree_entry_interesting) cannot fill
352 * ps_matched yet. Once it can, we can avoid calling
353 * match_pathspec() for _all_ entries when
354 * opts->source_tree != NULL.
356 if (ce_path_match(&the_index
, ce
, &opts
->pathspec
, ps_matched
))
357 ce
->ce_flags
|= CE_MATCHED
;
360 static void mark_ce_for_checkout_no_overlay(struct cache_entry
*ce
,
362 const struct checkout_opts
*opts
)
364 ce
->ce_flags
&= ~CE_MATCHED
;
365 if (!opts
->ignore_skipworktree
&& ce_skip_worktree(ce
))
367 if (ce_path_match(&the_index
, ce
, &opts
->pathspec
, ps_matched
)) {
368 ce
->ce_flags
|= CE_MATCHED
;
369 if (opts
->source_tree
&& !(ce
->ce_flags
& CE_UPDATE
))
371 * In overlay mode, but the path is not in
372 * tree-ish, which means we should remove it
373 * from the index and the working tree.
375 ce
->ce_flags
|= CE_REMOVE
| CE_WT_REMOVE
;
379 static int checkout_worktree(const struct checkout_opts
*opts
,
380 const struct branch_info
*info
)
382 struct checkout state
= CHECKOUT_INIT
;
383 int nr_checkouts
= 0, nr_unmerged
= 0;
386 int pc_workers
, pc_threshold
;
387 struct mem_pool ce_mem_pool
;
390 state
.refresh_cache
= 1;
391 state
.istate
= &the_index
;
393 mem_pool_init(&ce_mem_pool
, 0);
394 get_parallel_checkout_configs(&pc_workers
, &pc_threshold
);
395 init_checkout_metadata(&state
.meta
, info
->refname
,
396 info
->commit
? &info
->commit
->object
.oid
: &info
->oid
,
399 enable_delayed_checkout(&state
);
402 init_parallel_checkout();
404 for (pos
= 0; pos
< the_index
.cache_nr
; pos
++) {
405 struct cache_entry
*ce
= the_index
.cache
[pos
];
406 if (ce
->ce_flags
& CE_MATCHED
) {
408 errs
|= checkout_entry(ce
, &state
,
409 NULL
, &nr_checkouts
);
412 if (opts
->writeout_stage
)
413 errs
|= checkout_stage(opts
->writeout_stage
,
416 &nr_checkouts
, opts
->overlay_mode
);
417 else if (opts
->merge
)
418 errs
|= checkout_merged(pos
, &state
,
421 pos
= skip_same_name(ce
, pos
) - 1;
425 errs
|= run_parallel_checkout(&state
, pc_workers
, pc_threshold
,
427 mem_pool_discard(&ce_mem_pool
, should_validate_cache_entries());
428 remove_marked_cache_entries(&the_index
, 1);
429 remove_scheduled_dirs();
430 errs
|= finish_delayed_checkout(&state
, opts
->show_progress
);
432 if (opts
->count_checkout_paths
) {
434 fprintf_ln(stderr
, Q_("Recreated %d merge conflict",
435 "Recreated %d merge conflicts",
438 if (opts
->source_tree
)
439 fprintf_ln(stderr
, Q_("Updated %d path from %s",
440 "Updated %d paths from %s",
443 repo_find_unique_abbrev(the_repository
, &opts
->source_tree
->object
.oid
,
445 else if (!nr_unmerged
|| nr_checkouts
)
446 fprintf_ln(stderr
, Q_("Updated %d path from the index",
447 "Updated %d paths from the index",
455 static int checkout_paths(const struct checkout_opts
*opts
,
456 const struct branch_info
*new_branch_info
)
459 static char *ps_matched
;
460 struct object_id rev
;
463 struct lock_file lock_file
= LOCK_INIT
;
466 trace2_cmd_mode(opts
->patch_mode
? "patch" : "path");
468 if (opts
->track
!= BRANCH_TRACK_UNSPECIFIED
)
469 die(_("'%s' cannot be used with updating paths"), "--track");
471 if (opts
->new_branch_log
)
472 die(_("'%s' cannot be used with updating paths"), "-l");
474 if (opts
->ignore_unmerged
&& opts
->patch_mode
)
475 die(_("'%s' cannot be used with updating paths"),
476 opts
->ignore_unmerged_opt
);
478 if (opts
->force_detach
)
479 die(_("'%s' cannot be used with updating paths"), "--detach");
481 if (opts
->merge
&& opts
->patch_mode
)
482 die(_("options '%s' and '%s' cannot be used together"), "--merge", "--patch");
484 if (opts
->ignore_unmerged
&& opts
->merge
)
485 die(_("options '%s' and '%s' cannot be used together"),
486 opts
->ignore_unmerged_opt
, "-m");
488 if (opts
->new_branch
)
489 die(_("Cannot update paths and switch to branch '%s' at the same time."),
492 if (!opts
->checkout_worktree
&& !opts
->checkout_index
)
493 die(_("neither '%s' or '%s' is specified"),
494 "--staged", "--worktree");
496 if (!opts
->checkout_worktree
&& !opts
->from_treeish
)
497 die(_("'%s' must be used when '%s' is not specified"),
498 "--worktree", "--source");
501 * Reject --staged option to the restore command when combined with
502 * merge-related options. Use the accept_ref flag to distinguish it
503 * from the checkout command, which does not accept --staged anyway.
505 * `restore --ours|--theirs --worktree --staged` could mean resolving
506 * conflicted paths to one side in both the worktree and the index,
507 * but does not currently.
509 * `restore --merge|--conflict=<style>` already recreates conflicts
510 * in both the worktree and the index, so adding --staged would be
513 if (!opts
->accept_ref
&& opts
->checkout_index
) {
514 if (opts
->writeout_stage
)
515 die(_("'%s' or '%s' cannot be used with %s"),
516 "--ours", "--theirs", "--staged");
519 die(_("'%s' or '%s' cannot be used with %s"),
520 "--merge", "--conflict", "--staged");
523 if (opts
->patch_mode
) {
524 enum add_p_mode patch_mode
;
525 const char *rev
= new_branch_info
->name
;
526 char rev_oid
[GIT_MAX_HEXSZ
+ 1];
529 * Since rev can be in the form of `<a>...<b>` (which is not
530 * recognized by diff-index), we will always replace the name
531 * with the hex of the commit (whether it's in `...` form or
532 * not) for the run_add_interactive() machinery to work
533 * properly. However, there is special logic for the HEAD case
534 * so we mustn't replace that. Also, when we were given a
535 * tree-object, new_branch_info->commit would be NULL, but we
536 * do not have to do any replacement, either.
538 if (rev
&& new_branch_info
->commit
&& strcmp(rev
, "HEAD"))
539 rev
= oid_to_hex_r(rev_oid
, &new_branch_info
->commit
->object
.oid
);
541 if (opts
->checkout_index
&& opts
->checkout_worktree
)
542 patch_mode
= ADD_P_CHECKOUT
;
543 else if (opts
->checkout_index
&& !opts
->checkout_worktree
)
544 patch_mode
= ADD_P_RESET
;
545 else if (!opts
->checkout_index
&& opts
->checkout_worktree
)
546 patch_mode
= ADD_P_WORKTREE
;
548 BUG("either flag must have been set, worktree=%d, index=%d",
549 opts
->checkout_worktree
, opts
->checkout_index
);
550 return !!run_add_p(the_repository
, patch_mode
, rev
,
554 repo_hold_locked_index(the_repository
, &lock_file
, LOCK_DIE_ON_ERROR
);
555 if (repo_read_index_preload(the_repository
, &opts
->pathspec
, 0) < 0)
556 return error(_("index file corrupt"));
558 if (opts
->source_tree
)
559 read_tree_some(opts
->source_tree
, &opts
->pathspec
);
561 ps_matched
= xcalloc(opts
->pathspec
.nr
, 1);
564 * Make sure all pathspecs participated in locating the paths
567 for (pos
= 0; pos
< the_index
.cache_nr
; pos
++)
568 if (opts
->overlay_mode
)
569 mark_ce_for_checkout_overlay(the_index
.cache
[pos
],
573 mark_ce_for_checkout_no_overlay(the_index
.cache
[pos
],
577 if (report_path_error(ps_matched
, &opts
->pathspec
)) {
583 /* "checkout -m path" to recreate conflicted state */
585 unmerge_marked_index(&the_index
);
587 /* Any unmerged paths? */
588 for (pos
= 0; pos
< the_index
.cache_nr
; pos
++) {
589 const struct cache_entry
*ce
= the_index
.cache
[pos
];
590 if (ce
->ce_flags
& CE_MATCHED
) {
593 if (opts
->ignore_unmerged
) {
595 warning(_("path '%s' is unmerged"), ce
->name
);
596 } else if (opts
->writeout_stage
) {
597 errs
|= check_stage(opts
->writeout_stage
, ce
, pos
, opts
->overlay_mode
);
598 } else if (opts
->merge
) {
599 errs
|= check_stages((1<<2) | (1<<3), ce
, pos
);
602 error(_("path '%s' is unmerged"), ce
->name
);
604 pos
= skip_same_name(ce
, pos
) - 1;
610 /* Now we are committed to check them out */
611 if (opts
->checkout_worktree
)
612 errs
|= checkout_worktree(opts
, new_branch_info
);
614 remove_marked_cache_entries(&the_index
, 1);
617 * Allow updating the index when checking out from the index.
618 * This is to save new stat info.
620 if (opts
->checkout_worktree
&& !opts
->checkout_index
&& !opts
->source_tree
)
623 checkout_index
= opts
->checkout_index
;
625 if (checkout_index
) {
626 if (write_locked_index(&the_index
, &lock_file
, COMMIT_LOCK
))
627 die(_("unable to write new index file"));
630 * NEEDSWORK: if --worktree is not specified, we
631 * should save stat info of checked out files in the
632 * index to avoid the next (potentially costly)
633 * refresh. But it's a bit tricker to do...
635 rollback_lock_file(&lock_file
);
638 read_ref_full("HEAD", 0, &rev
, NULL
);
639 head
= lookup_commit_reference_gently(the_repository
, &rev
, 1);
641 errs
|= post_checkout_hook(head
, head
, 0);
645 static void show_local_changes(struct object
*head
,
646 const struct diff_options
*opts
)
649 /* I think we want full paths, even if we're in a subdirectory. */
650 repo_init_revisions(the_repository
, &rev
, NULL
);
651 rev
.diffopt
.flags
= opts
->flags
;
652 rev
.diffopt
.output_format
|= DIFF_FORMAT_NAME_STATUS
;
653 rev
.diffopt
.flags
.recursive
= 1;
654 diff_setup_done(&rev
.diffopt
);
655 add_pending_object(&rev
, head
, NULL
);
656 run_diff_index(&rev
, 0);
657 release_revisions(&rev
);
660 static void describe_detached_head(const char *msg
, struct commit
*commit
)
662 struct strbuf sb
= STRBUF_INIT
;
664 if (!repo_parse_commit(the_repository
, commit
))
665 pp_commit_easy(CMIT_FMT_ONELINE
, commit
, &sb
);
666 if (print_sha1_ellipsis()) {
667 fprintf(stderr
, "%s %s... %s\n", msg
,
668 repo_find_unique_abbrev(the_repository
, &commit
->object
.oid
, DEFAULT_ABBREV
),
671 fprintf(stderr
, "%s %s %s\n", msg
,
672 repo_find_unique_abbrev(the_repository
, &commit
->object
.oid
, DEFAULT_ABBREV
),
678 static int reset_tree(struct tree
*tree
, const struct checkout_opts
*o
,
679 int worktree
, int *writeout_error
,
680 struct branch_info
*info
)
682 struct unpack_trees_options opts
;
683 struct tree_desc tree_desc
;
685 memset(&opts
, 0, sizeof(opts
));
687 opts
.update
= worktree
;
688 opts
.skip_unmerged
= !worktree
;
689 opts
.reset
= o
->force
? UNPACK_RESET_OVERWRITE_UNTRACKED
:
690 UNPACK_RESET_PROTECT_UNTRACKED
;
691 opts
.preserve_ignored
= (!o
->force
&& !o
->overwrite_ignore
);
693 opts
.fn
= oneway_merge
;
694 opts
.verbose_update
= o
->show_progress
;
695 opts
.src_index
= &the_index
;
696 opts
.dst_index
= &the_index
;
697 init_checkout_metadata(&opts
.meta
, info
->refname
,
698 info
->commit
? &info
->commit
->object
.oid
: null_oid(),
701 init_tree_desc(&tree_desc
, tree
->buffer
, tree
->size
);
702 switch (unpack_trees(1, &tree_desc
, &opts
)) {
706 * We return 0 nevertheless, as the index is all right
707 * and more importantly we have made best efforts to
708 * update paths in the work tree, and we cannot revert
719 static void setup_branch_path(struct branch_info
*branch
)
721 struct strbuf buf
= STRBUF_INIT
;
724 * If this is a ref, resolve it; otherwise, look up the OID for our
725 * expression. Failure here is okay.
727 if (!repo_dwim_ref(the_repository
, branch
->name
, strlen(branch
->name
),
728 &branch
->oid
, &branch
->refname
, 0))
729 repo_get_oid_committish(the_repository
, branch
->name
, &branch
->oid
);
731 strbuf_branchname(&buf
, branch
->name
, INTERPRET_BRANCH_LOCAL
);
732 if (strcmp(buf
.buf
, branch
->name
)) {
734 branch
->name
= xstrdup(buf
.buf
);
736 strbuf_splice(&buf
, 0, 0, "refs/heads/", 11);
738 branch
->path
= strbuf_detach(&buf
, NULL
);
741 static void init_topts(struct unpack_trees_options
*topts
, int merge
,
742 int show_progress
, int overwrite_ignore
,
743 struct commit
*old_commit
)
745 memset(topts
, 0, sizeof(*topts
));
746 topts
->head_idx
= -1;
747 topts
->src_index
= &the_index
;
748 topts
->dst_index
= &the_index
;
750 setup_unpack_trees_porcelain(topts
, "checkout");
752 topts
->initial_checkout
= is_index_unborn(&the_index
);
755 topts
->quiet
= merge
&& old_commit
;
756 topts
->verbose_update
= show_progress
;
757 topts
->fn
= twoway_merge
;
758 topts
->preserve_ignored
= !overwrite_ignore
;
761 static int merge_working_tree(const struct checkout_opts
*opts
,
762 struct branch_info
*old_branch_info
,
763 struct branch_info
*new_branch_info
,
767 struct lock_file lock_file
= LOCK_INIT
;
768 struct tree
*new_tree
;
770 repo_hold_locked_index(the_repository
, &lock_file
, LOCK_DIE_ON_ERROR
);
771 if (repo_read_index_preload(the_repository
, NULL
, 0) < 0)
772 return error(_("index file corrupt"));
774 resolve_undo_clear_index(&the_index
);
775 if (opts
->new_orphan_branch
&& opts
->orphan_from_empty_tree
) {
776 if (new_branch_info
->commit
)
777 BUG("'switch --orphan' should never accept a commit as starting point");
778 new_tree
= parse_tree_indirect(the_hash_algo
->empty_tree
);
780 new_tree
= repo_get_commit_tree(the_repository
,
781 new_branch_info
->commit
);
782 if (opts
->discard_changes
) {
783 ret
= reset_tree(new_tree
, opts
, 1, writeout_error
, new_branch_info
);
787 struct tree_desc trees
[2];
789 struct unpack_trees_options topts
;
790 const struct object_id
*old_commit_oid
;
792 refresh_index(&the_index
, REFRESH_QUIET
, NULL
, NULL
, NULL
);
794 if (unmerged_index(&the_index
)) {
795 error(_("you need to resolve your current index first"));
799 /* 2-way merge to the new branch */
800 init_topts(&topts
, opts
->merge
, opts
->show_progress
,
801 opts
->overwrite_ignore
, old_branch_info
->commit
);
802 init_checkout_metadata(&topts
.meta
, new_branch_info
->refname
,
803 new_branch_info
->commit
?
804 &new_branch_info
->commit
->object
.oid
:
805 &new_branch_info
->oid
, NULL
);
807 old_commit_oid
= old_branch_info
->commit
?
808 &old_branch_info
->commit
->object
.oid
:
809 the_hash_algo
->empty_tree
;
810 tree
= parse_tree_indirect(old_commit_oid
);
812 die(_("unable to parse commit %s"),
813 oid_to_hex(old_commit_oid
));
815 init_tree_desc(&trees
[0], tree
->buffer
, tree
->size
);
816 parse_tree(new_tree
);
818 init_tree_desc(&trees
[1], tree
->buffer
, tree
->size
);
820 ret
= unpack_trees(2, trees
, &topts
);
821 clear_unpack_trees_porcelain(&topts
);
824 * Unpack couldn't do a trivial merge; either
825 * give up or do a real merge, depending on
826 * whether the merge flag was used.
829 struct tree
*old_tree
;
830 struct merge_options o
;
831 struct strbuf sb
= STRBUF_INIT
;
832 struct strbuf old_commit_shortname
= STRBUF_INIT
;
838 * Without old_branch_info->commit, the below is the same as
839 * the two-tree unpack we already tried and failed.
841 if (!old_branch_info
->commit
)
843 old_tree
= repo_get_commit_tree(the_repository
,
844 old_branch_info
->commit
);
846 if (repo_index_has_changes(the_repository
, old_tree
, &sb
))
847 die(_("cannot continue with staged changes in "
848 "the following files:\n%s"), sb
.buf
);
851 /* Do more real merge */
854 * We update the index fully, then write the
855 * tree from the index, then merge the new
856 * branch with the current tree, with the old
857 * branch as the base. Then we reset the index
858 * (but not the working tree) to the new
859 * branch, leaving the working tree as the
860 * merged version, but skipping unmerged
861 * entries in the index.
864 add_files_to_cache(NULL
, NULL
, 0);
865 init_merge_options(&o
, the_repository
);
867 work
= write_in_core_index_as_tree(the_repository
);
869 ret
= reset_tree(new_tree
,
871 writeout_error
, new_branch_info
);
874 o
.ancestor
= old_branch_info
->name
;
875 if (!old_branch_info
->name
) {
876 strbuf_add_unique_abbrev(&old_commit_shortname
,
877 &old_branch_info
->commit
->object
.oid
,
879 o
.ancestor
= old_commit_shortname
.buf
;
881 o
.branch1
= new_branch_info
->name
;
883 ret
= merge_trees(&o
,
889 ret
= reset_tree(new_tree
,
891 writeout_error
, new_branch_info
);
892 strbuf_release(&o
.obuf
);
893 strbuf_release(&old_commit_shortname
);
899 if (!cache_tree_fully_valid(the_index
.cache_tree
))
900 cache_tree_update(&the_index
, WRITE_TREE_SILENT
| WRITE_TREE_REPAIR
);
902 if (write_locked_index(&the_index
, &lock_file
, COMMIT_LOCK
))
903 die(_("unable to write new index file"));
905 if (!opts
->discard_changes
&& !opts
->quiet
&& new_branch_info
->commit
)
906 show_local_changes(&new_branch_info
->commit
->object
, &opts
->diff_options
);
911 static void report_tracking(struct branch_info
*new_branch_info
)
913 struct strbuf sb
= STRBUF_INIT
;
914 struct branch
*branch
= branch_get(new_branch_info
->name
);
916 if (!format_tracking_info(branch
, &sb
, AHEAD_BEHIND_FULL
))
918 fputs(sb
.buf
, stdout
);
922 static void update_refs_for_switch(const struct checkout_opts
*opts
,
923 struct branch_info
*old_branch_info
,
924 struct branch_info
*new_branch_info
)
926 struct strbuf msg
= STRBUF_INIT
;
927 const char *old_desc
, *reflog_msg
;
928 if (opts
->new_branch
) {
929 if (opts
->new_orphan_branch
) {
932 refname
= mkpathdup("refs/heads/%s", opts
->new_orphan_branch
);
933 if (opts
->new_branch_log
&&
934 !should_autocreate_reflog(refname
)) {
936 struct strbuf err
= STRBUF_INIT
;
938 ret
= safe_create_reflog(refname
, &err
);
940 fprintf(stderr
, _("Can not do reflog for '%s': %s\n"),
941 opts
->new_orphan_branch
, err
.buf
);
942 strbuf_release(&err
);
946 strbuf_release(&err
);
951 create_branch(the_repository
,
952 opts
->new_branch
, new_branch_info
->name
,
953 opts
->new_branch_force
? 1 : 0,
954 opts
->new_branch_force
? 1 : 0,
955 opts
->new_branch_log
,
959 free(new_branch_info
->name
);
960 free(new_branch_info
->refname
);
961 new_branch_info
->name
= xstrdup(opts
->new_branch
);
962 setup_branch_path(new_branch_info
);
965 old_desc
= old_branch_info
->name
;
966 if (!old_desc
&& old_branch_info
->commit
)
967 old_desc
= oid_to_hex(&old_branch_info
->commit
->object
.oid
);
969 reflog_msg
= getenv("GIT_REFLOG_ACTION");
971 strbuf_addf(&msg
, "checkout: moving from %s to %s",
972 old_desc
? old_desc
: "(invalid)", new_branch_info
->name
);
974 strbuf_insertstr(&msg
, 0, reflog_msg
);
976 if (!strcmp(new_branch_info
->name
, "HEAD") && !new_branch_info
->path
&& !opts
->force_detach
) {
978 } else if (opts
->force_detach
|| !new_branch_info
->path
) { /* No longer on any branch. */
979 update_ref(msg
.buf
, "HEAD", &new_branch_info
->commit
->object
.oid
, NULL
,
980 REF_NO_DEREF
, UPDATE_REFS_DIE_ON_ERR
);
982 if (old_branch_info
->path
&&
983 advice_enabled(ADVICE_DETACHED_HEAD
) && !opts
->force_detach
)
984 detach_advice(new_branch_info
->name
);
985 describe_detached_head(_("HEAD is now at"), new_branch_info
->commit
);
987 } else if (new_branch_info
->path
) { /* Switch branches. */
988 if (create_symref("HEAD", new_branch_info
->path
, msg
.buf
) < 0)
989 die(_("unable to update HEAD"));
991 if (old_branch_info
->path
&& !strcmp(new_branch_info
->path
, old_branch_info
->path
)) {
992 if (opts
->new_branch_force
)
993 fprintf(stderr
, _("Reset branch '%s'\n"),
994 new_branch_info
->name
);
996 fprintf(stderr
, _("Already on '%s'\n"),
997 new_branch_info
->name
);
998 } else if (opts
->new_branch
) {
999 if (opts
->branch_exists
)
1000 fprintf(stderr
, _("Switched to and reset branch '%s'\n"), new_branch_info
->name
);
1002 fprintf(stderr
, _("Switched to a new branch '%s'\n"), new_branch_info
->name
);
1004 fprintf(stderr
, _("Switched to branch '%s'\n"),
1005 new_branch_info
->name
);
1008 if (old_branch_info
->path
&& old_branch_info
->name
) {
1009 if (!ref_exists(old_branch_info
->path
) && reflog_exists(old_branch_info
->path
))
1010 delete_reflog(old_branch_info
->path
);
1013 remove_branch_state(the_repository
, !opts
->quiet
);
1014 strbuf_release(&msg
);
1016 (new_branch_info
->path
|| (!opts
->force_detach
&& !strcmp(new_branch_info
->name
, "HEAD"))))
1017 report_tracking(new_branch_info
);
1020 static int add_pending_uninteresting_ref(const char *refname
,
1021 const struct object_id
*oid
,
1022 int flags UNUSED
, void *cb_data
)
1024 add_pending_oid(cb_data
, refname
, oid
, UNINTERESTING
);
1028 static void describe_one_orphan(struct strbuf
*sb
, struct commit
*commit
)
1030 strbuf_addstr(sb
, " ");
1031 strbuf_add_unique_abbrev(sb
, &commit
->object
.oid
, DEFAULT_ABBREV
);
1032 strbuf_addch(sb
, ' ');
1033 if (!repo_parse_commit(the_repository
, commit
))
1034 pp_commit_easy(CMIT_FMT_ONELINE
, commit
, sb
);
1035 strbuf_addch(sb
, '\n');
1038 #define ORPHAN_CUTOFF 4
1039 static void suggest_reattach(struct commit
*commit
, struct rev_info
*revs
)
1041 struct commit
*c
, *last
= NULL
;
1042 struct strbuf sb
= STRBUF_INIT
;
1044 while ((c
= get_revision(revs
)) != NULL
) {
1045 if (lost
< ORPHAN_CUTOFF
)
1046 describe_one_orphan(&sb
, c
);
1050 if (ORPHAN_CUTOFF
< lost
) {
1051 int more
= lost
- ORPHAN_CUTOFF
;
1053 describe_one_orphan(&sb
, last
);
1055 strbuf_addf(&sb
, _(" ... and %d more.\n"), more
);
1060 /* The singular version */
1061 "Warning: you are leaving %d commit behind, "
1062 "not connected to\n"
1063 "any of your branches:\n\n"
1065 /* The plural version */
1066 "Warning: you are leaving %d commits behind, "
1067 "not connected to\n"
1068 "any of your branches:\n\n"
1070 /* Give ngettext() the count */
1074 strbuf_release(&sb
);
1076 if (advice_enabled(ADVICE_DETACHED_HEAD
))
1079 /* The singular version */
1080 "If you want to keep it by creating a new branch, "
1081 "this may be a good time\nto do so with:\n\n"
1082 " git branch <new-branch-name> %s\n\n",
1083 /* The plural version */
1084 "If you want to keep them by creating a new branch, "
1085 "this may be a good time\nto do so with:\n\n"
1086 " git branch <new-branch-name> %s\n\n",
1087 /* Give ngettext() the count */
1089 repo_find_unique_abbrev(the_repository
, &commit
->object
.oid
, DEFAULT_ABBREV
));
1093 * We are about to leave commit that was at the tip of a detached
1094 * HEAD. If it is not reachable from any ref, this is the last chance
1095 * for the user to do so without resorting to reflog.
1097 static void orphaned_commit_warning(struct commit
*old_commit
, struct commit
*new_commit
)
1099 struct rev_info revs
;
1100 struct object
*object
= &old_commit
->object
;
1102 repo_init_revisions(the_repository
, &revs
, NULL
);
1103 setup_revisions(0, NULL
, &revs
, NULL
);
1105 object
->flags
&= ~UNINTERESTING
;
1106 add_pending_object(&revs
, object
, oid_to_hex(&object
->oid
));
1108 for_each_ref(add_pending_uninteresting_ref
, &revs
);
1110 add_pending_oid(&revs
, "HEAD",
1111 &new_commit
->object
.oid
,
1114 if (prepare_revision_walk(&revs
))
1115 die(_("internal error in revision walk"));
1116 if (!(old_commit
->object
.flags
& UNINTERESTING
))
1117 suggest_reattach(old_commit
, &revs
);
1119 describe_detached_head(_("Previous HEAD position was"), old_commit
);
1121 /* Clean up objects used, as they will be reused. */
1122 repo_clear_commit_marks(the_repository
, ALL_REV_FLAGS
);
1123 release_revisions(&revs
);
1126 static int switch_branches(const struct checkout_opts
*opts
,
1127 struct branch_info
*new_branch_info
)
1130 struct branch_info old_branch_info
= { 0 };
1131 struct object_id rev
;
1132 int flag
, writeout_error
= 0;
1135 trace2_cmd_mode("branch");
1137 memset(&old_branch_info
, 0, sizeof(old_branch_info
));
1138 old_branch_info
.path
= resolve_refdup("HEAD", 0, &rev
, &flag
);
1139 if (old_branch_info
.path
)
1140 old_branch_info
.commit
= lookup_commit_reference_gently(the_repository
, &rev
, 1);
1141 if (!(flag
& REF_ISSYMREF
))
1142 FREE_AND_NULL(old_branch_info
.path
);
1144 if (old_branch_info
.path
) {
1145 const char *const prefix
= "refs/heads/";
1147 if (skip_prefix(old_branch_info
.path
, prefix
, &p
))
1148 old_branch_info
.name
= xstrdup(p
);
1151 if (opts
->new_orphan_branch
&& opts
->orphan_from_empty_tree
) {
1152 if (new_branch_info
->name
)
1153 BUG("'switch --orphan' should never accept a commit as starting point");
1154 new_branch_info
->commit
= NULL
;
1155 new_branch_info
->name
= xstrdup("(empty)");
1159 if (!new_branch_info
->name
) {
1160 new_branch_info
->name
= xstrdup("HEAD");
1161 new_branch_info
->commit
= old_branch_info
.commit
;
1162 if (!new_branch_info
->commit
)
1163 die(_("You are on a branch yet to be born"));
1164 parse_commit_or_die(new_branch_info
->commit
);
1166 if (opts
->only_merge_on_switching_branches
)
1171 ret
= merge_working_tree(opts
, &old_branch_info
, new_branch_info
, &writeout_error
);
1173 branch_info_release(&old_branch_info
);
1178 if (!opts
->quiet
&& !old_branch_info
.path
&& old_branch_info
.commit
&& new_branch_info
->commit
!= old_branch_info
.commit
)
1179 orphaned_commit_warning(old_branch_info
.commit
, new_branch_info
->commit
);
1181 update_refs_for_switch(opts
, &old_branch_info
, new_branch_info
);
1183 ret
= post_checkout_hook(old_branch_info
.commit
, new_branch_info
->commit
, 1);
1184 branch_info_release(&old_branch_info
);
1186 return ret
|| writeout_error
;
1189 static int git_checkout_config(const char *var
, const char *value
, void *cb
)
1191 struct checkout_opts
*opts
= cb
;
1193 if (!strcmp(var
, "diff.ignoresubmodules")) {
1194 handle_ignore_submodules_arg(&opts
->diff_options
, value
);
1197 if (!strcmp(var
, "checkout.guess")) {
1198 opts
->dwim_new_local_branch
= git_config_bool(var
, value
);
1202 if (starts_with(var
, "submodule."))
1203 return git_default_submodule_config(var
, value
, NULL
);
1205 return git_xmerge_config(var
, value
, NULL
);
1208 static void setup_new_branch_info_and_source_tree(
1209 struct branch_info
*new_branch_info
,
1210 struct checkout_opts
*opts
,
1211 struct object_id
*rev
,
1214 struct tree
**source_tree
= &opts
->source_tree
;
1215 struct object_id branch_rev
;
1217 new_branch_info
->name
= xstrdup(arg
);
1218 setup_branch_path(new_branch_info
);
1220 if (!check_refname_format(new_branch_info
->path
, 0) &&
1221 !read_ref(new_branch_info
->path
, &branch_rev
))
1222 oidcpy(rev
, &branch_rev
);
1224 /* not an existing branch */
1225 FREE_AND_NULL(new_branch_info
->path
);
1227 new_branch_info
->commit
= lookup_commit_reference_gently(the_repository
, rev
, 1);
1228 if (!new_branch_info
->commit
) {
1230 *source_tree
= parse_tree_indirect(rev
);
1232 parse_commit_or_die(new_branch_info
->commit
);
1233 *source_tree
= repo_get_commit_tree(the_repository
,
1234 new_branch_info
->commit
);
1238 static const char *parse_remote_branch(const char *arg
,
1239 struct object_id
*rev
,
1240 int could_be_checkout_paths
)
1242 int num_matches
= 0;
1243 const char *remote
= unique_tracking_name(arg
, rev
, &num_matches
);
1245 if (remote
&& could_be_checkout_paths
) {
1246 die(_("'%s' could be both a local file and a tracking branch.\n"
1247 "Please use -- (and optionally --no-guess) to disambiguate"),
1251 if (!remote
&& num_matches
> 1) {
1252 if (advice_enabled(ADVICE_CHECKOUT_AMBIGUOUS_REMOTE_BRANCH_NAME
)) {
1253 advise(_("If you meant to check out a remote tracking branch on, e.g. 'origin',\n"
1254 "you can do so by fully qualifying the name with the --track option:\n"
1256 " git checkout --track origin/<name>\n"
1258 "If you'd like to always have checkouts of an ambiguous <name> prefer\n"
1259 "one remote, e.g. the 'origin' remote, consider setting\n"
1260 "checkout.defaultRemote=origin in your config."));
1263 die(_("'%s' matched multiple (%d) remote tracking branches"),
1270 static int parse_branchname_arg(int argc
, const char **argv
,
1271 int dwim_new_local_branch_ok
,
1272 struct branch_info
*new_branch_info
,
1273 struct checkout_opts
*opts
,
1274 struct object_id
*rev
)
1276 const char **new_branch
= &opts
->new_branch
;
1280 int has_dash_dash
= 0;
1284 * case 1: git checkout <ref> -- [<paths>]
1286 * <ref> must be a valid tree, everything after the '--' must be
1289 * case 2: git checkout -- [<paths>]
1291 * everything after the '--' must be paths.
1293 * case 3: git checkout <something> [--]
1295 * (a) If <something> is a commit, that is to
1296 * switch to the branch or detach HEAD at it. As a special case,
1297 * if <something> is A...B (missing A or B means HEAD but you can
1298 * omit at most one side), and if there is a unique merge base
1299 * between A and B, A...B names that merge base.
1301 * (b) If <something> is _not_ a commit, either "--" is present
1302 * or <something> is not a path, no -t or -b was given,
1303 * and there is a tracking branch whose name is <something>
1304 * in one and only one remote (or if the branch exists on the
1305 * remote named in checkout.defaultRemote), then this is a
1306 * short-hand to fork local <something> from that
1307 * remote-tracking branch.
1309 * (c) Otherwise, if "--" is present, treat it like case (1).
1312 * - if it's a reference, treat it like case (1)
1313 * - else if it's a path, treat it like case (2)
1316 * case 4: git checkout <something> <paths>
1318 * The first argument must not be ambiguous.
1319 * - If it's *only* a reference, treat it like case (1).
1320 * - If it's only a path, treat it like case (2).
1327 if (!opts
->accept_pathspec
) {
1329 die(_("only one reference expected"));
1330 has_dash_dash
= 1; /* helps disambiguate */
1335 for (i
= 0; i
< argc
; i
++) {
1336 if (opts
->accept_pathspec
&& !strcmp(argv
[i
], "--")) {
1341 if (dash_dash_pos
== 0)
1342 return 1; /* case (2) */
1343 else if (dash_dash_pos
== 1)
1344 has_dash_dash
= 1; /* case (3) or (1) */
1345 else if (dash_dash_pos
>= 2)
1346 die(_("only one reference expected, %d given."), dash_dash_pos
);
1347 opts
->count_checkout_paths
= !opts
->quiet
&& !has_dash_dash
;
1349 if (!strcmp(arg
, "-"))
1352 if (repo_get_oid_mb(the_repository
, arg
, rev
)) {
1354 * Either case (3) or (4), with <something> not being
1355 * a commit, or an attempt to use case (1) with an
1358 * It's likely an error, but we need to find out if
1359 * we should auto-create the branch, case (3).(b).
1361 int recover_with_dwim
= dwim_new_local_branch_ok
;
1363 int could_be_checkout_paths
= !has_dash_dash
&&
1364 check_filename(opts
->prefix
, arg
);
1366 if (!has_dash_dash
&& !no_wildcard(arg
))
1367 recover_with_dwim
= 0;
1370 * Accept "git checkout foo", "git checkout foo --"
1371 * and "git switch foo" as candidates for dwim.
1373 if (!(argc
== 1 && !has_dash_dash
) &&
1374 !(argc
== 2 && has_dash_dash
) &&
1375 opts
->accept_pathspec
)
1376 recover_with_dwim
= 0;
1378 if (recover_with_dwim
) {
1379 const char *remote
= parse_remote_branch(arg
, rev
,
1380 could_be_checkout_paths
);
1384 /* DWIMmed to create local branch, case (3).(b) */
1386 recover_with_dwim
= 0;
1390 if (!recover_with_dwim
) {
1392 die(_("invalid reference: %s"), arg
);
1397 /* we can't end up being in (2) anymore, eat the argument */
1402 setup_new_branch_info_and_source_tree(new_branch_info
, opts
, rev
, arg
);
1404 if (!opts
->source_tree
) /* case (1): want a tree */
1405 die(_("reference is not a tree: %s"), arg
);
1407 if (!has_dash_dash
) { /* case (3).(d) -> (1) */
1409 * Do not complain the most common case
1410 * git checkout branch
1411 * even if there happen to be a file called 'branch';
1412 * it would be extremely annoying.
1415 verify_non_filename(opts
->prefix
, arg
);
1416 } else if (opts
->accept_pathspec
) {
1425 static int switch_unborn_to_new_branch(const struct checkout_opts
*opts
)
1428 struct strbuf branch_ref
= STRBUF_INIT
;
1430 trace2_cmd_mode("unborn");
1432 if (!opts
->new_branch
)
1433 die(_("You are on a branch yet to be born"));
1434 strbuf_addf(&branch_ref
, "refs/heads/%s", opts
->new_branch
);
1435 status
= create_symref("HEAD", branch_ref
.buf
, "checkout -b");
1436 strbuf_release(&branch_ref
);
1438 fprintf(stderr
, _("Switched to a new branch '%s'\n"),
1443 static void die_expecting_a_branch(const struct branch_info
*branch_info
)
1445 struct object_id oid
;
1449 if (repo_dwim_ref(the_repository
, branch_info
->name
,
1450 strlen(branch_info
->name
), &oid
, &to_free
, 0) == 1) {
1451 const char *ref
= to_free
;
1453 if (skip_prefix(ref
, "refs/tags/", &ref
))
1454 code
= die_message(_("a branch is expected, got tag '%s'"), ref
);
1455 else if (skip_prefix(ref
, "refs/remotes/", &ref
))
1456 code
= die_message(_("a branch is expected, got remote branch '%s'"), ref
);
1458 code
= die_message(_("a branch is expected, got '%s'"), ref
);
1460 else if (branch_info
->commit
)
1461 code
= die_message(_("a branch is expected, got commit '%s'"), branch_info
->name
);
1464 * This case should never happen because we already die() on
1465 * non-commit, but just in case.
1467 code
= die_message(_("a branch is expected, got '%s'"), branch_info
->name
);
1469 if (advice_enabled(ADVICE_SUGGEST_DETACHING_HEAD
))
1470 advise(_("If you want to detach HEAD at the commit, try again with the --detach option."));
1475 static void die_if_some_operation_in_progress(void)
1477 struct wt_status_state state
;
1479 memset(&state
, 0, sizeof(state
));
1480 wt_status_get_state(the_repository
, &state
, 0);
1482 if (state
.merge_in_progress
)
1483 die(_("cannot switch branch while merging\n"
1484 "Consider \"git merge --quit\" "
1485 "or \"git worktree add\"."));
1486 if (state
.am_in_progress
)
1487 die(_("cannot switch branch in the middle of an am session\n"
1488 "Consider \"git am --quit\" "
1489 "or \"git worktree add\"."));
1490 if (state
.rebase_interactive_in_progress
|| state
.rebase_in_progress
)
1491 die(_("cannot switch branch while rebasing\n"
1492 "Consider \"git rebase --quit\" "
1493 "or \"git worktree add\"."));
1494 if (state
.cherry_pick_in_progress
)
1495 die(_("cannot switch branch while cherry-picking\n"
1496 "Consider \"git cherry-pick --quit\" "
1497 "or \"git worktree add\"."));
1498 if (state
.revert_in_progress
)
1499 die(_("cannot switch branch while reverting\n"
1500 "Consider \"git revert --quit\" "
1501 "or \"git worktree add\"."));
1502 if (state
.bisect_in_progress
)
1503 warning(_("you are switching branch while bisecting"));
1505 wt_status_state_free_buffers(&state
);
1508 static int checkout_branch(struct checkout_opts
*opts
,
1509 struct branch_info
*new_branch_info
)
1511 if (opts
->pathspec
.nr
)
1512 die(_("paths cannot be used with switching branches"));
1514 if (opts
->patch_mode
)
1515 die(_("'%s' cannot be used with switching branches"),
1518 if (opts
->overlay_mode
!= -1)
1519 die(_("'%s' cannot be used with switching branches"),
1522 if (opts
->writeout_stage
)
1523 die(_("'%s' cannot be used with switching branches"),
1526 if (opts
->force
&& opts
->merge
)
1527 die(_("'%s' cannot be used with '%s'"), "-f", "-m");
1529 if (opts
->discard_changes
&& opts
->merge
)
1530 die(_("'%s' cannot be used with '%s'"), "--discard-changes", "--merge");
1532 if (opts
->force_detach
&& opts
->new_branch
)
1533 die(_("'%s' cannot be used with '%s'"),
1534 "--detach", "-b/-B/--orphan");
1536 if (opts
->new_orphan_branch
) {
1537 if (opts
->track
!= BRANCH_TRACK_UNSPECIFIED
)
1538 die(_("'%s' cannot be used with '%s'"), "--orphan", "-t");
1539 if (opts
->orphan_from_empty_tree
&& new_branch_info
->name
)
1540 die(_("'%s' cannot take <start-point>"), "--orphan");
1541 } else if (opts
->force_detach
) {
1542 if (opts
->track
!= BRANCH_TRACK_UNSPECIFIED
)
1543 die(_("'%s' cannot be used with '%s'"), "--detach", "-t");
1544 } else if (opts
->track
== BRANCH_TRACK_UNSPECIFIED
)
1545 opts
->track
= git_branch_track
;
1547 if (new_branch_info
->name
&& !new_branch_info
->commit
)
1548 die(_("Cannot switch branch to a non-commit '%s'"),
1549 new_branch_info
->name
);
1551 if (!opts
->switch_branch_doing_nothing_is_ok
&&
1552 !new_branch_info
->name
&&
1553 !opts
->new_branch
&&
1554 !opts
->force_detach
)
1555 die(_("missing branch or commit argument"));
1557 if (!opts
->implicit_detach
&&
1558 !opts
->force_detach
&&
1559 !opts
->new_branch
&&
1560 !opts
->new_branch_force
&&
1561 new_branch_info
->name
&&
1562 !new_branch_info
->path
)
1563 die_expecting_a_branch(new_branch_info
);
1565 if (!opts
->can_switch_when_in_progress
)
1566 die_if_some_operation_in_progress();
1568 if (new_branch_info
->path
&& !opts
->force_detach
&& !opts
->new_branch
&&
1569 !opts
->ignore_other_worktrees
) {
1571 char *head_ref
= resolve_refdup("HEAD", 0, NULL
, &flag
);
1573 (!(flag
& REF_ISSYMREF
) || strcmp(head_ref
, new_branch_info
->path
)))
1574 die_if_checked_out(new_branch_info
->path
, 1);
1578 if (!new_branch_info
->commit
&& opts
->new_branch
) {
1579 struct object_id rev
;
1582 if (!read_ref_full("HEAD", 0, &rev
, &flag
) &&
1583 (flag
& REF_ISSYMREF
) && is_null_oid(&rev
))
1584 return switch_unborn_to_new_branch(opts
);
1586 return switch_branches(opts
, new_branch_info
);
1589 static struct option
*add_common_options(struct checkout_opts
*opts
,
1590 struct option
*prevopts
)
1592 struct option options
[] = {
1593 OPT__QUIET(&opts
->quiet
, N_("suppress progress reporting")),
1594 OPT_CALLBACK_F(0, "recurse-submodules", NULL
,
1595 "checkout", "control recursive updating of submodules",
1596 PARSE_OPT_OPTARG
, option_parse_recurse_submodules_worktree_updater
),
1597 OPT_BOOL(0, "progress", &opts
->show_progress
, N_("force progress reporting")),
1598 OPT_BOOL('m', "merge", &opts
->merge
, N_("perform a 3-way merge with the new branch")),
1599 OPT_STRING(0, "conflict", &opts
->conflict_style
, N_("style"),
1600 N_("conflict style (merge, diff3, or zdiff3)")),
1603 struct option
*newopts
= parse_options_concat(prevopts
, options
);
1608 static struct option
*add_common_switch_branch_options(
1609 struct checkout_opts
*opts
, struct option
*prevopts
)
1611 struct option options
[] = {
1612 OPT_BOOL('d', "detach", &opts
->force_detach
, N_("detach HEAD at named commit")),
1613 OPT_CALLBACK_F('t', "track", &opts
->track
, "(direct|inherit)",
1614 N_("set branch tracking configuration"),
1616 parse_opt_tracking_mode
),
1617 OPT__FORCE(&opts
->force
, N_("force checkout (throw away local modifications)"),
1618 PARSE_OPT_NOCOMPLETE
),
1619 OPT_STRING(0, "orphan", &opts
->new_orphan_branch
, N_("new-branch"), N_("new unparented branch")),
1620 OPT_BOOL_F(0, "overwrite-ignore", &opts
->overwrite_ignore
,
1621 N_("update ignored files (default)"),
1622 PARSE_OPT_NOCOMPLETE
),
1623 OPT_BOOL(0, "ignore-other-worktrees", &opts
->ignore_other_worktrees
,
1624 N_("do not check if another worktree is holding the given ref")),
1627 struct option
*newopts
= parse_options_concat(prevopts
, options
);
1632 static struct option
*add_checkout_path_options(struct checkout_opts
*opts
,
1633 struct option
*prevopts
)
1635 struct option options
[] = {
1636 OPT_SET_INT_F('2', "ours", &opts
->writeout_stage
,
1637 N_("checkout our version for unmerged files"),
1638 2, PARSE_OPT_NONEG
),
1639 OPT_SET_INT_F('3', "theirs", &opts
->writeout_stage
,
1640 N_("checkout their version for unmerged files"),
1641 3, PARSE_OPT_NONEG
),
1642 OPT_BOOL('p', "patch", &opts
->patch_mode
, N_("select hunks interactively")),
1643 OPT_BOOL(0, "ignore-skip-worktree-bits", &opts
->ignore_skipworktree
,
1644 N_("do not limit pathspecs to sparse entries only")),
1645 OPT_PATHSPEC_FROM_FILE(&opts
->pathspec_from_file
),
1646 OPT_PATHSPEC_FILE_NUL(&opts
->pathspec_file_nul
),
1649 struct option
*newopts
= parse_options_concat(prevopts
, options
);
1654 /* create-branch option (either b or c) */
1655 static char cb_option
= 'b';
1657 static int checkout_main(int argc
, const char **argv
, const char *prefix
,
1658 struct checkout_opts
*opts
, struct option
*options
,
1659 const char * const usagestr
[],
1660 struct branch_info
*new_branch_info
)
1662 int parseopt_flags
= 0;
1664 opts
->overwrite_ignore
= 1;
1665 opts
->prefix
= prefix
;
1666 opts
->show_progress
= -1;
1668 git_config(git_checkout_config
, opts
);
1669 if (the_repository
->gitdir
) {
1670 prepare_repo_settings(the_repository
);
1671 the_repository
->settings
.command_requires_full_index
= 0;
1674 opts
->track
= BRANCH_TRACK_UNSPECIFIED
;
1676 if (!opts
->accept_pathspec
&& !opts
->accept_ref
)
1677 BUG("make up your mind, you need to take _something_");
1678 if (opts
->accept_pathspec
&& opts
->accept_ref
)
1679 parseopt_flags
= PARSE_OPT_KEEP_DASHDASH
;
1681 argc
= parse_options(argc
, argv
, prefix
, options
,
1682 usagestr
, parseopt_flags
);
1684 if (opts
->show_progress
< 0) {
1686 opts
->show_progress
= 0;
1688 opts
->show_progress
= isatty(2);
1691 if (opts
->conflict_style
) {
1692 opts
->merge
= 1; /* implied */
1693 git_xmerge_config("merge.conflictstyle", opts
->conflict_style
, NULL
);
1696 opts
->discard_changes
= 1;
1697 opts
->ignore_unmerged_opt
= "--force";
1698 opts
->ignore_unmerged
= 1;
1701 if ((!!opts
->new_branch
+ !!opts
->new_branch_force
+ !!opts
->new_orphan_branch
) > 1)
1702 die(_("options '-%c', '-%c', and '%s' cannot be used together"),
1703 cb_option
, toupper(cb_option
), "--orphan");
1705 if (opts
->overlay_mode
== 1 && opts
->patch_mode
)
1706 die(_("options '%s' and '%s' cannot be used together"), "-p", "--overlay");
1708 if (opts
->checkout_index
>= 0 || opts
->checkout_worktree
>= 0) {
1709 if (opts
->checkout_index
< 0)
1710 opts
->checkout_index
= 0;
1711 if (opts
->checkout_worktree
< 0)
1712 opts
->checkout_worktree
= 0;
1714 if (opts
->checkout_index
< 0)
1715 opts
->checkout_index
= -opts
->checkout_index
- 1;
1716 if (opts
->checkout_worktree
< 0)
1717 opts
->checkout_worktree
= -opts
->checkout_worktree
- 1;
1719 if (opts
->checkout_index
< 0 || opts
->checkout_worktree
< 0)
1720 BUG("these flags should be non-negative by now");
1722 * convenient shortcut: "git restore --staged [--worktree]" equals
1723 * "git restore --staged [--worktree] --source HEAD"
1725 if (!opts
->from_treeish
&& opts
->checkout_index
)
1726 opts
->from_treeish
= "HEAD";
1729 * From here on, new_branch will contain the branch to be checked out,
1730 * and new_branch_force and new_orphan_branch will tell us which one of
1731 * -b/-B/-c/-C/--orphan is being used.
1733 if (opts
->new_branch_force
)
1734 opts
->new_branch
= opts
->new_branch_force
;
1736 if (opts
->new_orphan_branch
)
1737 opts
->new_branch
= opts
->new_orphan_branch
;
1739 /* --track without -c/-C/-b/-B/--orphan should DWIM */
1740 if (opts
->track
!= BRANCH_TRACK_UNSPECIFIED
&& !opts
->new_branch
) {
1741 const char *argv0
= argv
[0];
1742 if (!argc
|| !strcmp(argv0
, "--"))
1743 die(_("--track needs a branch name"));
1744 skip_prefix(argv0
, "refs/", &argv0
);
1745 skip_prefix(argv0
, "remotes/", &argv0
);
1746 argv0
= strchr(argv0
, '/');
1747 if (!argv0
|| !argv0
[1])
1748 die(_("missing branch name; try -%c"), cb_option
);
1749 opts
->new_branch
= argv0
+ 1;
1753 * Extract branch name from command line arguments, so
1754 * all that is left is pathspecs.
1758 * 1) git checkout <tree> -- [<paths>]
1759 * 2) git checkout -- [<paths>]
1760 * 3) git checkout <something> [<paths>]
1762 * including "last branch" syntax and DWIM-ery for names of
1763 * remote branches, erroring out for invalid or ambiguous cases.
1765 if (argc
&& opts
->accept_ref
) {
1766 struct object_id rev
;
1768 !opts
->patch_mode
&&
1769 opts
->dwim_new_local_branch
&&
1770 opts
->track
== BRANCH_TRACK_UNSPECIFIED
&&
1772 int n
= parse_branchname_arg(argc
, argv
, dwim_ok
,
1773 new_branch_info
, opts
, &rev
);
1776 } else if (!opts
->accept_ref
&& opts
->from_treeish
) {
1777 struct object_id rev
;
1779 if (repo_get_oid_mb(the_repository
, opts
->from_treeish
, &rev
))
1780 die(_("could not resolve %s"), opts
->from_treeish
);
1782 setup_new_branch_info_and_source_tree(new_branch_info
,
1784 opts
->from_treeish
);
1786 if (!opts
->source_tree
)
1787 die(_("reference is not a tree: %s"), opts
->from_treeish
);
1791 parse_pathspec(&opts
->pathspec
, 0,
1792 opts
->patch_mode
? PATHSPEC_PREFIX_ORIGIN
: 0,
1795 if (!opts
->pathspec
.nr
)
1796 die(_("invalid path specification"));
1799 * Try to give more helpful suggestion.
1800 * new_branch && argc > 1 will be caught later.
1802 if (opts
->new_branch
&& argc
== 1 && !new_branch_info
->commit
)
1803 die(_("'%s' is not a commit and a branch '%s' cannot be created from it"),
1804 argv
[0], opts
->new_branch
);
1806 if (opts
->force_detach
)
1807 die(_("git checkout: --detach does not take a path argument '%s'"),
1811 if (opts
->pathspec_from_file
) {
1812 if (opts
->pathspec
.nr
)
1813 die(_("'%s' and pathspec arguments cannot be used together"), "--pathspec-from-file");
1815 if (opts
->force_detach
)
1816 die(_("options '%s' and '%s' cannot be used together"), "--pathspec-from-file", "--detach");
1818 if (opts
->patch_mode
)
1819 die(_("options '%s' and '%s' cannot be used together"), "--pathspec-from-file", "--patch");
1821 parse_pathspec_file(&opts
->pathspec
, 0,
1823 prefix
, opts
->pathspec_from_file
, opts
->pathspec_file_nul
);
1824 } else if (opts
->pathspec_file_nul
) {
1825 die(_("the option '%s' requires '%s'"), "--pathspec-file-nul", "--pathspec-from-file");
1828 opts
->pathspec
.recursive
= 1;
1830 if (opts
->pathspec
.nr
) {
1831 if (1 < !!opts
->writeout_stage
+ !!opts
->force
+ !!opts
->merge
)
1832 die(_("git checkout: --ours/--theirs, --force and --merge are incompatible when\n"
1833 "checking out of the index."));
1835 if (opts
->accept_pathspec
&& !opts
->empty_pathspec_ok
&&
1836 !opts
->patch_mode
) /* patch mode is special */
1837 die(_("you must specify path(s) to restore"));
1840 if (opts
->new_branch
) {
1841 struct strbuf buf
= STRBUF_INIT
;
1843 if (opts
->new_branch_force
)
1844 opts
->branch_exists
= validate_branchname(opts
->new_branch
, &buf
);
1846 opts
->branch_exists
=
1847 validate_new_branchname(opts
->new_branch
, &buf
, 0);
1848 strbuf_release(&buf
);
1851 if (opts
->patch_mode
|| opts
->pathspec
.nr
)
1852 return checkout_paths(opts
, new_branch_info
);
1854 return checkout_branch(opts
, new_branch_info
);
1857 int cmd_checkout(int argc
, const char **argv
, const char *prefix
)
1859 struct checkout_opts opts
;
1860 struct option
*options
;
1861 struct option checkout_options
[] = {
1862 OPT_STRING('b', NULL
, &opts
.new_branch
, N_("branch"),
1863 N_("create and checkout a new branch")),
1864 OPT_STRING('B', NULL
, &opts
.new_branch_force
, N_("branch"),
1865 N_("create/reset and checkout a branch")),
1866 OPT_BOOL('l', NULL
, &opts
.new_branch_log
, N_("create reflog for new branch")),
1867 OPT_BOOL(0, "guess", &opts
.dwim_new_local_branch
,
1868 N_("second guess 'git checkout <no-such-branch>' (default)")),
1869 OPT_BOOL(0, "overlay", &opts
.overlay_mode
, N_("use overlay mode (default)")),
1873 struct branch_info new_branch_info
= { 0 };
1875 memset(&opts
, 0, sizeof(opts
));
1876 opts
.dwim_new_local_branch
= 1;
1877 opts
.switch_branch_doing_nothing_is_ok
= 1;
1878 opts
.only_merge_on_switching_branches
= 0;
1879 opts
.accept_ref
= 1;
1880 opts
.accept_pathspec
= 1;
1881 opts
.implicit_detach
= 1;
1882 opts
.can_switch_when_in_progress
= 1;
1883 opts
.orphan_from_empty_tree
= 0;
1884 opts
.empty_pathspec_ok
= 1;
1885 opts
.overlay_mode
= -1;
1886 opts
.checkout_index
= -2; /* default on */
1887 opts
.checkout_worktree
= -2; /* default on */
1889 if (argc
== 3 && !strcmp(argv
[1], "-b")) {
1891 * User ran 'git checkout -b <branch>' and expects
1892 * the same behavior as 'git switch -c <branch>'.
1894 opts
.switch_branch_doing_nothing_is_ok
= 0;
1895 opts
.only_merge_on_switching_branches
= 1;
1898 options
= parse_options_dup(checkout_options
);
1899 options
= add_common_options(&opts
, options
);
1900 options
= add_common_switch_branch_options(&opts
, options
);
1901 options
= add_checkout_path_options(&opts
, options
);
1903 ret
= checkout_main(argc
, argv
, prefix
, &opts
,
1904 options
, checkout_usage
, &new_branch_info
);
1905 branch_info_release(&new_branch_info
);
1906 clear_pathspec(&opts
.pathspec
);
1907 free(opts
.pathspec_from_file
);
1908 FREE_AND_NULL(options
);
1912 int cmd_switch(int argc
, const char **argv
, const char *prefix
)
1914 struct checkout_opts opts
;
1915 struct option
*options
= NULL
;
1916 struct option switch_options
[] = {
1917 OPT_STRING('c', "create", &opts
.new_branch
, N_("branch"),
1918 N_("create and switch to a new branch")),
1919 OPT_STRING('C', "force-create", &opts
.new_branch_force
, N_("branch"),
1920 N_("create/reset and switch to a branch")),
1921 OPT_BOOL(0, "guess", &opts
.dwim_new_local_branch
,
1922 N_("second guess 'git switch <no-such-branch>'")),
1923 OPT_BOOL(0, "discard-changes", &opts
.discard_changes
,
1924 N_("throw away local modifications")),
1928 struct branch_info new_branch_info
= { 0 };
1930 memset(&opts
, 0, sizeof(opts
));
1931 opts
.dwim_new_local_branch
= 1;
1932 opts
.accept_ref
= 1;
1933 opts
.accept_pathspec
= 0;
1934 opts
.switch_branch_doing_nothing_is_ok
= 0;
1935 opts
.only_merge_on_switching_branches
= 1;
1936 opts
.implicit_detach
= 0;
1937 opts
.can_switch_when_in_progress
= 0;
1938 opts
.orphan_from_empty_tree
= 1;
1939 opts
.overlay_mode
= -1;
1941 options
= parse_options_dup(switch_options
);
1942 options
= add_common_options(&opts
, options
);
1943 options
= add_common_switch_branch_options(&opts
, options
);
1947 ret
= checkout_main(argc
, argv
, prefix
, &opts
,
1948 options
, switch_branch_usage
, &new_branch_info
);
1949 branch_info_release(&new_branch_info
);
1950 FREE_AND_NULL(options
);
1954 int cmd_restore(int argc
, const char **argv
, const char *prefix
)
1956 struct checkout_opts opts
;
1957 struct option
*options
;
1958 struct option restore_options
[] = {
1959 OPT_STRING('s', "source", &opts
.from_treeish
, "<tree-ish>",
1960 N_("which tree-ish to checkout from")),
1961 OPT_BOOL('S', "staged", &opts
.checkout_index
,
1962 N_("restore the index")),
1963 OPT_BOOL('W', "worktree", &opts
.checkout_worktree
,
1964 N_("restore the working tree (default)")),
1965 OPT_BOOL(0, "ignore-unmerged", &opts
.ignore_unmerged
,
1966 N_("ignore unmerged entries")),
1967 OPT_BOOL(0, "overlay", &opts
.overlay_mode
, N_("use overlay mode")),
1971 struct branch_info new_branch_info
= { 0 };
1973 memset(&opts
, 0, sizeof(opts
));
1974 opts
.accept_ref
= 0;
1975 opts
.accept_pathspec
= 1;
1976 opts
.empty_pathspec_ok
= 0;
1977 opts
.overlay_mode
= 0;
1978 opts
.checkout_index
= -1; /* default off */
1979 opts
.checkout_worktree
= -2; /* default on */
1980 opts
.ignore_unmerged_opt
= "--ignore-unmerged";
1982 options
= parse_options_dup(restore_options
);
1983 options
= add_common_options(&opts
, options
);
1984 options
= add_checkout_path_options(&opts
, options
);
1986 ret
= checkout_main(argc
, argv
, prefix
, &opts
,
1987 options
, restore_usage
, &new_branch_info
);
1988 branch_info_release(&new_branch_info
);
1989 FREE_AND_NULL(options
);