1 #define USE_THE_INDEX_VARIABLE
6 #include "cache-tree.h"
17 #include "merge-recursive.h"
18 #include "object-store.h"
19 #include "parse-options.h"
22 #include "resolve-undo.h"
24 #include "run-command.h"
25 #include "submodule.h"
26 #include "submodule-config.h"
28 #include "tree-walk.h"
29 #include "unpack-trees.h"
30 #include "wt-status.h"
31 #include "xdiff-interface.h"
33 #include "parallel-checkout.h"
34 #include "add-interactive.h"
36 static const char * const checkout_usage
[] = {
37 N_("git checkout [<options>] <branch>"),
38 N_("git checkout [<options>] [<branch>] -- <file>..."),
42 static const char * const switch_branch_usage
[] = {
43 N_("git switch [<options>] [<branch>]"),
47 static const char * const restore_usage
[] = {
48 N_("git restore [<options>] [--source=<branch>] <file>..."),
52 struct checkout_opts
{
61 int ignore_skipworktree
;
62 int ignore_other_worktrees
;
64 int count_checkout_paths
;
66 int dwim_new_local_branch
;
70 int switch_branch_doing_nothing_is_ok
;
71 int only_merge_on_switching_branches
;
72 int can_switch_when_in_progress
;
73 int orphan_from_empty_tree
;
74 int empty_pathspec_ok
;
76 int checkout_worktree
;
77 const char *ignore_unmerged_opt
;
79 int pathspec_file_nul
;
80 char *pathspec_from_file
;
82 const char *new_branch
;
83 const char *new_branch_force
;
84 const char *new_orphan_branch
;
86 enum branch_track track
;
87 struct diff_options diff_options
;
92 struct pathspec pathspec
;
93 const char *from_treeish
;
94 struct tree
*source_tree
;
98 char *name
; /* The short name used */
99 char *path
; /* The full name of a real branch */
100 struct commit
*commit
; /* The named commit */
101 char *refname
; /* The full name of the ref being checked out. */
102 struct object_id oid
; /* The object ID of the commit being checked out. */
104 * if not null the branch is detached because it's already
105 * checked out in this checkout
110 static void branch_info_release(struct branch_info
*info
)
115 free(info
->checkout
);
118 static int post_checkout_hook(struct commit
*old_commit
, struct commit
*new_commit
,
121 return run_hooks_l("post-checkout",
122 oid_to_hex(old_commit
? &old_commit
->object
.oid
: null_oid()),
123 oid_to_hex(new_commit
? &new_commit
->object
.oid
: null_oid()),
124 changed
? "1" : "0", NULL
);
125 /* "new_commit" can be NULL when checking out from the index before
130 static int update_some(const struct object_id
*oid
, struct strbuf
*base
,
131 const char *pathname
, unsigned mode
, void *context UNUSED
)
134 struct cache_entry
*ce
;
138 return READ_TREE_RECURSIVE
;
140 len
= base
->len
+ strlen(pathname
);
141 ce
= make_empty_cache_entry(&the_index
, len
);
142 oidcpy(&ce
->oid
, oid
);
143 memcpy(ce
->name
, base
->buf
, base
->len
);
144 memcpy(ce
->name
+ base
->len
, pathname
, len
- base
->len
);
145 ce
->ce_flags
= create_ce_flags(0) | CE_UPDATE
;
146 ce
->ce_namelen
= len
;
147 ce
->ce_mode
= create_ce_mode(mode
);
150 * If the entry is the same as the current index, we can leave the old
151 * entry in place. Whether it is UPTODATE or not, checkout_entry will
152 * do the right thing.
154 pos
= index_name_pos(&the_index
, ce
->name
, ce
->ce_namelen
);
156 struct cache_entry
*old
= the_index
.cache
[pos
];
157 if (ce
->ce_mode
== old
->ce_mode
&&
158 !ce_intent_to_add(old
) &&
159 oideq(&ce
->oid
, &old
->oid
)) {
160 old
->ce_flags
|= CE_UPDATE
;
161 discard_cache_entry(ce
);
166 add_index_entry(&the_index
, ce
,
167 ADD_CACHE_OK_TO_ADD
| ADD_CACHE_OK_TO_REPLACE
);
171 static int read_tree_some(struct tree
*tree
, const struct pathspec
*pathspec
)
173 read_tree(the_repository
, tree
,
174 pathspec
, update_some
, NULL
);
176 /* update the index with the given tree's info
177 * for all args, expanding wildcards, and exit
178 * with any non-zero return code.
183 static int skip_same_name(const struct cache_entry
*ce
, int pos
)
185 while (++pos
< the_index
.cache_nr
&&
186 !strcmp(the_index
.cache
[pos
]->name
, ce
->name
))
191 static int check_stage(int stage
, const struct cache_entry
*ce
, int pos
,
194 while (pos
< the_index
.cache_nr
&&
195 !strcmp(the_index
.cache
[pos
]->name
, ce
->name
)) {
196 if (ce_stage(the_index
.cache
[pos
]) == stage
)
203 return error(_("path '%s' does not have our version"), ce
->name
);
205 return error(_("path '%s' does not have their version"), ce
->name
);
208 static int check_stages(unsigned stages
, const struct cache_entry
*ce
, int pos
)
211 const char *name
= ce
->name
;
213 while (pos
< the_index
.cache_nr
) {
214 ce
= the_index
.cache
[pos
];
215 if (strcmp(name
, ce
->name
))
217 seen
|= (1 << ce_stage(ce
));
220 if ((stages
& seen
) != stages
)
221 return error(_("path '%s' does not have all necessary versions"),
226 static int checkout_stage(int stage
, const struct cache_entry
*ce
, int pos
,
227 const struct checkout
*state
, int *nr_checkouts
,
230 while (pos
< the_index
.cache_nr
&&
231 !strcmp(the_index
.cache
[pos
]->name
, ce
->name
)) {
232 if (ce_stage(the_index
.cache
[pos
]) == stage
)
233 return checkout_entry(the_index
.cache
[pos
], state
,
238 unlink_entry(ce
, NULL
);
242 return error(_("path '%s' does not have our version"), ce
->name
);
244 return error(_("path '%s' does not have their version"), ce
->name
);
247 static int checkout_merged(int pos
, const struct checkout
*state
,
248 int *nr_checkouts
, struct mem_pool
*ce_mem_pool
)
250 struct cache_entry
*ce
= the_index
.cache
[pos
];
251 const char *path
= ce
->name
;
252 mmfile_t ancestor
, ours
, theirs
;
253 enum ll_merge_result merge_status
;
255 struct object_id oid
;
256 mmbuffer_t result_buf
;
257 struct object_id threeway
[3];
259 struct ll_merge_options ll_opts
;
262 memset(threeway
, 0, sizeof(threeway
));
263 while (pos
< the_index
.cache_nr
) {
265 stage
= ce_stage(ce
);
266 if (!stage
|| strcmp(path
, ce
->name
))
268 oidcpy(&threeway
[stage
- 1], &ce
->oid
);
270 mode
= create_ce_mode(ce
->ce_mode
);
272 ce
= the_index
.cache
[pos
];
274 if (is_null_oid(&threeway
[1]) || is_null_oid(&threeway
[2]))
275 return error(_("path '%s' does not have necessary versions"), path
);
277 read_mmblob(&ancestor
, &threeway
[0]);
278 read_mmblob(&ours
, &threeway
[1]);
279 read_mmblob(&theirs
, &threeway
[2]);
281 memset(&ll_opts
, 0, sizeof(ll_opts
));
282 git_config_get_bool("merge.renormalize", &renormalize
);
283 ll_opts
.renormalize
= renormalize
;
284 merge_status
= ll_merge(&result_buf
, path
, &ancestor
, "base",
285 &ours
, "ours", &theirs
, "theirs",
286 state
->istate
, &ll_opts
);
290 if (merge_status
== LL_MERGE_BINARY_CONFLICT
)
291 warning("Cannot merge binary files: %s (%s vs. %s)",
292 path
, "ours", "theirs");
293 if (merge_status
< 0 || !result_buf
.ptr
) {
294 free(result_buf
.ptr
);
295 return error(_("path '%s': cannot merge"), path
);
300 * There is absolutely no reason to write this as a blob object
301 * and create a phony cache entry. This hack is primarily to get
302 * to the write_entry() machinery that massages the contents to
303 * work-tree format and writes out which only allows it for a
304 * cache entry. The code in write_entry() needs to be refactored
305 * to allow us to feed a <buffer, size, mode> instead of a cache
306 * entry. Such a refactoring would help merge_recursive as well
307 * (it also writes the merge result to the object database even
308 * when it may contain conflicts).
310 if (write_object_file(result_buf
.ptr
, result_buf
.size
, OBJ_BLOB
, &oid
))
311 die(_("Unable to add merge result for '%s'"), path
);
312 free(result_buf
.ptr
);
313 ce
= make_transient_cache_entry(mode
, &oid
, path
, 2, ce_mem_pool
);
315 die(_("make_cache_entry failed for path '%s'"), path
);
316 status
= checkout_entry(ce
, state
, NULL
, nr_checkouts
);
320 static void mark_ce_for_checkout_overlay(struct cache_entry
*ce
,
322 const struct checkout_opts
*opts
)
324 ce
->ce_flags
&= ~CE_MATCHED
;
325 if (!opts
->ignore_skipworktree
&& ce_skip_worktree(ce
))
327 if (opts
->source_tree
&& !(ce
->ce_flags
& CE_UPDATE
))
329 * "git checkout tree-ish -- path", but this entry
330 * is in the original index but is not in tree-ish
331 * or does not match the pathspec; it will not be
332 * checked out to the working tree. We will not do
333 * anything to this entry at all.
337 * Either this entry came from the tree-ish we are
338 * checking the paths out of, or we are checking out
341 * If it comes from the tree-ish, we already know it
342 * matches the pathspec and could just stamp
343 * CE_MATCHED to it from update_some(). But we still
344 * need ps_matched and read_tree (and
345 * eventually tree_entry_interesting) cannot fill
346 * ps_matched yet. Once it can, we can avoid calling
347 * match_pathspec() for _all_ entries when
348 * opts->source_tree != NULL.
350 if (ce_path_match(&the_index
, ce
, &opts
->pathspec
, ps_matched
))
351 ce
->ce_flags
|= CE_MATCHED
;
354 static void mark_ce_for_checkout_no_overlay(struct cache_entry
*ce
,
356 const struct checkout_opts
*opts
)
358 ce
->ce_flags
&= ~CE_MATCHED
;
359 if (!opts
->ignore_skipworktree
&& ce_skip_worktree(ce
))
361 if (ce_path_match(&the_index
, ce
, &opts
->pathspec
, ps_matched
)) {
362 ce
->ce_flags
|= CE_MATCHED
;
363 if (opts
->source_tree
&& !(ce
->ce_flags
& CE_UPDATE
))
365 * In overlay mode, but the path is not in
366 * tree-ish, which means we should remove it
367 * from the index and the working tree.
369 ce
->ce_flags
|= CE_REMOVE
| CE_WT_REMOVE
;
373 static int checkout_worktree(const struct checkout_opts
*opts
,
374 const struct branch_info
*info
)
376 struct checkout state
= CHECKOUT_INIT
;
377 int nr_checkouts
= 0, nr_unmerged
= 0;
380 int pc_workers
, pc_threshold
;
381 struct mem_pool ce_mem_pool
;
384 state
.refresh_cache
= 1;
385 state
.istate
= &the_index
;
387 mem_pool_init(&ce_mem_pool
, 0);
388 get_parallel_checkout_configs(&pc_workers
, &pc_threshold
);
389 init_checkout_metadata(&state
.meta
, info
->refname
,
390 info
->commit
? &info
->commit
->object
.oid
: &info
->oid
,
393 enable_delayed_checkout(&state
);
396 init_parallel_checkout();
398 for (pos
= 0; pos
< the_index
.cache_nr
; pos
++) {
399 struct cache_entry
*ce
= the_index
.cache
[pos
];
400 if (ce
->ce_flags
& CE_MATCHED
) {
402 errs
|= checkout_entry(ce
, &state
,
403 NULL
, &nr_checkouts
);
406 if (opts
->writeout_stage
)
407 errs
|= checkout_stage(opts
->writeout_stage
,
410 &nr_checkouts
, opts
->overlay_mode
);
411 else if (opts
->merge
)
412 errs
|= checkout_merged(pos
, &state
,
415 pos
= skip_same_name(ce
, pos
) - 1;
419 errs
|= run_parallel_checkout(&state
, pc_workers
, pc_threshold
,
421 mem_pool_discard(&ce_mem_pool
, should_validate_cache_entries());
422 remove_marked_cache_entries(&the_index
, 1);
423 remove_scheduled_dirs();
424 errs
|= finish_delayed_checkout(&state
, opts
->show_progress
);
426 if (opts
->count_checkout_paths
) {
428 fprintf_ln(stderr
, Q_("Recreated %d merge conflict",
429 "Recreated %d merge conflicts",
432 if (opts
->source_tree
)
433 fprintf_ln(stderr
, Q_("Updated %d path from %s",
434 "Updated %d paths from %s",
437 find_unique_abbrev(&opts
->source_tree
->object
.oid
,
439 else if (!nr_unmerged
|| nr_checkouts
)
440 fprintf_ln(stderr
, Q_("Updated %d path from the index",
441 "Updated %d paths from the index",
449 static int checkout_paths(const struct checkout_opts
*opts
,
450 const struct branch_info
*new_branch_info
)
453 static char *ps_matched
;
454 struct object_id rev
;
457 struct lock_file lock_file
= LOCK_INIT
;
460 trace2_cmd_mode(opts
->patch_mode
? "patch" : "path");
462 if (opts
->track
!= BRANCH_TRACK_UNSPECIFIED
)
463 die(_("'%s' cannot be used with updating paths"), "--track");
465 if (opts
->new_branch_log
)
466 die(_("'%s' cannot be used with updating paths"), "-l");
468 if (opts
->ignore_unmerged
&& opts
->patch_mode
)
469 die(_("'%s' cannot be used with updating paths"),
470 opts
->ignore_unmerged_opt
);
472 if (opts
->force_detach
)
473 die(_("'%s' cannot be used with updating paths"), "--detach");
475 if (opts
->merge
&& opts
->patch_mode
)
476 die(_("options '%s' and '%s' cannot be used together"), "--merge", "--patch");
478 if (opts
->ignore_unmerged
&& opts
->merge
)
479 die(_("options '%s' and '%s' cannot be used together"),
480 opts
->ignore_unmerged_opt
, "-m");
482 if (opts
->new_branch
)
483 die(_("Cannot update paths and switch to branch '%s' at the same time."),
486 if (!opts
->checkout_worktree
&& !opts
->checkout_index
)
487 die(_("neither '%s' or '%s' is specified"),
488 "--staged", "--worktree");
490 if (!opts
->checkout_worktree
&& !opts
->from_treeish
)
491 die(_("'%s' must be used when '%s' is not specified"),
492 "--worktree", "--source");
495 * Reject --staged option to the restore command when combined with
496 * merge-related options. Use the accept_ref flag to distinguish it
497 * from the checkout command, which does not accept --staged anyway.
499 * `restore --ours|--theirs --worktree --staged` could mean resolving
500 * conflicted paths to one side in both the worktree and the index,
501 * but does not currently.
503 * `restore --merge|--conflict=<style>` already recreates conflicts
504 * in both the worktree and the index, so adding --staged would be
507 if (!opts
->accept_ref
&& opts
->checkout_index
) {
508 if (opts
->writeout_stage
)
509 die(_("'%s' or '%s' cannot be used with %s"),
510 "--ours", "--theirs", "--staged");
513 die(_("'%s' or '%s' cannot be used with %s"),
514 "--merge", "--conflict", "--staged");
517 if (opts
->patch_mode
) {
518 enum add_p_mode patch_mode
;
519 const char *rev
= new_branch_info
->name
;
520 char rev_oid
[GIT_MAX_HEXSZ
+ 1];
523 * Since rev can be in the form of `<a>...<b>` (which is not
524 * recognized by diff-index), we will always replace the name
525 * with the hex of the commit (whether it's in `...` form or
526 * not) for the run_add_interactive() machinery to work
527 * properly. However, there is special logic for the HEAD case
528 * so we mustn't replace that. Also, when we were given a
529 * tree-object, new_branch_info->commit would be NULL, but we
530 * do not have to do any replacement, either.
532 if (rev
&& new_branch_info
->commit
&& strcmp(rev
, "HEAD"))
533 rev
= oid_to_hex_r(rev_oid
, &new_branch_info
->commit
->object
.oid
);
535 if (opts
->checkout_index
&& opts
->checkout_worktree
)
536 patch_mode
= ADD_P_CHECKOUT
;
537 else if (opts
->checkout_index
&& !opts
->checkout_worktree
)
538 patch_mode
= ADD_P_RESET
;
539 else if (!opts
->checkout_index
&& opts
->checkout_worktree
)
540 patch_mode
= ADD_P_WORKTREE
;
542 BUG("either flag must have been set, worktree=%d, index=%d",
543 opts
->checkout_worktree
, opts
->checkout_index
);
544 return !!run_add_p(the_repository
, patch_mode
, rev
,
548 repo_hold_locked_index(the_repository
, &lock_file
, LOCK_DIE_ON_ERROR
);
549 if (repo_read_index_preload(the_repository
, &opts
->pathspec
, 0) < 0)
550 return error(_("index file corrupt"));
552 if (opts
->source_tree
)
553 read_tree_some(opts
->source_tree
, &opts
->pathspec
);
555 ps_matched
= xcalloc(opts
->pathspec
.nr
, 1);
558 * Make sure all pathspecs participated in locating the paths
561 for (pos
= 0; pos
< the_index
.cache_nr
; pos
++)
562 if (opts
->overlay_mode
)
563 mark_ce_for_checkout_overlay(the_index
.cache
[pos
],
567 mark_ce_for_checkout_no_overlay(the_index
.cache
[pos
],
571 if (report_path_error(ps_matched
, &opts
->pathspec
)) {
577 /* "checkout -m path" to recreate conflicted state */
579 unmerge_marked_index(&the_index
);
581 /* Any unmerged paths? */
582 for (pos
= 0; pos
< the_index
.cache_nr
; pos
++) {
583 const struct cache_entry
*ce
= the_index
.cache
[pos
];
584 if (ce
->ce_flags
& CE_MATCHED
) {
587 if (opts
->ignore_unmerged
) {
589 warning(_("path '%s' is unmerged"), ce
->name
);
590 } else if (opts
->writeout_stage
) {
591 errs
|= check_stage(opts
->writeout_stage
, ce
, pos
, opts
->overlay_mode
);
592 } else if (opts
->merge
) {
593 errs
|= check_stages((1<<2) | (1<<3), ce
, pos
);
596 error(_("path '%s' is unmerged"), ce
->name
);
598 pos
= skip_same_name(ce
, pos
) - 1;
604 /* Now we are committed to check them out */
605 if (opts
->checkout_worktree
)
606 errs
|= checkout_worktree(opts
, new_branch_info
);
608 remove_marked_cache_entries(&the_index
, 1);
611 * Allow updating the index when checking out from the index.
612 * This is to save new stat info.
614 if (opts
->checkout_worktree
&& !opts
->checkout_index
&& !opts
->source_tree
)
617 checkout_index
= opts
->checkout_index
;
619 if (checkout_index
) {
620 if (write_locked_index(&the_index
, &lock_file
, COMMIT_LOCK
))
621 die(_("unable to write new index file"));
624 * NEEDSWORK: if --worktree is not specified, we
625 * should save stat info of checked out files in the
626 * index to avoid the next (potentially costly)
627 * refresh. But it's a bit tricker to do...
629 rollback_lock_file(&lock_file
);
632 read_ref_full("HEAD", 0, &rev
, NULL
);
633 head
= lookup_commit_reference_gently(the_repository
, &rev
, 1);
635 errs
|= post_checkout_hook(head
, head
, 0);
639 static void show_local_changes(struct object
*head
,
640 const struct diff_options
*opts
)
643 /* I think we want full paths, even if we're in a subdirectory. */
644 repo_init_revisions(the_repository
, &rev
, NULL
);
645 rev
.diffopt
.flags
= opts
->flags
;
646 rev
.diffopt
.output_format
|= DIFF_FORMAT_NAME_STATUS
;
647 rev
.diffopt
.flags
.recursive
= 1;
648 diff_setup_done(&rev
.diffopt
);
649 add_pending_object(&rev
, head
, NULL
);
650 run_diff_index(&rev
, 0);
651 release_revisions(&rev
);
654 static void describe_detached_head(const char *msg
, struct commit
*commit
)
656 struct strbuf sb
= STRBUF_INIT
;
658 if (!parse_commit(commit
))
659 pp_commit_easy(CMIT_FMT_ONELINE
, commit
, &sb
);
660 if (print_sha1_ellipsis()) {
661 fprintf(stderr
, "%s %s... %s\n", msg
,
662 find_unique_abbrev(&commit
->object
.oid
, DEFAULT_ABBREV
), sb
.buf
);
664 fprintf(stderr
, "%s %s %s\n", msg
,
665 find_unique_abbrev(&commit
->object
.oid
, DEFAULT_ABBREV
), sb
.buf
);
670 static int reset_tree(struct tree
*tree
, const struct checkout_opts
*o
,
671 int worktree
, int *writeout_error
,
672 struct branch_info
*info
)
674 struct unpack_trees_options opts
;
675 struct tree_desc tree_desc
;
677 memset(&opts
, 0, sizeof(opts
));
679 opts
.update
= worktree
;
680 opts
.skip_unmerged
= !worktree
;
681 opts
.reset
= o
->force
? UNPACK_RESET_OVERWRITE_UNTRACKED
:
682 UNPACK_RESET_PROTECT_UNTRACKED
;
683 opts
.preserve_ignored
= (!o
->force
&& !o
->overwrite_ignore
);
685 opts
.fn
= oneway_merge
;
686 opts
.verbose_update
= o
->show_progress
;
687 opts
.src_index
= &the_index
;
688 opts
.dst_index
= &the_index
;
689 init_checkout_metadata(&opts
.meta
, info
->refname
,
690 info
->commit
? &info
->commit
->object
.oid
: null_oid(),
693 init_tree_desc(&tree_desc
, tree
->buffer
, tree
->size
);
694 switch (unpack_trees(1, &tree_desc
, &opts
)) {
698 * We return 0 nevertheless, as the index is all right
699 * and more importantly we have made best efforts to
700 * update paths in the work tree, and we cannot revert
711 static void setup_branch_path(struct branch_info
*branch
)
713 struct strbuf buf
= STRBUF_INIT
;
716 * If this is a ref, resolve it; otherwise, look up the OID for our
717 * expression. Failure here is okay.
719 if (!dwim_ref(branch
->name
, strlen(branch
->name
), &branch
->oid
, &branch
->refname
, 0))
720 repo_get_oid_committish(the_repository
, branch
->name
, &branch
->oid
);
722 strbuf_branchname(&buf
, branch
->name
, INTERPRET_BRANCH_LOCAL
);
723 if (strcmp(buf
.buf
, branch
->name
)) {
725 branch
->name
= xstrdup(buf
.buf
);
727 strbuf_splice(&buf
, 0, 0, "refs/heads/", 11);
729 branch
->path
= strbuf_detach(&buf
, NULL
);
732 static void init_topts(struct unpack_trees_options
*topts
, int merge
,
733 int show_progress
, int overwrite_ignore
,
734 struct commit
*old_commit
)
736 memset(topts
, 0, sizeof(*topts
));
737 topts
->head_idx
= -1;
738 topts
->src_index
= &the_index
;
739 topts
->dst_index
= &the_index
;
741 setup_unpack_trees_porcelain(topts
, "checkout");
743 topts
->initial_checkout
= is_index_unborn(&the_index
);
746 topts
->quiet
= merge
&& old_commit
;
747 topts
->verbose_update
= show_progress
;
748 topts
->fn
= twoway_merge
;
749 topts
->preserve_ignored
= !overwrite_ignore
;
752 static int merge_working_tree(const struct checkout_opts
*opts
,
753 struct branch_info
*old_branch_info
,
754 struct branch_info
*new_branch_info
,
758 struct lock_file lock_file
= LOCK_INIT
;
759 struct tree
*new_tree
;
761 repo_hold_locked_index(the_repository
, &lock_file
, LOCK_DIE_ON_ERROR
);
762 if (repo_read_index_preload(the_repository
, NULL
, 0) < 0)
763 return error(_("index file corrupt"));
765 resolve_undo_clear_index(&the_index
);
766 if (opts
->new_orphan_branch
&& opts
->orphan_from_empty_tree
) {
767 if (new_branch_info
->commit
)
768 BUG("'switch --orphan' should never accept a commit as starting point");
769 new_tree
= parse_tree_indirect(the_hash_algo
->empty_tree
);
771 new_tree
= get_commit_tree(new_branch_info
->commit
);
772 if (opts
->discard_changes
) {
773 ret
= reset_tree(new_tree
, opts
, 1, writeout_error
, new_branch_info
);
777 struct tree_desc trees
[2];
779 struct unpack_trees_options topts
;
780 const struct object_id
*old_commit_oid
;
782 refresh_index(&the_index
, REFRESH_QUIET
, NULL
, NULL
, NULL
);
784 if (unmerged_index(&the_index
)) {
785 error(_("you need to resolve your current index first"));
789 /* 2-way merge to the new branch */
790 init_topts(&topts
, opts
->merge
, opts
->show_progress
,
791 opts
->overwrite_ignore
, old_branch_info
->commit
);
792 init_checkout_metadata(&topts
.meta
, new_branch_info
->refname
,
793 new_branch_info
->commit
?
794 &new_branch_info
->commit
->object
.oid
:
795 &new_branch_info
->oid
, NULL
);
797 old_commit_oid
= old_branch_info
->commit
?
798 &old_branch_info
->commit
->object
.oid
:
799 the_hash_algo
->empty_tree
;
800 tree
= parse_tree_indirect(old_commit_oid
);
802 die(_("unable to parse commit %s"),
803 oid_to_hex(old_commit_oid
));
805 init_tree_desc(&trees
[0], tree
->buffer
, tree
->size
);
806 parse_tree(new_tree
);
808 init_tree_desc(&trees
[1], tree
->buffer
, tree
->size
);
810 ret
= unpack_trees(2, trees
, &topts
);
811 clear_unpack_trees_porcelain(&topts
);
814 * Unpack couldn't do a trivial merge; either
815 * give up or do a real merge, depending on
816 * whether the merge flag was used.
819 struct tree
*old_tree
;
820 struct merge_options o
;
821 struct strbuf sb
= STRBUF_INIT
;
822 struct strbuf old_commit_shortname
= STRBUF_INIT
;
828 * Without old_branch_info->commit, the below is the same as
829 * the two-tree unpack we already tried and failed.
831 if (!old_branch_info
->commit
)
833 old_tree
= get_commit_tree(old_branch_info
->commit
);
835 if (repo_index_has_changes(the_repository
, old_tree
, &sb
))
836 die(_("cannot continue with staged changes in "
837 "the following files:\n%s"), sb
.buf
);
840 /* Do more real merge */
843 * We update the index fully, then write the
844 * tree from the index, then merge the new
845 * branch with the current tree, with the old
846 * branch as the base. Then we reset the index
847 * (but not the working tree) to the new
848 * branch, leaving the working tree as the
849 * merged version, but skipping unmerged
850 * entries in the index.
853 add_files_to_cache(NULL
, NULL
, 0);
854 init_merge_options(&o
, the_repository
);
856 work
= write_in_core_index_as_tree(the_repository
);
858 ret
= reset_tree(new_tree
,
860 writeout_error
, new_branch_info
);
863 o
.ancestor
= old_branch_info
->name
;
864 if (!old_branch_info
->name
) {
865 strbuf_add_unique_abbrev(&old_commit_shortname
,
866 &old_branch_info
->commit
->object
.oid
,
868 o
.ancestor
= old_commit_shortname
.buf
;
870 o
.branch1
= new_branch_info
->name
;
872 ret
= merge_trees(&o
,
878 ret
= reset_tree(new_tree
,
880 writeout_error
, new_branch_info
);
881 strbuf_release(&o
.obuf
);
882 strbuf_release(&old_commit_shortname
);
888 if (!cache_tree_fully_valid(the_index
.cache_tree
))
889 cache_tree_update(&the_index
, WRITE_TREE_SILENT
| WRITE_TREE_REPAIR
);
891 if (write_locked_index(&the_index
, &lock_file
, COMMIT_LOCK
))
892 die(_("unable to write new index file"));
894 if (!opts
->discard_changes
&& !opts
->quiet
&& new_branch_info
->commit
)
895 show_local_changes(&new_branch_info
->commit
->object
, &opts
->diff_options
);
900 static void report_tracking(struct branch_info
*new_branch_info
)
902 struct strbuf sb
= STRBUF_INIT
;
903 struct branch
*branch
= branch_get(new_branch_info
->name
);
905 if (!format_tracking_info(branch
, &sb
, AHEAD_BEHIND_FULL
))
907 fputs(sb
.buf
, stdout
);
911 static void update_refs_for_switch(const struct checkout_opts
*opts
,
912 struct branch_info
*old_branch_info
,
913 struct branch_info
*new_branch_info
)
915 struct strbuf msg
= STRBUF_INIT
;
916 const char *old_desc
, *reflog_msg
;
917 if (opts
->new_branch
) {
918 if (opts
->new_orphan_branch
) {
921 refname
= mkpathdup("refs/heads/%s", opts
->new_orphan_branch
);
922 if (opts
->new_branch_log
&&
923 !should_autocreate_reflog(refname
)) {
925 struct strbuf err
= STRBUF_INIT
;
927 ret
= safe_create_reflog(refname
, &err
);
929 fprintf(stderr
, _("Can not do reflog for '%s': %s\n"),
930 opts
->new_orphan_branch
, err
.buf
);
931 strbuf_release(&err
);
935 strbuf_release(&err
);
940 create_branch(the_repository
,
941 opts
->new_branch
, new_branch_info
->name
,
942 opts
->new_branch_force
? 1 : 0,
943 opts
->new_branch_force
? 1 : 0,
944 opts
->new_branch_log
,
948 free(new_branch_info
->name
);
949 free(new_branch_info
->refname
);
950 new_branch_info
->name
= xstrdup(opts
->new_branch
);
951 setup_branch_path(new_branch_info
);
954 old_desc
= old_branch_info
->name
;
955 if (!old_desc
&& old_branch_info
->commit
)
956 old_desc
= oid_to_hex(&old_branch_info
->commit
->object
.oid
);
958 reflog_msg
= getenv("GIT_REFLOG_ACTION");
960 strbuf_addf(&msg
, "checkout: moving from %s to %s",
961 old_desc
? old_desc
: "(invalid)", new_branch_info
->name
);
963 strbuf_insertstr(&msg
, 0, reflog_msg
);
965 if (!strcmp(new_branch_info
->name
, "HEAD") && !new_branch_info
->path
&& !opts
->force_detach
) {
967 } else if (opts
->force_detach
|| !new_branch_info
->path
) { /* No longer on any branch. */
968 update_ref(msg
.buf
, "HEAD", &new_branch_info
->commit
->object
.oid
, NULL
,
969 REF_NO_DEREF
, UPDATE_REFS_DIE_ON_ERR
);
971 if (old_branch_info
->path
&&
972 advice_enabled(ADVICE_DETACHED_HEAD
) && !opts
->force_detach
)
973 detach_advice(new_branch_info
->name
);
974 describe_detached_head(_("HEAD is now at"), new_branch_info
->commit
);
976 } else if (new_branch_info
->path
) { /* Switch branches. */
977 if (create_symref("HEAD", new_branch_info
->path
, msg
.buf
) < 0)
978 die(_("unable to update HEAD"));
980 if (old_branch_info
->path
&& !strcmp(new_branch_info
->path
, old_branch_info
->path
)) {
981 if (opts
->new_branch_force
)
982 fprintf(stderr
, _("Reset branch '%s'\n"),
983 new_branch_info
->name
);
985 fprintf(stderr
, _("Already on '%s'\n"),
986 new_branch_info
->name
);
987 } else if (opts
->new_branch
) {
988 if (opts
->branch_exists
)
989 fprintf(stderr
, _("Switched to and reset branch '%s'\n"), new_branch_info
->name
);
991 fprintf(stderr
, _("Switched to a new branch '%s'\n"), new_branch_info
->name
);
993 fprintf(stderr
, _("Switched to branch '%s'\n"),
994 new_branch_info
->name
);
997 if (old_branch_info
->path
&& old_branch_info
->name
) {
998 if (!ref_exists(old_branch_info
->path
) && reflog_exists(old_branch_info
->path
))
999 delete_reflog(old_branch_info
->path
);
1002 remove_branch_state(the_repository
, !opts
->quiet
);
1003 strbuf_release(&msg
);
1005 (new_branch_info
->path
|| (!opts
->force_detach
&& !strcmp(new_branch_info
->name
, "HEAD"))))
1006 report_tracking(new_branch_info
);
1009 static int add_pending_uninteresting_ref(const char *refname
,
1010 const struct object_id
*oid
,
1011 int flags UNUSED
, void *cb_data
)
1013 add_pending_oid(cb_data
, refname
, oid
, UNINTERESTING
);
1017 static void describe_one_orphan(struct strbuf
*sb
, struct commit
*commit
)
1019 strbuf_addstr(sb
, " ");
1020 strbuf_add_unique_abbrev(sb
, &commit
->object
.oid
, DEFAULT_ABBREV
);
1021 strbuf_addch(sb
, ' ');
1022 if (!parse_commit(commit
))
1023 pp_commit_easy(CMIT_FMT_ONELINE
, commit
, sb
);
1024 strbuf_addch(sb
, '\n');
1027 #define ORPHAN_CUTOFF 4
1028 static void suggest_reattach(struct commit
*commit
, struct rev_info
*revs
)
1030 struct commit
*c
, *last
= NULL
;
1031 struct strbuf sb
= STRBUF_INIT
;
1033 while ((c
= get_revision(revs
)) != NULL
) {
1034 if (lost
< ORPHAN_CUTOFF
)
1035 describe_one_orphan(&sb
, c
);
1039 if (ORPHAN_CUTOFF
< lost
) {
1040 int more
= lost
- ORPHAN_CUTOFF
;
1042 describe_one_orphan(&sb
, last
);
1044 strbuf_addf(&sb
, _(" ... and %d more.\n"), more
);
1049 /* The singular version */
1050 "Warning: you are leaving %d commit behind, "
1051 "not connected to\n"
1052 "any of your branches:\n\n"
1054 /* The plural version */
1055 "Warning: you are leaving %d commits behind, "
1056 "not connected to\n"
1057 "any of your branches:\n\n"
1059 /* Give ngettext() the count */
1063 strbuf_release(&sb
);
1065 if (advice_enabled(ADVICE_DETACHED_HEAD
))
1068 /* The singular version */
1069 "If you want to keep it by creating a new branch, "
1070 "this may be a good time\nto do so with:\n\n"
1071 " git branch <new-branch-name> %s\n\n",
1072 /* The plural version */
1073 "If you want to keep them by creating a new branch, "
1074 "this may be a good time\nto do so with:\n\n"
1075 " git branch <new-branch-name> %s\n\n",
1076 /* Give ngettext() the count */
1078 find_unique_abbrev(&commit
->object
.oid
, DEFAULT_ABBREV
));
1082 * We are about to leave commit that was at the tip of a detached
1083 * HEAD. If it is not reachable from any ref, this is the last chance
1084 * for the user to do so without resorting to reflog.
1086 static void orphaned_commit_warning(struct commit
*old_commit
, struct commit
*new_commit
)
1088 struct rev_info revs
;
1089 struct object
*object
= &old_commit
->object
;
1091 repo_init_revisions(the_repository
, &revs
, NULL
);
1092 setup_revisions(0, NULL
, &revs
, NULL
);
1094 object
->flags
&= ~UNINTERESTING
;
1095 add_pending_object(&revs
, object
, oid_to_hex(&object
->oid
));
1097 for_each_ref(add_pending_uninteresting_ref
, &revs
);
1099 add_pending_oid(&revs
, "HEAD",
1100 &new_commit
->object
.oid
,
1103 if (prepare_revision_walk(&revs
))
1104 die(_("internal error in revision walk"));
1105 if (!(old_commit
->object
.flags
& UNINTERESTING
))
1106 suggest_reattach(old_commit
, &revs
);
1108 describe_detached_head(_("Previous HEAD position was"), old_commit
);
1110 /* Clean up objects used, as they will be reused. */
1111 repo_clear_commit_marks(the_repository
, ALL_REV_FLAGS
);
1112 release_revisions(&revs
);
1115 static int switch_branches(const struct checkout_opts
*opts
,
1116 struct branch_info
*new_branch_info
)
1119 struct branch_info old_branch_info
= { 0 };
1120 struct object_id rev
;
1121 int flag
, writeout_error
= 0;
1124 trace2_cmd_mode("branch");
1126 memset(&old_branch_info
, 0, sizeof(old_branch_info
));
1127 old_branch_info
.path
= resolve_refdup("HEAD", 0, &rev
, &flag
);
1128 if (old_branch_info
.path
)
1129 old_branch_info
.commit
= lookup_commit_reference_gently(the_repository
, &rev
, 1);
1130 if (!(flag
& REF_ISSYMREF
))
1131 FREE_AND_NULL(old_branch_info
.path
);
1133 if (old_branch_info
.path
) {
1134 const char *const prefix
= "refs/heads/";
1136 if (skip_prefix(old_branch_info
.path
, prefix
, &p
))
1137 old_branch_info
.name
= xstrdup(p
);
1140 if (opts
->new_orphan_branch
&& opts
->orphan_from_empty_tree
) {
1141 if (new_branch_info
->name
)
1142 BUG("'switch --orphan' should never accept a commit as starting point");
1143 new_branch_info
->commit
= NULL
;
1144 new_branch_info
->name
= xstrdup("(empty)");
1148 if (!new_branch_info
->name
) {
1149 new_branch_info
->name
= xstrdup("HEAD");
1150 new_branch_info
->commit
= old_branch_info
.commit
;
1151 if (!new_branch_info
->commit
)
1152 die(_("You are on a branch yet to be born"));
1153 parse_commit_or_die(new_branch_info
->commit
);
1155 if (opts
->only_merge_on_switching_branches
)
1160 ret
= merge_working_tree(opts
, &old_branch_info
, new_branch_info
, &writeout_error
);
1162 branch_info_release(&old_branch_info
);
1167 if (!opts
->quiet
&& !old_branch_info
.path
&& old_branch_info
.commit
&& new_branch_info
->commit
!= old_branch_info
.commit
)
1168 orphaned_commit_warning(old_branch_info
.commit
, new_branch_info
->commit
);
1170 update_refs_for_switch(opts
, &old_branch_info
, new_branch_info
);
1172 ret
= post_checkout_hook(old_branch_info
.commit
, new_branch_info
->commit
, 1);
1173 branch_info_release(&old_branch_info
);
1175 return ret
|| writeout_error
;
1178 static int git_checkout_config(const char *var
, const char *value
, void *cb
)
1180 struct checkout_opts
*opts
= cb
;
1182 if (!strcmp(var
, "diff.ignoresubmodules")) {
1183 handle_ignore_submodules_arg(&opts
->diff_options
, value
);
1186 if (!strcmp(var
, "checkout.guess")) {
1187 opts
->dwim_new_local_branch
= git_config_bool(var
, value
);
1191 if (starts_with(var
, "submodule."))
1192 return git_default_submodule_config(var
, value
, NULL
);
1194 return git_xmerge_config(var
, value
, NULL
);
1197 static void setup_new_branch_info_and_source_tree(
1198 struct branch_info
*new_branch_info
,
1199 struct checkout_opts
*opts
,
1200 struct object_id
*rev
,
1203 struct tree
**source_tree
= &opts
->source_tree
;
1204 struct object_id branch_rev
;
1206 new_branch_info
->name
= xstrdup(arg
);
1207 setup_branch_path(new_branch_info
);
1209 if (!check_refname_format(new_branch_info
->path
, 0) &&
1210 !read_ref(new_branch_info
->path
, &branch_rev
))
1211 oidcpy(rev
, &branch_rev
);
1213 /* not an existing branch */
1214 FREE_AND_NULL(new_branch_info
->path
);
1216 new_branch_info
->commit
= lookup_commit_reference_gently(the_repository
, rev
, 1);
1217 if (!new_branch_info
->commit
) {
1219 *source_tree
= parse_tree_indirect(rev
);
1221 parse_commit_or_die(new_branch_info
->commit
);
1222 *source_tree
= get_commit_tree(new_branch_info
->commit
);
1226 static const char *parse_remote_branch(const char *arg
,
1227 struct object_id
*rev
,
1228 int could_be_checkout_paths
)
1230 int num_matches
= 0;
1231 const char *remote
= unique_tracking_name(arg
, rev
, &num_matches
);
1233 if (remote
&& could_be_checkout_paths
) {
1234 die(_("'%s' could be both a local file and a tracking branch.\n"
1235 "Please use -- (and optionally --no-guess) to disambiguate"),
1239 if (!remote
&& num_matches
> 1) {
1240 if (advice_enabled(ADVICE_CHECKOUT_AMBIGUOUS_REMOTE_BRANCH_NAME
)) {
1241 advise(_("If you meant to check out a remote tracking branch on, e.g. 'origin',\n"
1242 "you can do so by fully qualifying the name with the --track option:\n"
1244 " git checkout --track origin/<name>\n"
1246 "If you'd like to always have checkouts of an ambiguous <name> prefer\n"
1247 "one remote, e.g. the 'origin' remote, consider setting\n"
1248 "checkout.defaultRemote=origin in your config."));
1251 die(_("'%s' matched multiple (%d) remote tracking branches"),
1258 static int parse_branchname_arg(int argc
, const char **argv
,
1259 int dwim_new_local_branch_ok
,
1260 struct branch_info
*new_branch_info
,
1261 struct checkout_opts
*opts
,
1262 struct object_id
*rev
)
1264 const char **new_branch
= &opts
->new_branch
;
1268 int has_dash_dash
= 0;
1272 * case 1: git checkout <ref> -- [<paths>]
1274 * <ref> must be a valid tree, everything after the '--' must be
1277 * case 2: git checkout -- [<paths>]
1279 * everything after the '--' must be paths.
1281 * case 3: git checkout <something> [--]
1283 * (a) If <something> is a commit, that is to
1284 * switch to the branch or detach HEAD at it. As a special case,
1285 * if <something> is A...B (missing A or B means HEAD but you can
1286 * omit at most one side), and if there is a unique merge base
1287 * between A and B, A...B names that merge base.
1289 * (b) If <something> is _not_ a commit, either "--" is present
1290 * or <something> is not a path, no -t or -b was given,
1291 * and there is a tracking branch whose name is <something>
1292 * in one and only one remote (or if the branch exists on the
1293 * remote named in checkout.defaultRemote), then this is a
1294 * short-hand to fork local <something> from that
1295 * remote-tracking branch.
1297 * (c) Otherwise, if "--" is present, treat it like case (1).
1300 * - if it's a reference, treat it like case (1)
1301 * - else if it's a path, treat it like case (2)
1304 * case 4: git checkout <something> <paths>
1306 * The first argument must not be ambiguous.
1307 * - If it's *only* a reference, treat it like case (1).
1308 * - If it's only a path, treat it like case (2).
1315 if (!opts
->accept_pathspec
) {
1317 die(_("only one reference expected"));
1318 has_dash_dash
= 1; /* helps disambiguate */
1323 for (i
= 0; i
< argc
; i
++) {
1324 if (opts
->accept_pathspec
&& !strcmp(argv
[i
], "--")) {
1329 if (dash_dash_pos
== 0)
1330 return 1; /* case (2) */
1331 else if (dash_dash_pos
== 1)
1332 has_dash_dash
= 1; /* case (3) or (1) */
1333 else if (dash_dash_pos
>= 2)
1334 die(_("only one reference expected, %d given."), dash_dash_pos
);
1335 opts
->count_checkout_paths
= !opts
->quiet
&& !has_dash_dash
;
1337 if (!strcmp(arg
, "-"))
1340 if (get_oid_mb(arg
, rev
)) {
1342 * Either case (3) or (4), with <something> not being
1343 * a commit, or an attempt to use case (1) with an
1346 * It's likely an error, but we need to find out if
1347 * we should auto-create the branch, case (3).(b).
1349 int recover_with_dwim
= dwim_new_local_branch_ok
;
1351 int could_be_checkout_paths
= !has_dash_dash
&&
1352 check_filename(opts
->prefix
, arg
);
1354 if (!has_dash_dash
&& !no_wildcard(arg
))
1355 recover_with_dwim
= 0;
1358 * Accept "git checkout foo", "git checkout foo --"
1359 * and "git switch foo" as candidates for dwim.
1361 if (!(argc
== 1 && !has_dash_dash
) &&
1362 !(argc
== 2 && has_dash_dash
) &&
1363 opts
->accept_pathspec
)
1364 recover_with_dwim
= 0;
1366 if (recover_with_dwim
) {
1367 const char *remote
= parse_remote_branch(arg
, rev
,
1368 could_be_checkout_paths
);
1372 /* DWIMmed to create local branch, case (3).(b) */
1374 recover_with_dwim
= 0;
1378 if (!recover_with_dwim
) {
1380 die(_("invalid reference: %s"), arg
);
1385 /* we can't end up being in (2) anymore, eat the argument */
1390 setup_new_branch_info_and_source_tree(new_branch_info
, opts
, rev
, arg
);
1392 if (!opts
->source_tree
) /* case (1): want a tree */
1393 die(_("reference is not a tree: %s"), arg
);
1395 if (!has_dash_dash
) { /* case (3).(d) -> (1) */
1397 * Do not complain the most common case
1398 * git checkout branch
1399 * even if there happen to be a file called 'branch';
1400 * it would be extremely annoying.
1403 verify_non_filename(opts
->prefix
, arg
);
1404 } else if (opts
->accept_pathspec
) {
1413 static int switch_unborn_to_new_branch(const struct checkout_opts
*opts
)
1416 struct strbuf branch_ref
= STRBUF_INIT
;
1418 trace2_cmd_mode("unborn");
1420 if (!opts
->new_branch
)
1421 die(_("You are on a branch yet to be born"));
1422 strbuf_addf(&branch_ref
, "refs/heads/%s", opts
->new_branch
);
1423 status
= create_symref("HEAD", branch_ref
.buf
, "checkout -b");
1424 strbuf_release(&branch_ref
);
1426 fprintf(stderr
, _("Switched to a new branch '%s'\n"),
1431 static void die_expecting_a_branch(const struct branch_info
*branch_info
)
1433 struct object_id oid
;
1437 if (dwim_ref(branch_info
->name
, strlen(branch_info
->name
), &oid
, &to_free
, 0) == 1) {
1438 const char *ref
= to_free
;
1440 if (skip_prefix(ref
, "refs/tags/", &ref
))
1441 code
= die_message(_("a branch is expected, got tag '%s'"), ref
);
1442 else if (skip_prefix(ref
, "refs/remotes/", &ref
))
1443 code
= die_message(_("a branch is expected, got remote branch '%s'"), ref
);
1445 code
= die_message(_("a branch is expected, got '%s'"), ref
);
1447 else if (branch_info
->commit
)
1448 code
= die_message(_("a branch is expected, got commit '%s'"), branch_info
->name
);
1451 * This case should never happen because we already die() on
1452 * non-commit, but just in case.
1454 code
= die_message(_("a branch is expected, got '%s'"), branch_info
->name
);
1456 if (advice_enabled(ADVICE_SUGGEST_DETACHING_HEAD
))
1457 advise(_("If you want to detach HEAD at the commit, try again with the --detach option."));
1462 static void die_if_some_operation_in_progress(void)
1464 struct wt_status_state state
;
1466 memset(&state
, 0, sizeof(state
));
1467 wt_status_get_state(the_repository
, &state
, 0);
1469 if (state
.merge_in_progress
)
1470 die(_("cannot switch branch while merging\n"
1471 "Consider \"git merge --quit\" "
1472 "or \"git worktree add\"."));
1473 if (state
.am_in_progress
)
1474 die(_("cannot switch branch in the middle of an am session\n"
1475 "Consider \"git am --quit\" "
1476 "or \"git worktree add\"."));
1477 if (state
.rebase_interactive_in_progress
|| state
.rebase_in_progress
)
1478 die(_("cannot switch branch while rebasing\n"
1479 "Consider \"git rebase --quit\" "
1480 "or \"git worktree add\"."));
1481 if (state
.cherry_pick_in_progress
)
1482 die(_("cannot switch branch while cherry-picking\n"
1483 "Consider \"git cherry-pick --quit\" "
1484 "or \"git worktree add\"."));
1485 if (state
.revert_in_progress
)
1486 die(_("cannot switch branch while reverting\n"
1487 "Consider \"git revert --quit\" "
1488 "or \"git worktree add\"."));
1489 if (state
.bisect_in_progress
)
1490 warning(_("you are switching branch while bisecting"));
1492 wt_status_state_free_buffers(&state
);
1495 static int checkout_branch(struct checkout_opts
*opts
,
1496 struct branch_info
*new_branch_info
)
1498 if (opts
->pathspec
.nr
)
1499 die(_("paths cannot be used with switching branches"));
1501 if (opts
->patch_mode
)
1502 die(_("'%s' cannot be used with switching branches"),
1505 if (opts
->overlay_mode
!= -1)
1506 die(_("'%s' cannot be used with switching branches"),
1509 if (opts
->writeout_stage
)
1510 die(_("'%s' cannot be used with switching branches"),
1513 if (opts
->force
&& opts
->merge
)
1514 die(_("'%s' cannot be used with '%s'"), "-f", "-m");
1516 if (opts
->discard_changes
&& opts
->merge
)
1517 die(_("'%s' cannot be used with '%s'"), "--discard-changes", "--merge");
1519 if (opts
->force_detach
&& opts
->new_branch
)
1520 die(_("'%s' cannot be used with '%s'"),
1521 "--detach", "-b/-B/--orphan");
1523 if (opts
->new_orphan_branch
) {
1524 if (opts
->track
!= BRANCH_TRACK_UNSPECIFIED
)
1525 die(_("'%s' cannot be used with '%s'"), "--orphan", "-t");
1526 if (opts
->orphan_from_empty_tree
&& new_branch_info
->name
)
1527 die(_("'%s' cannot take <start-point>"), "--orphan");
1528 } else if (opts
->force_detach
) {
1529 if (opts
->track
!= BRANCH_TRACK_UNSPECIFIED
)
1530 die(_("'%s' cannot be used with '%s'"), "--detach", "-t");
1531 } else if (opts
->track
== BRANCH_TRACK_UNSPECIFIED
)
1532 opts
->track
= git_branch_track
;
1534 if (new_branch_info
->name
&& !new_branch_info
->commit
)
1535 die(_("Cannot switch branch to a non-commit '%s'"),
1536 new_branch_info
->name
);
1538 if (!opts
->switch_branch_doing_nothing_is_ok
&&
1539 !new_branch_info
->name
&&
1540 !opts
->new_branch
&&
1541 !opts
->force_detach
)
1542 die(_("missing branch or commit argument"));
1544 if (!opts
->implicit_detach
&&
1545 !opts
->force_detach
&&
1546 !opts
->new_branch
&&
1547 !opts
->new_branch_force
&&
1548 new_branch_info
->name
&&
1549 !new_branch_info
->path
)
1550 die_expecting_a_branch(new_branch_info
);
1552 if (!opts
->can_switch_when_in_progress
)
1553 die_if_some_operation_in_progress();
1555 if (new_branch_info
->path
&& !opts
->force_detach
&& !opts
->new_branch
&&
1556 !opts
->ignore_other_worktrees
) {
1558 char *head_ref
= resolve_refdup("HEAD", 0, NULL
, &flag
);
1560 (!(flag
& REF_ISSYMREF
) || strcmp(head_ref
, new_branch_info
->path
)))
1561 die_if_checked_out(new_branch_info
->path
, 1);
1565 if (!new_branch_info
->commit
&& opts
->new_branch
) {
1566 struct object_id rev
;
1569 if (!read_ref_full("HEAD", 0, &rev
, &flag
) &&
1570 (flag
& REF_ISSYMREF
) && is_null_oid(&rev
))
1571 return switch_unborn_to_new_branch(opts
);
1573 return switch_branches(opts
, new_branch_info
);
1576 static struct option
*add_common_options(struct checkout_opts
*opts
,
1577 struct option
*prevopts
)
1579 struct option options
[] = {
1580 OPT__QUIET(&opts
->quiet
, N_("suppress progress reporting")),
1581 OPT_CALLBACK_F(0, "recurse-submodules", NULL
,
1582 "checkout", "control recursive updating of submodules",
1583 PARSE_OPT_OPTARG
, option_parse_recurse_submodules_worktree_updater
),
1584 OPT_BOOL(0, "progress", &opts
->show_progress
, N_("force progress reporting")),
1585 OPT_BOOL('m', "merge", &opts
->merge
, N_("perform a 3-way merge with the new branch")),
1586 OPT_STRING(0, "conflict", &opts
->conflict_style
, N_("style"),
1587 N_("conflict style (merge, diff3, or zdiff3)")),
1590 struct option
*newopts
= parse_options_concat(prevopts
, options
);
1595 static struct option
*add_common_switch_branch_options(
1596 struct checkout_opts
*opts
, struct option
*prevopts
)
1598 struct option options
[] = {
1599 OPT_BOOL('d', "detach", &opts
->force_detach
, N_("detach HEAD at named commit")),
1600 OPT_CALLBACK_F('t', "track", &opts
->track
, "(direct|inherit)",
1601 N_("set branch tracking configuration"),
1603 parse_opt_tracking_mode
),
1604 OPT__FORCE(&opts
->force
, N_("force checkout (throw away local modifications)"),
1605 PARSE_OPT_NOCOMPLETE
),
1606 OPT_STRING(0, "orphan", &opts
->new_orphan_branch
, N_("new-branch"), N_("new unparented branch")),
1607 OPT_BOOL_F(0, "overwrite-ignore", &opts
->overwrite_ignore
,
1608 N_("update ignored files (default)"),
1609 PARSE_OPT_NOCOMPLETE
),
1610 OPT_BOOL(0, "ignore-other-worktrees", &opts
->ignore_other_worktrees
,
1611 N_("do not check if another worktree is holding the given ref")),
1614 struct option
*newopts
= parse_options_concat(prevopts
, options
);
1619 static struct option
*add_checkout_path_options(struct checkout_opts
*opts
,
1620 struct option
*prevopts
)
1622 struct option options
[] = {
1623 OPT_SET_INT_F('2', "ours", &opts
->writeout_stage
,
1624 N_("checkout our version for unmerged files"),
1625 2, PARSE_OPT_NONEG
),
1626 OPT_SET_INT_F('3', "theirs", &opts
->writeout_stage
,
1627 N_("checkout their version for unmerged files"),
1628 3, PARSE_OPT_NONEG
),
1629 OPT_BOOL('p', "patch", &opts
->patch_mode
, N_("select hunks interactively")),
1630 OPT_BOOL(0, "ignore-skip-worktree-bits", &opts
->ignore_skipworktree
,
1631 N_("do not limit pathspecs to sparse entries only")),
1632 OPT_PATHSPEC_FROM_FILE(&opts
->pathspec_from_file
),
1633 OPT_PATHSPEC_FILE_NUL(&opts
->pathspec_file_nul
),
1636 struct option
*newopts
= parse_options_concat(prevopts
, options
);
1641 /* create-branch option (either b or c) */
1642 static char cb_option
= 'b';
1644 static int checkout_main(int argc
, const char **argv
, const char *prefix
,
1645 struct checkout_opts
*opts
, struct option
*options
,
1646 const char * const usagestr
[],
1647 struct branch_info
*new_branch_info
)
1649 int parseopt_flags
= 0;
1651 opts
->overwrite_ignore
= 1;
1652 opts
->prefix
= prefix
;
1653 opts
->show_progress
= -1;
1655 git_config(git_checkout_config
, opts
);
1656 if (the_repository
->gitdir
) {
1657 prepare_repo_settings(the_repository
);
1658 the_repository
->settings
.command_requires_full_index
= 0;
1661 opts
->track
= BRANCH_TRACK_UNSPECIFIED
;
1663 if (!opts
->accept_pathspec
&& !opts
->accept_ref
)
1664 BUG("make up your mind, you need to take _something_");
1665 if (opts
->accept_pathspec
&& opts
->accept_ref
)
1666 parseopt_flags
= PARSE_OPT_KEEP_DASHDASH
;
1668 argc
= parse_options(argc
, argv
, prefix
, options
,
1669 usagestr
, parseopt_flags
);
1671 if (opts
->show_progress
< 0) {
1673 opts
->show_progress
= 0;
1675 opts
->show_progress
= isatty(2);
1678 if (opts
->conflict_style
) {
1679 opts
->merge
= 1; /* implied */
1680 git_xmerge_config("merge.conflictstyle", opts
->conflict_style
, NULL
);
1683 opts
->discard_changes
= 1;
1684 opts
->ignore_unmerged_opt
= "--force";
1685 opts
->ignore_unmerged
= 1;
1688 if ((!!opts
->new_branch
+ !!opts
->new_branch_force
+ !!opts
->new_orphan_branch
) > 1)
1689 die(_("options '-%c', '-%c', and '%s' cannot be used together"),
1690 cb_option
, toupper(cb_option
), "--orphan");
1692 if (opts
->overlay_mode
== 1 && opts
->patch_mode
)
1693 die(_("options '%s' and '%s' cannot be used together"), "-p", "--overlay");
1695 if (opts
->checkout_index
>= 0 || opts
->checkout_worktree
>= 0) {
1696 if (opts
->checkout_index
< 0)
1697 opts
->checkout_index
= 0;
1698 if (opts
->checkout_worktree
< 0)
1699 opts
->checkout_worktree
= 0;
1701 if (opts
->checkout_index
< 0)
1702 opts
->checkout_index
= -opts
->checkout_index
- 1;
1703 if (opts
->checkout_worktree
< 0)
1704 opts
->checkout_worktree
= -opts
->checkout_worktree
- 1;
1706 if (opts
->checkout_index
< 0 || opts
->checkout_worktree
< 0)
1707 BUG("these flags should be non-negative by now");
1709 * convenient shortcut: "git restore --staged [--worktree]" equals
1710 * "git restore --staged [--worktree] --source HEAD"
1712 if (!opts
->from_treeish
&& opts
->checkout_index
)
1713 opts
->from_treeish
= "HEAD";
1716 * From here on, new_branch will contain the branch to be checked out,
1717 * and new_branch_force and new_orphan_branch will tell us which one of
1718 * -b/-B/-c/-C/--orphan is being used.
1720 if (opts
->new_branch_force
)
1721 opts
->new_branch
= opts
->new_branch_force
;
1723 if (opts
->new_orphan_branch
)
1724 opts
->new_branch
= opts
->new_orphan_branch
;
1726 /* --track without -c/-C/-b/-B/--orphan should DWIM */
1727 if (opts
->track
!= BRANCH_TRACK_UNSPECIFIED
&& !opts
->new_branch
) {
1728 const char *argv0
= argv
[0];
1729 if (!argc
|| !strcmp(argv0
, "--"))
1730 die(_("--track needs a branch name"));
1731 skip_prefix(argv0
, "refs/", &argv0
);
1732 skip_prefix(argv0
, "remotes/", &argv0
);
1733 argv0
= strchr(argv0
, '/');
1734 if (!argv0
|| !argv0
[1])
1735 die(_("missing branch name; try -%c"), cb_option
);
1736 opts
->new_branch
= argv0
+ 1;
1740 * Extract branch name from command line arguments, so
1741 * all that is left is pathspecs.
1745 * 1) git checkout <tree> -- [<paths>]
1746 * 2) git checkout -- [<paths>]
1747 * 3) git checkout <something> [<paths>]
1749 * including "last branch" syntax and DWIM-ery for names of
1750 * remote branches, erroring out for invalid or ambiguous cases.
1752 if (argc
&& opts
->accept_ref
) {
1753 struct object_id rev
;
1755 !opts
->patch_mode
&&
1756 opts
->dwim_new_local_branch
&&
1757 opts
->track
== BRANCH_TRACK_UNSPECIFIED
&&
1759 int n
= parse_branchname_arg(argc
, argv
, dwim_ok
,
1760 new_branch_info
, opts
, &rev
);
1763 } else if (!opts
->accept_ref
&& opts
->from_treeish
) {
1764 struct object_id rev
;
1766 if (get_oid_mb(opts
->from_treeish
, &rev
))
1767 die(_("could not resolve %s"), opts
->from_treeish
);
1769 setup_new_branch_info_and_source_tree(new_branch_info
,
1771 opts
->from_treeish
);
1773 if (!opts
->source_tree
)
1774 die(_("reference is not a tree: %s"), opts
->from_treeish
);
1778 parse_pathspec(&opts
->pathspec
, 0,
1779 opts
->patch_mode
? PATHSPEC_PREFIX_ORIGIN
: 0,
1782 if (!opts
->pathspec
.nr
)
1783 die(_("invalid path specification"));
1786 * Try to give more helpful suggestion.
1787 * new_branch && argc > 1 will be caught later.
1789 if (opts
->new_branch
&& argc
== 1 && !new_branch_info
->commit
)
1790 die(_("'%s' is not a commit and a branch '%s' cannot be created from it"),
1791 argv
[0], opts
->new_branch
);
1793 if (opts
->force_detach
)
1794 die(_("git checkout: --detach does not take a path argument '%s'"),
1798 if (opts
->pathspec_from_file
) {
1799 if (opts
->pathspec
.nr
)
1800 die(_("'%s' and pathspec arguments cannot be used together"), "--pathspec-from-file");
1802 if (opts
->force_detach
)
1803 die(_("options '%s' and '%s' cannot be used together"), "--pathspec-from-file", "--detach");
1805 if (opts
->patch_mode
)
1806 die(_("options '%s' and '%s' cannot be used together"), "--pathspec-from-file", "--patch");
1808 parse_pathspec_file(&opts
->pathspec
, 0,
1810 prefix
, opts
->pathspec_from_file
, opts
->pathspec_file_nul
);
1811 } else if (opts
->pathspec_file_nul
) {
1812 die(_("the option '%s' requires '%s'"), "--pathspec-file-nul", "--pathspec-from-file");
1815 opts
->pathspec
.recursive
= 1;
1817 if (opts
->pathspec
.nr
) {
1818 if (1 < !!opts
->writeout_stage
+ !!opts
->force
+ !!opts
->merge
)
1819 die(_("git checkout: --ours/--theirs, --force and --merge are incompatible when\n"
1820 "checking out of the index."));
1822 if (opts
->accept_pathspec
&& !opts
->empty_pathspec_ok
&&
1823 !opts
->patch_mode
) /* patch mode is special */
1824 die(_("you must specify path(s) to restore"));
1827 if (opts
->new_branch
) {
1828 struct strbuf buf
= STRBUF_INIT
;
1830 if (opts
->new_branch_force
)
1831 opts
->branch_exists
= validate_branchname(opts
->new_branch
, &buf
);
1833 opts
->branch_exists
=
1834 validate_new_branchname(opts
->new_branch
, &buf
, 0);
1835 strbuf_release(&buf
);
1838 if (opts
->patch_mode
|| opts
->pathspec
.nr
)
1839 return checkout_paths(opts
, new_branch_info
);
1841 return checkout_branch(opts
, new_branch_info
);
1844 int cmd_checkout(int argc
, const char **argv
, const char *prefix
)
1846 struct checkout_opts opts
;
1847 struct option
*options
;
1848 struct option checkout_options
[] = {
1849 OPT_STRING('b', NULL
, &opts
.new_branch
, N_("branch"),
1850 N_("create and checkout a new branch")),
1851 OPT_STRING('B', NULL
, &opts
.new_branch_force
, N_("branch"),
1852 N_("create/reset and checkout a branch")),
1853 OPT_BOOL('l', NULL
, &opts
.new_branch_log
, N_("create reflog for new branch")),
1854 OPT_BOOL(0, "guess", &opts
.dwim_new_local_branch
,
1855 N_("second guess 'git checkout <no-such-branch>' (default)")),
1856 OPT_BOOL(0, "overlay", &opts
.overlay_mode
, N_("use overlay mode (default)")),
1860 struct branch_info new_branch_info
= { 0 };
1862 memset(&opts
, 0, sizeof(opts
));
1863 opts
.dwim_new_local_branch
= 1;
1864 opts
.switch_branch_doing_nothing_is_ok
= 1;
1865 opts
.only_merge_on_switching_branches
= 0;
1866 opts
.accept_ref
= 1;
1867 opts
.accept_pathspec
= 1;
1868 opts
.implicit_detach
= 1;
1869 opts
.can_switch_when_in_progress
= 1;
1870 opts
.orphan_from_empty_tree
= 0;
1871 opts
.empty_pathspec_ok
= 1;
1872 opts
.overlay_mode
= -1;
1873 opts
.checkout_index
= -2; /* default on */
1874 opts
.checkout_worktree
= -2; /* default on */
1876 if (argc
== 3 && !strcmp(argv
[1], "-b")) {
1878 * User ran 'git checkout -b <branch>' and expects
1879 * the same behavior as 'git switch -c <branch>'.
1881 opts
.switch_branch_doing_nothing_is_ok
= 0;
1882 opts
.only_merge_on_switching_branches
= 1;
1885 options
= parse_options_dup(checkout_options
);
1886 options
= add_common_options(&opts
, options
);
1887 options
= add_common_switch_branch_options(&opts
, options
);
1888 options
= add_checkout_path_options(&opts
, options
);
1890 ret
= checkout_main(argc
, argv
, prefix
, &opts
,
1891 options
, checkout_usage
, &new_branch_info
);
1892 branch_info_release(&new_branch_info
);
1893 clear_pathspec(&opts
.pathspec
);
1894 free(opts
.pathspec_from_file
);
1895 FREE_AND_NULL(options
);
1899 int cmd_switch(int argc
, const char **argv
, const char *prefix
)
1901 struct checkout_opts opts
;
1902 struct option
*options
= NULL
;
1903 struct option switch_options
[] = {
1904 OPT_STRING('c', "create", &opts
.new_branch
, N_("branch"),
1905 N_("create and switch to a new branch")),
1906 OPT_STRING('C', "force-create", &opts
.new_branch_force
, N_("branch"),
1907 N_("create/reset and switch to a branch")),
1908 OPT_BOOL(0, "guess", &opts
.dwim_new_local_branch
,
1909 N_("second guess 'git switch <no-such-branch>'")),
1910 OPT_BOOL(0, "discard-changes", &opts
.discard_changes
,
1911 N_("throw away local modifications")),
1915 struct branch_info new_branch_info
= { 0 };
1917 memset(&opts
, 0, sizeof(opts
));
1918 opts
.dwim_new_local_branch
= 1;
1919 opts
.accept_ref
= 1;
1920 opts
.accept_pathspec
= 0;
1921 opts
.switch_branch_doing_nothing_is_ok
= 0;
1922 opts
.only_merge_on_switching_branches
= 1;
1923 opts
.implicit_detach
= 0;
1924 opts
.can_switch_when_in_progress
= 0;
1925 opts
.orphan_from_empty_tree
= 1;
1926 opts
.overlay_mode
= -1;
1928 options
= parse_options_dup(switch_options
);
1929 options
= add_common_options(&opts
, options
);
1930 options
= add_common_switch_branch_options(&opts
, options
);
1934 ret
= checkout_main(argc
, argv
, prefix
, &opts
,
1935 options
, switch_branch_usage
, &new_branch_info
);
1936 branch_info_release(&new_branch_info
);
1937 FREE_AND_NULL(options
);
1941 int cmd_restore(int argc
, const char **argv
, const char *prefix
)
1943 struct checkout_opts opts
;
1944 struct option
*options
;
1945 struct option restore_options
[] = {
1946 OPT_STRING('s', "source", &opts
.from_treeish
, "<tree-ish>",
1947 N_("which tree-ish to checkout from")),
1948 OPT_BOOL('S', "staged", &opts
.checkout_index
,
1949 N_("restore the index")),
1950 OPT_BOOL('W', "worktree", &opts
.checkout_worktree
,
1951 N_("restore the working tree (default)")),
1952 OPT_BOOL(0, "ignore-unmerged", &opts
.ignore_unmerged
,
1953 N_("ignore unmerged entries")),
1954 OPT_BOOL(0, "overlay", &opts
.overlay_mode
, N_("use overlay mode")),
1958 struct branch_info new_branch_info
= { 0 };
1960 memset(&opts
, 0, sizeof(opts
));
1961 opts
.accept_ref
= 0;
1962 opts
.accept_pathspec
= 1;
1963 opts
.empty_pathspec_ok
= 0;
1964 opts
.overlay_mode
= 0;
1965 opts
.checkout_index
= -1; /* default off */
1966 opts
.checkout_worktree
= -2; /* default on */
1967 opts
.ignore_unmerged_opt
= "--ignore-unmerged";
1969 options
= parse_options_dup(restore_options
);
1970 options
= add_common_options(&opts
, options
);
1971 options
= add_checkout_path_options(&opts
, options
);
1973 ret
= checkout_main(argc
, argv
, prefix
, &opts
,
1974 options
, restore_usage
, &new_branch_info
);
1975 branch_info_release(&new_branch_info
);
1976 FREE_AND_NULL(options
);