4 #include "cache-tree.h"
10 #include "environment.h"
17 #include "merge-recursive.h"
18 #include "object-name.h"
19 #include "object-store-ll.h"
20 #include "parse-options.h"
22 #include "preload-index.h"
23 #include "read-cache.h"
26 #include "resolve-undo.h"
29 #include "submodule.h"
33 #include "tree-walk.h"
34 #include "unpack-trees.h"
35 #include "wt-status.h"
36 #include "xdiff-interface.h"
38 #include "parallel-checkout.h"
39 #include "add-interactive.h"
41 static const char * const checkout_usage
[] = {
42 N_("git checkout [<options>] <branch>"),
43 N_("git checkout [<options>] [<branch>] -- <file>..."),
47 static const char * const switch_branch_usage
[] = {
48 N_("git switch [<options>] [<branch>]"),
52 static const char * const restore_usage
[] = {
53 N_("git restore [<options>] [--source=<branch>] <file>..."),
57 struct checkout_opts
{
66 int ignore_skipworktree
;
67 int ignore_other_worktrees
;
69 int count_checkout_paths
;
71 int dwim_new_local_branch
;
75 int switch_branch_doing_nothing_is_ok
;
76 int only_merge_on_switching_branches
;
77 int can_switch_when_in_progress
;
78 int orphan_from_empty_tree
;
79 int empty_pathspec_ok
;
81 int checkout_worktree
;
82 const char *ignore_unmerged_opt
;
84 int pathspec_file_nul
;
85 char *pathspec_from_file
;
87 const char *new_branch
;
88 const char *new_branch_force
;
89 const char *new_orphan_branch
;
91 enum branch_track track
;
92 struct diff_options diff_options
;
97 struct pathspec pathspec
;
98 const char *from_treeish
;
99 struct tree
*source_tree
;
102 #define CHECKOUT_OPTS_INIT { .conflict_style = -1, .merge = -1 }
105 char *name
; /* The short name used */
106 char *path
; /* The full name of a real branch */
107 struct commit
*commit
; /* The named commit */
108 char *refname
; /* The full name of the ref being checked out. */
109 struct object_id oid
; /* The object ID of the commit being checked out. */
111 * if not null the branch is detached because it's already
112 * checked out in this checkout
117 static void branch_info_release(struct branch_info
*info
)
122 free(info
->checkout
);
125 static int post_checkout_hook(struct commit
*old_commit
, struct commit
*new_commit
,
128 return run_hooks_l("post-checkout",
129 oid_to_hex(old_commit
? &old_commit
->object
.oid
: null_oid()),
130 oid_to_hex(new_commit
? &new_commit
->object
.oid
: null_oid()),
131 changed
? "1" : "0", NULL
);
132 /* "new_commit" can be NULL when checking out from the index before
137 static int update_some(const struct object_id
*oid
, struct strbuf
*base
,
138 const char *pathname
, unsigned mode
, void *context UNUSED
)
141 struct cache_entry
*ce
;
145 return READ_TREE_RECURSIVE
;
147 len
= base
->len
+ strlen(pathname
);
148 ce
= make_empty_cache_entry(the_repository
->index
, len
);
149 oidcpy(&ce
->oid
, oid
);
150 memcpy(ce
->name
, base
->buf
, base
->len
);
151 memcpy(ce
->name
+ base
->len
, pathname
, len
- base
->len
);
152 ce
->ce_flags
= create_ce_flags(0) | CE_UPDATE
;
153 ce
->ce_namelen
= len
;
154 ce
->ce_mode
= create_ce_mode(mode
);
157 * If the entry is the same as the current index, we can leave the old
158 * entry in place. Whether it is UPTODATE or not, checkout_entry will
159 * do the right thing.
161 pos
= index_name_pos(the_repository
->index
, ce
->name
, ce
->ce_namelen
);
163 struct cache_entry
*old
= the_repository
->index
->cache
[pos
];
164 if (ce
->ce_mode
== old
->ce_mode
&&
165 !ce_intent_to_add(old
) &&
166 oideq(&ce
->oid
, &old
->oid
)) {
167 old
->ce_flags
|= CE_UPDATE
;
168 discard_cache_entry(ce
);
173 add_index_entry(the_repository
->index
, ce
,
174 ADD_CACHE_OK_TO_ADD
| ADD_CACHE_OK_TO_REPLACE
);
178 static int read_tree_some(struct tree
*tree
, const struct pathspec
*pathspec
)
180 read_tree(the_repository
, tree
,
181 pathspec
, update_some
, NULL
);
183 /* update the index with the given tree's info
184 * for all args, expanding wildcards, and exit
185 * with any non-zero return code.
190 static int skip_same_name(const struct cache_entry
*ce
, int pos
)
192 while (++pos
< the_repository
->index
->cache_nr
&&
193 !strcmp(the_repository
->index
->cache
[pos
]->name
, ce
->name
))
198 static int check_stage(int stage
, const struct cache_entry
*ce
, int pos
,
201 while (pos
< the_repository
->index
->cache_nr
&&
202 !strcmp(the_repository
->index
->cache
[pos
]->name
, ce
->name
)) {
203 if (ce_stage(the_repository
->index
->cache
[pos
]) == stage
)
210 return error(_("path '%s' does not have our version"), ce
->name
);
212 return error(_("path '%s' does not have their version"), ce
->name
);
215 static int check_stages(unsigned stages
, const struct cache_entry
*ce
, int pos
)
218 const char *name
= ce
->name
;
220 while (pos
< the_repository
->index
->cache_nr
) {
221 ce
= the_repository
->index
->cache
[pos
];
222 if (strcmp(name
, ce
->name
))
224 seen
|= (1 << ce_stage(ce
));
227 if ((stages
& seen
) != stages
)
228 return error(_("path '%s' does not have all necessary versions"),
233 static int checkout_stage(int stage
, const struct cache_entry
*ce
, int pos
,
234 const struct checkout
*state
, int *nr_checkouts
,
237 while (pos
< the_repository
->index
->cache_nr
&&
238 !strcmp(the_repository
->index
->cache
[pos
]->name
, ce
->name
)) {
239 if (ce_stage(the_repository
->index
->cache
[pos
]) == stage
)
240 return checkout_entry(the_repository
->index
->cache
[pos
], state
,
245 unlink_entry(ce
, NULL
);
249 return error(_("path '%s' does not have our version"), ce
->name
);
251 return error(_("path '%s' does not have their version"), ce
->name
);
254 static int checkout_merged(int pos
, const struct checkout
*state
,
255 int *nr_checkouts
, struct mem_pool
*ce_mem_pool
,
258 struct cache_entry
*ce
= the_repository
->index
->cache
[pos
];
259 const char *path
= ce
->name
;
260 mmfile_t ancestor
, ours
, theirs
;
261 enum ll_merge_result merge_status
;
263 struct object_id oid
;
264 mmbuffer_t result_buf
;
265 struct object_id threeway
[3];
267 struct ll_merge_options ll_opts
= LL_MERGE_OPTIONS_INIT
;
270 memset(threeway
, 0, sizeof(threeway
));
271 while (pos
< the_repository
->index
->cache_nr
) {
273 stage
= ce_stage(ce
);
274 if (!stage
|| strcmp(path
, ce
->name
))
276 oidcpy(&threeway
[stage
- 1], &ce
->oid
);
278 mode
= create_ce_mode(ce
->ce_mode
);
280 ce
= the_repository
->index
->cache
[pos
];
282 if (is_null_oid(&threeway
[1]) || is_null_oid(&threeway
[2]))
283 return error(_("path '%s' does not have necessary versions"), path
);
285 read_mmblob(&ancestor
, &threeway
[0]);
286 read_mmblob(&ours
, &threeway
[1]);
287 read_mmblob(&theirs
, &threeway
[2]);
289 git_config_get_bool("merge.renormalize", &renormalize
);
290 ll_opts
.renormalize
= renormalize
;
291 ll_opts
.conflict_style
= conflict_style
;
292 merge_status
= ll_merge(&result_buf
, path
, &ancestor
, "base",
293 &ours
, "ours", &theirs
, "theirs",
294 state
->istate
, &ll_opts
);
298 if (merge_status
== LL_MERGE_BINARY_CONFLICT
)
299 warning("Cannot merge binary files: %s (%s vs. %s)",
300 path
, "ours", "theirs");
301 if (merge_status
< 0 || !result_buf
.ptr
) {
302 free(result_buf
.ptr
);
303 return error(_("path '%s': cannot merge"), path
);
308 * There is absolutely no reason to write this as a blob object
309 * and create a phony cache entry. This hack is primarily to get
310 * to the write_entry() machinery that massages the contents to
311 * work-tree format and writes out which only allows it for a
312 * cache entry. The code in write_entry() needs to be refactored
313 * to allow us to feed a <buffer, size, mode> instead of a cache
314 * entry. Such a refactoring would help merge_recursive as well
315 * (it also writes the merge result to the object database even
316 * when it may contain conflicts).
318 if (write_object_file(result_buf
.ptr
, result_buf
.size
, OBJ_BLOB
, &oid
))
319 die(_("Unable to add merge result for '%s'"), path
);
320 free(result_buf
.ptr
);
321 ce
= make_transient_cache_entry(mode
, &oid
, path
, 2, ce_mem_pool
);
323 die(_("make_cache_entry failed for path '%s'"), path
);
324 status
= checkout_entry(ce
, state
, NULL
, nr_checkouts
);
328 static void mark_ce_for_checkout_overlay(struct cache_entry
*ce
,
330 const struct checkout_opts
*opts
)
332 ce
->ce_flags
&= ~CE_MATCHED
;
333 if (!opts
->ignore_skipworktree
&& ce_skip_worktree(ce
))
335 if (opts
->source_tree
&& !(ce
->ce_flags
& CE_UPDATE
))
337 * "git checkout tree-ish -- path", but this entry
338 * is in the original index but is not in tree-ish
339 * or does not match the pathspec; it will not be
340 * checked out to the working tree. We will not do
341 * anything to this entry at all.
345 * Either this entry came from the tree-ish we are
346 * checking the paths out of, or we are checking out
349 * If it comes from the tree-ish, we already know it
350 * matches the pathspec and could just stamp
351 * CE_MATCHED to it from update_some(). But we still
352 * need ps_matched and read_tree (and
353 * eventually tree_entry_interesting) cannot fill
354 * ps_matched yet. Once it can, we can avoid calling
355 * match_pathspec() for _all_ entries when
356 * opts->source_tree != NULL.
358 if (ce_path_match(the_repository
->index
, ce
, &opts
->pathspec
, ps_matched
))
359 ce
->ce_flags
|= CE_MATCHED
;
362 static void mark_ce_for_checkout_no_overlay(struct cache_entry
*ce
,
364 const struct checkout_opts
*opts
)
366 ce
->ce_flags
&= ~CE_MATCHED
;
367 if (!opts
->ignore_skipworktree
&& ce_skip_worktree(ce
))
369 if (ce_path_match(the_repository
->index
, ce
, &opts
->pathspec
, ps_matched
)) {
370 ce
->ce_flags
|= CE_MATCHED
;
371 if (opts
->source_tree
&& !(ce
->ce_flags
& CE_UPDATE
))
373 * In overlay mode, but the path is not in
374 * tree-ish, which means we should remove it
375 * from the index and the working tree.
377 ce
->ce_flags
|= CE_REMOVE
| CE_WT_REMOVE
;
381 static int checkout_worktree(const struct checkout_opts
*opts
,
382 const struct branch_info
*info
)
384 struct checkout state
= CHECKOUT_INIT
;
385 int nr_checkouts
= 0, nr_unmerged
= 0;
388 int pc_workers
, pc_threshold
;
389 struct mem_pool ce_mem_pool
;
392 state
.refresh_cache
= 1;
393 state
.istate
= the_repository
->index
;
395 mem_pool_init(&ce_mem_pool
, 0);
396 get_parallel_checkout_configs(&pc_workers
, &pc_threshold
);
397 init_checkout_metadata(&state
.meta
, info
->refname
,
398 info
->commit
? &info
->commit
->object
.oid
: &info
->oid
,
401 enable_delayed_checkout(&state
);
404 init_parallel_checkout();
406 for (pos
= 0; pos
< the_repository
->index
->cache_nr
; pos
++) {
407 struct cache_entry
*ce
= the_repository
->index
->cache
[pos
];
408 if (ce
->ce_flags
& CE_MATCHED
) {
410 errs
|= checkout_entry(ce
, &state
,
411 NULL
, &nr_checkouts
);
414 if (opts
->writeout_stage
)
415 errs
|= checkout_stage(opts
->writeout_stage
,
418 &nr_checkouts
, opts
->overlay_mode
);
419 else if (opts
->merge
)
420 errs
|= checkout_merged(pos
, &state
,
423 opts
->conflict_style
);
424 pos
= skip_same_name(ce
, pos
) - 1;
428 errs
|= run_parallel_checkout(&state
, pc_workers
, pc_threshold
,
430 mem_pool_discard(&ce_mem_pool
, should_validate_cache_entries());
431 remove_marked_cache_entries(the_repository
->index
, 1);
432 remove_scheduled_dirs();
433 errs
|= finish_delayed_checkout(&state
, opts
->show_progress
);
435 if (opts
->count_checkout_paths
) {
437 fprintf_ln(stderr
, Q_("Recreated %d merge conflict",
438 "Recreated %d merge conflicts",
441 if (opts
->source_tree
)
442 fprintf_ln(stderr
, Q_("Updated %d path from %s",
443 "Updated %d paths from %s",
446 repo_find_unique_abbrev(the_repository
, &opts
->source_tree
->object
.oid
,
448 else if (!nr_unmerged
|| nr_checkouts
)
449 fprintf_ln(stderr
, Q_("Updated %d path from the index",
450 "Updated %d paths from the index",
458 static int checkout_paths(const struct checkout_opts
*opts
,
459 const struct branch_info
*new_branch_info
)
462 static char *ps_matched
;
463 struct object_id rev
;
466 struct lock_file lock_file
= LOCK_INIT
;
469 trace2_cmd_mode(opts
->patch_mode
? "patch" : "path");
471 if (opts
->track
!= BRANCH_TRACK_UNSPECIFIED
)
472 die(_("'%s' cannot be used with updating paths"), "--track");
474 if (opts
->new_branch_log
)
475 die(_("'%s' cannot be used with updating paths"), "-l");
477 if (opts
->ignore_unmerged
&& opts
->patch_mode
)
478 die(_("'%s' cannot be used with updating paths"),
479 opts
->ignore_unmerged_opt
);
481 if (opts
->force_detach
)
482 die(_("'%s' cannot be used with updating paths"), "--detach");
484 if (opts
->merge
&& opts
->patch_mode
)
485 die(_("options '%s' and '%s' cannot be used together"), "--merge", "--patch");
487 if (opts
->ignore_unmerged
&& opts
->merge
)
488 die(_("options '%s' and '%s' cannot be used together"),
489 opts
->ignore_unmerged_opt
, "-m");
491 if (opts
->new_branch
)
492 die(_("Cannot update paths and switch to branch '%s' at the same time."),
495 if (!opts
->checkout_worktree
&& !opts
->checkout_index
)
496 die(_("neither '%s' or '%s' is specified"),
497 "--staged", "--worktree");
499 if (!opts
->checkout_worktree
&& !opts
->from_treeish
)
500 die(_("'%s' must be used when '%s' is not specified"),
501 "--worktree", "--source");
504 * Reject --staged option to the restore command when combined with
505 * merge-related options. Use the accept_ref flag to distinguish it
506 * from the checkout command, which does not accept --staged anyway.
508 * `restore --ours|--theirs --worktree --staged` could mean resolving
509 * conflicted paths to one side in both the worktree and the index,
510 * but does not currently.
512 * `restore --merge|--conflict=<style>` already recreates conflicts
513 * in both the worktree and the index, so adding --staged would be
516 if (!opts
->accept_ref
&& opts
->checkout_index
) {
517 if (opts
->writeout_stage
)
518 die(_("'%s' or '%s' cannot be used with %s"),
519 "--ours", "--theirs", "--staged");
522 die(_("'%s' or '%s' cannot be used with %s"),
523 "--merge", "--conflict", "--staged");
527 * recreating unmerged index entries and writing out data from
528 * unmerged index entries would make no sense when checking out
531 if ((opts
->merge
|| opts
->writeout_stage
) && opts
->source_tree
)
532 die(_("'%s', '%s', or '%s' cannot be used when checking out of a tree"),
533 "--merge", "--ours", "--theirs");
535 if (opts
->patch_mode
) {
536 enum add_p_mode patch_mode
;
537 const char *rev
= new_branch_info
->name
;
538 char rev_oid
[GIT_MAX_HEXSZ
+ 1];
541 * Since rev can be in the form of `<a>...<b>` (which is not
542 * recognized by diff-index), we will always replace the name
543 * with the hex of the commit (whether it's in `...` form or
544 * not) for the run_add_interactive() machinery to work
545 * properly. However, there is special logic for the HEAD case
546 * so we mustn't replace that. Also, when we were given a
547 * tree-object, new_branch_info->commit would be NULL, but we
548 * do not have to do any replacement, either.
550 if (rev
&& new_branch_info
->commit
&& strcmp(rev
, "HEAD"))
551 rev
= oid_to_hex_r(rev_oid
, &new_branch_info
->commit
->object
.oid
);
553 if (opts
->checkout_index
&& opts
->checkout_worktree
)
554 patch_mode
= ADD_P_CHECKOUT
;
555 else if (opts
->checkout_index
&& !opts
->checkout_worktree
)
556 patch_mode
= ADD_P_RESET
;
557 else if (!opts
->checkout_index
&& opts
->checkout_worktree
)
558 patch_mode
= ADD_P_WORKTREE
;
560 BUG("either flag must have been set, worktree=%d, index=%d",
561 opts
->checkout_worktree
, opts
->checkout_index
);
562 return !!run_add_p(the_repository
, patch_mode
, rev
,
566 repo_hold_locked_index(the_repository
, &lock_file
, LOCK_DIE_ON_ERROR
);
567 if (repo_read_index_preload(the_repository
, &opts
->pathspec
, 0) < 0)
568 return error(_("index file corrupt"));
570 if (opts
->source_tree
)
571 read_tree_some(opts
->source_tree
, &opts
->pathspec
);
573 unmerge_index(the_repository
->index
, &opts
->pathspec
, CE_MATCHED
);
575 ps_matched
= xcalloc(opts
->pathspec
.nr
, 1);
578 * Make sure all pathspecs participated in locating the paths
581 for (pos
= 0; pos
< the_repository
->index
->cache_nr
; pos
++)
582 if (opts
->overlay_mode
)
583 mark_ce_for_checkout_overlay(the_repository
->index
->cache
[pos
],
587 mark_ce_for_checkout_no_overlay(the_repository
->index
->cache
[pos
],
591 if (report_path_error(ps_matched
, &opts
->pathspec
)) {
597 /* Any unmerged paths? */
598 for (pos
= 0; pos
< the_repository
->index
->cache_nr
; pos
++) {
599 const struct cache_entry
*ce
= the_repository
->index
->cache
[pos
];
600 if (ce
->ce_flags
& CE_MATCHED
) {
603 if (opts
->ignore_unmerged
) {
605 warning(_("path '%s' is unmerged"), ce
->name
);
606 } else if (opts
->writeout_stage
) {
607 errs
|= check_stage(opts
->writeout_stage
, ce
, pos
, opts
->overlay_mode
);
608 } else if (opts
->merge
) {
609 errs
|= check_stages((1<<2) | (1<<3), ce
, pos
);
612 error(_("path '%s' is unmerged"), ce
->name
);
614 pos
= skip_same_name(ce
, pos
) - 1;
620 /* Now we are committed to check them out */
621 if (opts
->checkout_worktree
)
622 errs
|= checkout_worktree(opts
, new_branch_info
);
624 remove_marked_cache_entries(the_repository
->index
, 1);
627 * Allow updating the index when checking out from the index.
628 * This is to save new stat info.
630 if (opts
->checkout_worktree
&& !opts
->checkout_index
&& !opts
->source_tree
)
633 checkout_index
= opts
->checkout_index
;
635 if (checkout_index
) {
636 if (write_locked_index(the_repository
->index
, &lock_file
, COMMIT_LOCK
))
637 die(_("unable to write new index file"));
640 * NEEDSWORK: if --worktree is not specified, we
641 * should save stat info of checked out files in the
642 * index to avoid the next (potentially costly)
643 * refresh. But it's a bit tricker to do...
645 rollback_lock_file(&lock_file
);
648 refs_read_ref_full(get_main_ref_store(the_repository
), "HEAD", 0,
650 head
= lookup_commit_reference_gently(the_repository
, &rev
, 1);
652 errs
|= post_checkout_hook(head
, head
, 0);
656 static void show_local_changes(struct object
*head
,
657 const struct diff_options
*opts
)
660 /* I think we want full paths, even if we're in a subdirectory. */
661 repo_init_revisions(the_repository
, &rev
, NULL
);
662 rev
.diffopt
.flags
= opts
->flags
;
663 rev
.diffopt
.output_format
|= DIFF_FORMAT_NAME_STATUS
;
664 rev
.diffopt
.flags
.recursive
= 1;
665 diff_setup_done(&rev
.diffopt
);
666 add_pending_object(&rev
, head
, NULL
);
667 run_diff_index(&rev
, 0);
668 release_revisions(&rev
);
671 static void describe_detached_head(const char *msg
, struct commit
*commit
)
673 struct strbuf sb
= STRBUF_INIT
;
675 if (!repo_parse_commit(the_repository
, commit
))
676 pp_commit_easy(CMIT_FMT_ONELINE
, commit
, &sb
);
677 if (print_sha1_ellipsis()) {
678 fprintf(stderr
, "%s %s... %s\n", msg
,
679 repo_find_unique_abbrev(the_repository
, &commit
->object
.oid
, DEFAULT_ABBREV
),
682 fprintf(stderr
, "%s %s %s\n", msg
,
683 repo_find_unique_abbrev(the_repository
, &commit
->object
.oid
, DEFAULT_ABBREV
),
689 static int reset_tree(struct tree
*tree
, const struct checkout_opts
*o
,
690 int worktree
, int *writeout_error
,
691 struct branch_info
*info
)
693 struct unpack_trees_options opts
;
694 struct tree_desc tree_desc
;
696 memset(&opts
, 0, sizeof(opts
));
698 opts
.update
= worktree
;
699 opts
.skip_unmerged
= !worktree
;
700 opts
.reset
= o
->force
? UNPACK_RESET_OVERWRITE_UNTRACKED
:
701 UNPACK_RESET_PROTECT_UNTRACKED
;
702 opts
.preserve_ignored
= (!o
->force
&& !o
->overwrite_ignore
);
704 opts
.fn
= oneway_merge
;
705 opts
.verbose_update
= o
->show_progress
;
706 opts
.src_index
= the_repository
->index
;
707 opts
.dst_index
= the_repository
->index
;
708 init_checkout_metadata(&opts
.meta
, info
->refname
,
709 info
->commit
? &info
->commit
->object
.oid
: null_oid(),
711 if (parse_tree(tree
) < 0)
713 init_tree_desc(&tree_desc
, &tree
->object
.oid
, tree
->buffer
, tree
->size
);
714 switch (unpack_trees(1, &tree_desc
, &opts
)) {
718 * We return 0 nevertheless, as the index is all right
719 * and more importantly we have made best efforts to
720 * update paths in the work tree, and we cannot revert
731 static void setup_branch_path(struct branch_info
*branch
)
733 struct strbuf buf
= STRBUF_INIT
;
736 * If this is a ref, resolve it; otherwise, look up the OID for our
737 * expression. Failure here is okay.
739 if (!repo_dwim_ref(the_repository
, branch
->name
, strlen(branch
->name
),
740 &branch
->oid
, &branch
->refname
, 0))
741 repo_get_oid_committish(the_repository
, branch
->name
, &branch
->oid
);
743 strbuf_branchname(&buf
, branch
->name
, INTERPRET_BRANCH_LOCAL
);
744 if (strcmp(buf
.buf
, branch
->name
)) {
746 branch
->name
= xstrdup(buf
.buf
);
748 strbuf_splice(&buf
, 0, 0, "refs/heads/", 11);
750 branch
->path
= strbuf_detach(&buf
, NULL
);
753 static void init_topts(struct unpack_trees_options
*topts
, int merge
,
754 int show_progress
, int overwrite_ignore
,
755 struct commit
*old_commit
)
757 memset(topts
, 0, sizeof(*topts
));
758 topts
->head_idx
= -1;
759 topts
->src_index
= the_repository
->index
;
760 topts
->dst_index
= the_repository
->index
;
762 setup_unpack_trees_porcelain(topts
, "checkout");
764 topts
->initial_checkout
= is_index_unborn(the_repository
->index
);
767 topts
->quiet
= merge
&& old_commit
;
768 topts
->verbose_update
= show_progress
;
769 topts
->fn
= twoway_merge
;
770 topts
->preserve_ignored
= !overwrite_ignore
;
773 static int merge_working_tree(const struct checkout_opts
*opts
,
774 struct branch_info
*old_branch_info
,
775 struct branch_info
*new_branch_info
,
779 struct lock_file lock_file
= LOCK_INIT
;
780 struct tree
*new_tree
;
782 repo_hold_locked_index(the_repository
, &lock_file
, LOCK_DIE_ON_ERROR
);
783 if (repo_read_index_preload(the_repository
, NULL
, 0) < 0)
784 return error(_("index file corrupt"));
786 resolve_undo_clear_index(the_repository
->index
);
787 if (opts
->new_orphan_branch
&& opts
->orphan_from_empty_tree
) {
788 if (new_branch_info
->commit
)
789 BUG("'switch --orphan' should never accept a commit as starting point");
790 new_tree
= parse_tree_indirect(the_hash_algo
->empty_tree
);
792 BUG("unable to read empty tree");
794 new_tree
= repo_get_commit_tree(the_repository
,
795 new_branch_info
->commit
);
797 return error(_("unable to read tree (%s)"),
798 oid_to_hex(&new_branch_info
->commit
->object
.oid
));
800 if (opts
->discard_changes
) {
801 ret
= reset_tree(new_tree
, opts
, 1, writeout_error
, new_branch_info
);
805 struct tree_desc trees
[2];
807 struct unpack_trees_options topts
;
808 const struct object_id
*old_commit_oid
;
810 refresh_index(the_repository
->index
, REFRESH_QUIET
, NULL
, NULL
, NULL
);
812 if (unmerged_index(the_repository
->index
)) {
813 error(_("you need to resolve your current index first"));
817 /* 2-way merge to the new branch */
818 init_topts(&topts
, opts
->merge
, opts
->show_progress
,
819 opts
->overwrite_ignore
, old_branch_info
->commit
);
820 init_checkout_metadata(&topts
.meta
, new_branch_info
->refname
,
821 new_branch_info
->commit
?
822 &new_branch_info
->commit
->object
.oid
:
823 &new_branch_info
->oid
, NULL
);
825 old_commit_oid
= old_branch_info
->commit
?
826 &old_branch_info
->commit
->object
.oid
:
827 the_hash_algo
->empty_tree
;
828 tree
= parse_tree_indirect(old_commit_oid
);
830 die(_("unable to parse commit %s"),
831 oid_to_hex(old_commit_oid
));
833 init_tree_desc(&trees
[0], &tree
->object
.oid
,
834 tree
->buffer
, tree
->size
);
835 if (parse_tree(new_tree
) < 0)
838 init_tree_desc(&trees
[1], &tree
->object
.oid
,
839 tree
->buffer
, tree
->size
);
841 ret
= unpack_trees(2, trees
, &topts
);
842 clear_unpack_trees_porcelain(&topts
);
845 * Unpack couldn't do a trivial merge; either
846 * give up or do a real merge, depending on
847 * whether the merge flag was used.
850 struct tree
*old_tree
;
851 struct merge_options o
;
852 struct strbuf sb
= STRBUF_INIT
;
853 struct strbuf old_commit_shortname
= STRBUF_INIT
;
859 * Without old_branch_info->commit, the below is the same as
860 * the two-tree unpack we already tried and failed.
862 if (!old_branch_info
->commit
)
864 old_tree
= repo_get_commit_tree(the_repository
,
865 old_branch_info
->commit
);
867 if (repo_index_has_changes(the_repository
, old_tree
, &sb
))
868 die(_("cannot continue with staged changes in "
869 "the following files:\n%s"), sb
.buf
);
872 /* Do more real merge */
875 * We update the index fully, then write the
876 * tree from the index, then merge the new
877 * branch with the current tree, with the old
878 * branch as the base. Then we reset the index
879 * (but not the working tree) to the new
880 * branch, leaving the working tree as the
881 * merged version, but skipping unmerged
882 * entries in the index.
885 add_files_to_cache(the_repository
, NULL
, NULL
, NULL
, 0,
887 init_merge_options(&o
, the_repository
);
889 work
= write_in_core_index_as_tree(the_repository
);
891 ret
= reset_tree(new_tree
,
893 writeout_error
, new_branch_info
);
896 o
.ancestor
= old_branch_info
->name
;
897 if (!old_branch_info
->name
) {
898 strbuf_add_unique_abbrev(&old_commit_shortname
,
899 &old_branch_info
->commit
->object
.oid
,
901 o
.ancestor
= old_commit_shortname
.buf
;
903 o
.branch1
= new_branch_info
->name
;
905 o
.conflict_style
= opts
->conflict_style
;
906 ret
= merge_trees(&o
,
912 ret
= reset_tree(new_tree
,
914 writeout_error
, new_branch_info
);
915 strbuf_release(&o
.obuf
);
916 strbuf_release(&old_commit_shortname
);
922 if (!cache_tree_fully_valid(the_repository
->index
->cache_tree
))
923 cache_tree_update(the_repository
->index
, WRITE_TREE_SILENT
| WRITE_TREE_REPAIR
);
925 if (write_locked_index(the_repository
->index
, &lock_file
, COMMIT_LOCK
))
926 die(_("unable to write new index file"));
928 if (!opts
->discard_changes
&& !opts
->quiet
&& new_branch_info
->commit
)
929 show_local_changes(&new_branch_info
->commit
->object
, &opts
->diff_options
);
934 static void report_tracking(struct branch_info
*new_branch_info
)
936 struct strbuf sb
= STRBUF_INIT
;
937 struct branch
*branch
= branch_get(new_branch_info
->name
);
939 if (!format_tracking_info(branch
, &sb
, AHEAD_BEHIND_FULL
, 1))
941 fputs(sb
.buf
, stdout
);
945 static void update_refs_for_switch(const struct checkout_opts
*opts
,
946 struct branch_info
*old_branch_info
,
947 struct branch_info
*new_branch_info
)
949 struct strbuf msg
= STRBUF_INIT
;
950 const char *old_desc
, *reflog_msg
;
951 if (opts
->new_branch
) {
952 if (opts
->new_orphan_branch
) {
955 refname
= mkpathdup("refs/heads/%s", opts
->new_orphan_branch
);
956 if (opts
->new_branch_log
&&
957 !should_autocreate_reflog(refname
)) {
959 struct strbuf err
= STRBUF_INIT
;
961 ret
= refs_create_reflog(get_main_ref_store(the_repository
),
964 fprintf(stderr
, _("Can not do reflog for '%s': %s\n"),
965 opts
->new_orphan_branch
, err
.buf
);
966 strbuf_release(&err
);
970 strbuf_release(&err
);
975 create_branch(the_repository
,
976 opts
->new_branch
, new_branch_info
->name
,
977 opts
->new_branch_force
? 1 : 0,
978 opts
->new_branch_force
? 1 : 0,
979 opts
->new_branch_log
,
983 free(new_branch_info
->name
);
984 free(new_branch_info
->refname
);
985 new_branch_info
->name
= xstrdup(opts
->new_branch
);
986 setup_branch_path(new_branch_info
);
989 old_desc
= old_branch_info
->name
;
990 if (!old_desc
&& old_branch_info
->commit
)
991 old_desc
= oid_to_hex(&old_branch_info
->commit
->object
.oid
);
993 reflog_msg
= getenv("GIT_REFLOG_ACTION");
995 strbuf_addf(&msg
, "checkout: moving from %s to %s",
996 old_desc
? old_desc
: "(invalid)", new_branch_info
->name
);
998 strbuf_insertstr(&msg
, 0, reflog_msg
);
1000 if (!strcmp(new_branch_info
->name
, "HEAD") && !new_branch_info
->path
&& !opts
->force_detach
) {
1001 /* Nothing to do. */
1002 } else if (opts
->force_detach
|| !new_branch_info
->path
) { /* No longer on any branch. */
1003 refs_update_ref(get_main_ref_store(the_repository
), msg
.buf
,
1004 "HEAD", &new_branch_info
->commit
->object
.oid
,
1006 REF_NO_DEREF
, UPDATE_REFS_DIE_ON_ERR
);
1008 if (old_branch_info
->path
&&
1009 advice_enabled(ADVICE_DETACHED_HEAD
) && !opts
->force_detach
)
1010 detach_advice(new_branch_info
->name
);
1011 describe_detached_head(_("HEAD is now at"), new_branch_info
->commit
);
1013 } else if (new_branch_info
->path
) { /* Switch branches. */
1014 if (refs_update_symref(get_main_ref_store(the_repository
), "HEAD", new_branch_info
->path
, msg
.buf
) < 0)
1015 die(_("unable to update HEAD"));
1017 if (old_branch_info
->path
&& !strcmp(new_branch_info
->path
, old_branch_info
->path
)) {
1018 if (opts
->new_branch_force
)
1019 fprintf(stderr
, _("Reset branch '%s'\n"),
1020 new_branch_info
->name
);
1022 fprintf(stderr
, _("Already on '%s'\n"),
1023 new_branch_info
->name
);
1024 } else if (opts
->new_branch
) {
1025 if (opts
->branch_exists
)
1026 fprintf(stderr
, _("Switched to and reset branch '%s'\n"), new_branch_info
->name
);
1028 fprintf(stderr
, _("Switched to a new branch '%s'\n"), new_branch_info
->name
);
1030 fprintf(stderr
, _("Switched to branch '%s'\n"),
1031 new_branch_info
->name
);
1034 if (old_branch_info
->path
&& old_branch_info
->name
) {
1035 if (!refs_ref_exists(get_main_ref_store(the_repository
), old_branch_info
->path
) && refs_reflog_exists(get_main_ref_store(the_repository
), old_branch_info
->path
))
1036 refs_delete_reflog(get_main_ref_store(the_repository
),
1037 old_branch_info
->path
);
1040 remove_branch_state(the_repository
, !opts
->quiet
);
1041 strbuf_release(&msg
);
1043 !opts
->force_detach
&&
1044 (new_branch_info
->path
|| !strcmp(new_branch_info
->name
, "HEAD")))
1045 report_tracking(new_branch_info
);
1048 static int add_pending_uninteresting_ref(const char *refname
,
1049 const struct object_id
*oid
,
1050 int flags UNUSED
, void *cb_data
)
1052 add_pending_oid(cb_data
, refname
, oid
, UNINTERESTING
);
1056 static void describe_one_orphan(struct strbuf
*sb
, struct commit
*commit
)
1058 strbuf_addstr(sb
, " ");
1059 strbuf_add_unique_abbrev(sb
, &commit
->object
.oid
, DEFAULT_ABBREV
);
1060 strbuf_addch(sb
, ' ');
1061 if (!repo_parse_commit(the_repository
, commit
))
1062 pp_commit_easy(CMIT_FMT_ONELINE
, commit
, sb
);
1063 strbuf_addch(sb
, '\n');
1066 #define ORPHAN_CUTOFF 4
1067 static void suggest_reattach(struct commit
*commit
, struct rev_info
*revs
)
1069 struct commit
*c
, *last
= NULL
;
1070 struct strbuf sb
= STRBUF_INIT
;
1072 while ((c
= get_revision(revs
)) != NULL
) {
1073 if (lost
< ORPHAN_CUTOFF
)
1074 describe_one_orphan(&sb
, c
);
1078 if (ORPHAN_CUTOFF
< lost
) {
1079 int more
= lost
- ORPHAN_CUTOFF
;
1081 describe_one_orphan(&sb
, last
);
1083 strbuf_addf(&sb
, _(" ... and %d more.\n"), more
);
1088 /* The singular version */
1089 "Warning: you are leaving %d commit behind, "
1090 "not connected to\n"
1091 "any of your branches:\n\n"
1093 /* The plural version */
1094 "Warning: you are leaving %d commits behind, "
1095 "not connected to\n"
1096 "any of your branches:\n\n"
1098 /* Give ngettext() the count */
1102 strbuf_release(&sb
);
1104 if (advice_enabled(ADVICE_DETACHED_HEAD
))
1107 /* The singular version */
1108 "If you want to keep it by creating a new branch, "
1109 "this may be a good time\nto do so with:\n\n"
1110 " git branch <new-branch-name> %s\n\n",
1111 /* The plural version */
1112 "If you want to keep them by creating a new branch, "
1113 "this may be a good time\nto do so with:\n\n"
1114 " git branch <new-branch-name> %s\n\n",
1115 /* Give ngettext() the count */
1117 repo_find_unique_abbrev(the_repository
, &commit
->object
.oid
, DEFAULT_ABBREV
));
1121 * We are about to leave commit that was at the tip of a detached
1122 * HEAD. If it is not reachable from any ref, this is the last chance
1123 * for the user to do so without resorting to reflog.
1125 static void orphaned_commit_warning(struct commit
*old_commit
, struct commit
*new_commit
)
1127 struct rev_info revs
;
1128 struct object
*object
= &old_commit
->object
;
1130 repo_init_revisions(the_repository
, &revs
, NULL
);
1131 setup_revisions(0, NULL
, &revs
, NULL
);
1133 object
->flags
&= ~UNINTERESTING
;
1134 add_pending_object(&revs
, object
, oid_to_hex(&object
->oid
));
1136 refs_for_each_ref(get_main_ref_store(the_repository
),
1137 add_pending_uninteresting_ref
, &revs
);
1139 add_pending_oid(&revs
, "HEAD",
1140 &new_commit
->object
.oid
,
1143 if (prepare_revision_walk(&revs
))
1144 die(_("internal error in revision walk"));
1145 if (!(old_commit
->object
.flags
& UNINTERESTING
))
1146 suggest_reattach(old_commit
, &revs
);
1148 describe_detached_head(_("Previous HEAD position was"), old_commit
);
1150 /* Clean up objects used, as they will be reused. */
1151 repo_clear_commit_marks(the_repository
, ALL_REV_FLAGS
);
1152 release_revisions(&revs
);
1155 static int switch_branches(const struct checkout_opts
*opts
,
1156 struct branch_info
*new_branch_info
)
1159 struct branch_info old_branch_info
= { 0 };
1160 struct object_id rev
;
1161 int flag
, writeout_error
= 0;
1164 trace2_cmd_mode("branch");
1166 memset(&old_branch_info
, 0, sizeof(old_branch_info
));
1167 old_branch_info
.path
= refs_resolve_refdup(get_main_ref_store(the_repository
),
1168 "HEAD", 0, &rev
, &flag
);
1169 if (old_branch_info
.path
)
1170 old_branch_info
.commit
= lookup_commit_reference_gently(the_repository
, &rev
, 1);
1171 if (!(flag
& REF_ISSYMREF
))
1172 FREE_AND_NULL(old_branch_info
.path
);
1174 if (old_branch_info
.path
) {
1175 const char *const prefix
= "refs/heads/";
1177 if (skip_prefix(old_branch_info
.path
, prefix
, &p
))
1178 old_branch_info
.name
= xstrdup(p
);
1181 if (opts
->new_orphan_branch
&& opts
->orphan_from_empty_tree
) {
1182 if (new_branch_info
->name
)
1183 BUG("'switch --orphan' should never accept a commit as starting point");
1184 new_branch_info
->commit
= NULL
;
1185 new_branch_info
->name
= xstrdup("(empty)");
1189 if (!new_branch_info
->name
) {
1190 new_branch_info
->name
= xstrdup("HEAD");
1191 new_branch_info
->commit
= old_branch_info
.commit
;
1192 if (!new_branch_info
->commit
)
1193 die(_("You are on a branch yet to be born"));
1194 parse_commit_or_die(new_branch_info
->commit
);
1196 if (opts
->only_merge_on_switching_branches
)
1201 ret
= merge_working_tree(opts
, &old_branch_info
, new_branch_info
, &writeout_error
);
1203 branch_info_release(&old_branch_info
);
1208 if (!opts
->quiet
&& !old_branch_info
.path
&& old_branch_info
.commit
&& new_branch_info
->commit
!= old_branch_info
.commit
)
1209 orphaned_commit_warning(old_branch_info
.commit
, new_branch_info
->commit
);
1211 update_refs_for_switch(opts
, &old_branch_info
, new_branch_info
);
1213 ret
= post_checkout_hook(old_branch_info
.commit
, new_branch_info
->commit
, 1);
1214 branch_info_release(&old_branch_info
);
1216 return ret
|| writeout_error
;
1219 static int git_checkout_config(const char *var
, const char *value
,
1220 const struct config_context
*ctx
, void *cb
)
1222 struct checkout_opts
*opts
= cb
;
1224 if (!strcmp(var
, "diff.ignoresubmodules")) {
1226 return config_error_nonbool(var
);
1227 handle_ignore_submodules_arg(&opts
->diff_options
, value
);
1230 if (!strcmp(var
, "checkout.guess")) {
1231 opts
->dwim_new_local_branch
= git_config_bool(var
, value
);
1235 if (starts_with(var
, "submodule."))
1236 return git_default_submodule_config(var
, value
, NULL
);
1238 return git_xmerge_config(var
, value
, ctx
, NULL
);
1241 static void setup_new_branch_info_and_source_tree(
1242 struct branch_info
*new_branch_info
,
1243 struct checkout_opts
*opts
,
1244 struct object_id
*rev
,
1247 struct tree
**source_tree
= &opts
->source_tree
;
1248 struct object_id branch_rev
;
1250 /* treat '@' as a shortcut for 'HEAD' */
1251 new_branch_info
->name
= !strcmp(arg
, "@") ? xstrdup("HEAD") :
1253 setup_branch_path(new_branch_info
);
1255 if (!check_refname_format(new_branch_info
->path
, 0) &&
1256 !refs_read_ref(get_main_ref_store(the_repository
), new_branch_info
->path
, &branch_rev
))
1257 oidcpy(rev
, &branch_rev
);
1259 /* not an existing branch */
1260 FREE_AND_NULL(new_branch_info
->path
);
1262 new_branch_info
->commit
= lookup_commit_reference_gently(the_repository
, rev
, 1);
1263 if (!new_branch_info
->commit
) {
1265 *source_tree
= parse_tree_indirect(rev
);
1267 die(_("unable to read tree (%s)"), oid_to_hex(rev
));
1269 parse_commit_or_die(new_branch_info
->commit
);
1270 *source_tree
= repo_get_commit_tree(the_repository
,
1271 new_branch_info
->commit
);
1273 die(_("unable to read tree (%s)"),
1274 oid_to_hex(&new_branch_info
->commit
->object
.oid
));
1278 static const char *parse_remote_branch(const char *arg
,
1279 struct object_id
*rev
,
1280 int could_be_checkout_paths
)
1282 int num_matches
= 0;
1283 const char *remote
= unique_tracking_name(arg
, rev
, &num_matches
);
1285 if (remote
&& could_be_checkout_paths
) {
1286 die(_("'%s' could be both a local file and a tracking branch.\n"
1287 "Please use -- (and optionally --no-guess) to disambiguate"),
1291 if (!remote
&& num_matches
> 1) {
1292 if (advice_enabled(ADVICE_CHECKOUT_AMBIGUOUS_REMOTE_BRANCH_NAME
)) {
1293 advise(_("If you meant to check out a remote tracking branch on, e.g. 'origin',\n"
1294 "you can do so by fully qualifying the name with the --track option:\n"
1296 " git checkout --track origin/<name>\n"
1298 "If you'd like to always have checkouts of an ambiguous <name> prefer\n"
1299 "one remote, e.g. the 'origin' remote, consider setting\n"
1300 "checkout.defaultRemote=origin in your config."));
1303 die(_("'%s' matched multiple (%d) remote tracking branches"),
1310 static int parse_branchname_arg(int argc
, const char **argv
,
1311 int dwim_new_local_branch_ok
,
1312 struct branch_info
*new_branch_info
,
1313 struct checkout_opts
*opts
,
1314 struct object_id
*rev
)
1316 const char **new_branch
= &opts
->new_branch
;
1320 int has_dash_dash
= 0;
1324 * case 1: git checkout <ref> -- [<paths>]
1326 * <ref> must be a valid tree, everything after the '--' must be
1329 * case 2: git checkout -- [<paths>]
1331 * everything after the '--' must be paths.
1333 * case 3: git checkout <something> [--]
1335 * (a) If <something> is a commit, that is to
1336 * switch to the branch or detach HEAD at it. As a special case,
1337 * if <something> is A...B (missing A or B means HEAD but you can
1338 * omit at most one side), and if there is a unique merge base
1339 * between A and B, A...B names that merge base.
1341 * (b) If <something> is _not_ a commit, either "--" is present
1342 * or <something> is not a path, no -t or -b was given,
1343 * and there is a tracking branch whose name is <something>
1344 * in one and only one remote (or if the branch exists on the
1345 * remote named in checkout.defaultRemote), then this is a
1346 * short-hand to fork local <something> from that
1347 * remote-tracking branch.
1349 * (c) Otherwise, if "--" is present, treat it like case (1).
1352 * - if it's a reference, treat it like case (1)
1353 * - else if it's a path, treat it like case (2)
1356 * case 4: git checkout <something> <paths>
1358 * The first argument must not be ambiguous.
1359 * - If it's *only* a reference, treat it like case (1).
1360 * - If it's only a path, treat it like case (2).
1367 if (!opts
->accept_pathspec
) {
1369 die(_("only one reference expected"));
1370 has_dash_dash
= 1; /* helps disambiguate */
1375 for (i
= 0; i
< argc
; i
++) {
1376 if (opts
->accept_pathspec
&& !strcmp(argv
[i
], "--")) {
1381 if (dash_dash_pos
== 0)
1382 return 1; /* case (2) */
1383 else if (dash_dash_pos
== 1)
1384 has_dash_dash
= 1; /* case (3) or (1) */
1385 else if (dash_dash_pos
>= 2)
1386 die(_("only one reference expected, %d given."), dash_dash_pos
);
1387 opts
->count_checkout_paths
= !opts
->quiet
&& !has_dash_dash
;
1389 if (!strcmp(arg
, "-"))
1392 if (repo_get_oid_mb(the_repository
, arg
, rev
)) {
1394 * Either case (3) or (4), with <something> not being
1395 * a commit, or an attempt to use case (1) with an
1398 * It's likely an error, but we need to find out if
1399 * we should auto-create the branch, case (3).(b).
1401 int recover_with_dwim
= dwim_new_local_branch_ok
;
1403 int could_be_checkout_paths
= !has_dash_dash
&&
1404 check_filename(opts
->prefix
, arg
);
1406 if (!has_dash_dash
&& !no_wildcard(arg
))
1407 recover_with_dwim
= 0;
1410 * Accept "git checkout foo", "git checkout foo --"
1411 * and "git switch foo" as candidates for dwim.
1413 if (!(argc
== 1 && !has_dash_dash
) &&
1414 !(argc
== 2 && has_dash_dash
) &&
1415 opts
->accept_pathspec
)
1416 recover_with_dwim
= 0;
1418 if (recover_with_dwim
) {
1419 const char *remote
= parse_remote_branch(arg
, rev
,
1420 could_be_checkout_paths
);
1424 /* DWIMmed to create local branch, case (3).(b) */
1426 recover_with_dwim
= 0;
1430 if (!recover_with_dwim
) {
1432 die(_("invalid reference: %s"), arg
);
1437 /* we can't end up being in (2) anymore, eat the argument */
1442 setup_new_branch_info_and_source_tree(new_branch_info
, opts
, rev
, arg
);
1444 if (!opts
->source_tree
) /* case (1): want a tree */
1445 die(_("reference is not a tree: %s"), arg
);
1447 if (!has_dash_dash
) { /* case (3).(d) -> (1) */
1449 * Do not complain the most common case
1450 * git checkout branch
1451 * even if there happen to be a file called 'branch';
1452 * it would be extremely annoying.
1455 verify_non_filename(opts
->prefix
, arg
);
1456 } else if (opts
->accept_pathspec
) {
1465 static int switch_unborn_to_new_branch(const struct checkout_opts
*opts
)
1468 struct strbuf branch_ref
= STRBUF_INIT
;
1470 trace2_cmd_mode("unborn");
1472 if (!opts
->new_branch
)
1473 die(_("You are on a branch yet to be born"));
1474 strbuf_addf(&branch_ref
, "refs/heads/%s", opts
->new_branch
);
1475 status
= refs_update_symref(get_main_ref_store(the_repository
),
1476 "HEAD", branch_ref
.buf
, "checkout -b");
1477 strbuf_release(&branch_ref
);
1479 fprintf(stderr
, _("Switched to a new branch '%s'\n"),
1484 static void die_expecting_a_branch(const struct branch_info
*branch_info
)
1486 struct object_id oid
;
1490 if (repo_dwim_ref(the_repository
, branch_info
->name
,
1491 strlen(branch_info
->name
), &oid
, &to_free
, 0) == 1) {
1492 const char *ref
= to_free
;
1494 if (skip_prefix(ref
, "refs/tags/", &ref
))
1495 code
= die_message(_("a branch is expected, got tag '%s'"), ref
);
1496 else if (skip_prefix(ref
, "refs/remotes/", &ref
))
1497 code
= die_message(_("a branch is expected, got remote branch '%s'"), ref
);
1499 code
= die_message(_("a branch is expected, got '%s'"), ref
);
1501 else if (branch_info
->commit
)
1502 code
= die_message(_("a branch is expected, got commit '%s'"), branch_info
->name
);
1505 * This case should never happen because we already die() on
1506 * non-commit, but just in case.
1508 code
= die_message(_("a branch is expected, got '%s'"), branch_info
->name
);
1510 if (advice_enabled(ADVICE_SUGGEST_DETACHING_HEAD
))
1511 advise(_("If you want to detach HEAD at the commit, try again with the --detach option."));
1516 static void die_if_some_operation_in_progress(void)
1518 struct wt_status_state state
;
1520 memset(&state
, 0, sizeof(state
));
1521 wt_status_get_state(the_repository
, &state
, 0);
1523 if (state
.merge_in_progress
)
1524 die(_("cannot switch branch while merging\n"
1525 "Consider \"git merge --quit\" "
1526 "or \"git worktree add\"."));
1527 if (state
.am_in_progress
)
1528 die(_("cannot switch branch in the middle of an am session\n"
1529 "Consider \"git am --quit\" "
1530 "or \"git worktree add\"."));
1531 if (state
.rebase_interactive_in_progress
|| state
.rebase_in_progress
)
1532 die(_("cannot switch branch while rebasing\n"
1533 "Consider \"git rebase --quit\" "
1534 "or \"git worktree add\"."));
1535 if (state
.cherry_pick_in_progress
)
1536 die(_("cannot switch branch while cherry-picking\n"
1537 "Consider \"git cherry-pick --quit\" "
1538 "or \"git worktree add\"."));
1539 if (state
.revert_in_progress
)
1540 die(_("cannot switch branch while reverting\n"
1541 "Consider \"git revert --quit\" "
1542 "or \"git worktree add\"."));
1543 if (state
.bisect_in_progress
)
1544 warning(_("you are switching branch while bisecting"));
1546 wt_status_state_free_buffers(&state
);
1550 * die if attempting to checkout an existing branch that is in use
1551 * in another worktree, unless ignore-other-wortrees option is given.
1552 * The check is bypassed when the branch is already the current one,
1553 * as it will not make things any worse.
1555 static void die_if_switching_to_a_branch_in_use(struct checkout_opts
*opts
,
1556 const char *full_ref
)
1561 if (opts
->ignore_other_worktrees
)
1563 head_ref
= refs_resolve_refdup(get_main_ref_store(the_repository
),
1564 "HEAD", 0, NULL
, &flags
);
1565 if (head_ref
&& (!(flags
& REF_ISSYMREF
) || strcmp(head_ref
, full_ref
)))
1566 die_if_checked_out(full_ref
, 1);
1570 static int checkout_branch(struct checkout_opts
*opts
,
1571 struct branch_info
*new_branch_info
)
1573 if (opts
->pathspec
.nr
)
1574 die(_("paths cannot be used with switching branches"));
1576 if (opts
->patch_mode
)
1577 die(_("'%s' cannot be used with switching branches"),
1580 if (opts
->overlay_mode
!= -1)
1581 die(_("'%s' cannot be used with switching branches"),
1584 if (opts
->writeout_stage
)
1585 die(_("'%s' cannot be used with switching branches"),
1588 if (opts
->force
&& opts
->merge
)
1589 die(_("'%s' cannot be used with '%s'"), "-f", "-m");
1591 if (opts
->discard_changes
&& opts
->merge
)
1592 die(_("'%s' cannot be used with '%s'"), "--discard-changes", "--merge");
1594 if (opts
->force_detach
&& opts
->new_branch
)
1595 die(_("'%s' cannot be used with '%s'"),
1596 "--detach", "-b/-B/--orphan");
1598 if (opts
->new_orphan_branch
) {
1599 if (opts
->track
!= BRANCH_TRACK_UNSPECIFIED
)
1600 die(_("'%s' cannot be used with '%s'"), "--orphan", "-t");
1601 if (opts
->orphan_from_empty_tree
&& new_branch_info
->name
)
1602 die(_("'%s' cannot take <start-point>"), "--orphan");
1603 } else if (opts
->force_detach
) {
1604 if (opts
->track
!= BRANCH_TRACK_UNSPECIFIED
)
1605 die(_("'%s' cannot be used with '%s'"), "--detach", "-t");
1606 } else if (opts
->track
== BRANCH_TRACK_UNSPECIFIED
)
1607 opts
->track
= git_branch_track
;
1609 if (new_branch_info
->name
&& !new_branch_info
->commit
)
1610 die(_("Cannot switch branch to a non-commit '%s'"),
1611 new_branch_info
->name
);
1613 if (!opts
->switch_branch_doing_nothing_is_ok
&&
1614 !new_branch_info
->name
&&
1615 !opts
->new_branch
&&
1616 !opts
->force_detach
)
1617 die(_("missing branch or commit argument"));
1619 if (!opts
->implicit_detach
&&
1620 !opts
->force_detach
&&
1621 !opts
->new_branch
&&
1622 !opts
->new_branch_force
&&
1623 new_branch_info
->name
&&
1624 !new_branch_info
->path
)
1625 die_expecting_a_branch(new_branch_info
);
1627 if (!opts
->can_switch_when_in_progress
)
1628 die_if_some_operation_in_progress();
1630 /* "git checkout <branch>" */
1631 if (new_branch_info
->path
&& !opts
->force_detach
&& !opts
->new_branch
)
1632 die_if_switching_to_a_branch_in_use(opts
, new_branch_info
->path
);
1634 /* "git checkout -B <branch>" */
1635 if (opts
->new_branch_force
) {
1636 char *full_ref
= xstrfmt("refs/heads/%s", opts
->new_branch
);
1637 die_if_switching_to_a_branch_in_use(opts
, full_ref
);
1641 if (!new_branch_info
->commit
&& opts
->new_branch
) {
1642 struct object_id rev
;
1645 if (!refs_read_ref_full(get_main_ref_store(the_repository
), "HEAD", 0, &rev
, &flag
) &&
1646 (flag
& REF_ISSYMREF
) && is_null_oid(&rev
))
1647 return switch_unborn_to_new_branch(opts
);
1649 return switch_branches(opts
, new_branch_info
);
1652 static int parse_opt_conflict(const struct option
*o
, const char *arg
, int unset
)
1654 struct checkout_opts
*opts
= o
->value
;
1657 opts
->conflict_style
= -1;
1660 opts
->conflict_style
= parse_conflict_style_name(arg
);
1661 if (opts
->conflict_style
< 0)
1662 return error(_("unknown conflict style '%s'"), arg
);
1663 /* --conflict overrides a previous --no-merge */
1670 static struct option
*add_common_options(struct checkout_opts
*opts
,
1671 struct option
*prevopts
)
1673 struct option options
[] = {
1674 OPT__QUIET(&opts
->quiet
, N_("suppress progress reporting")),
1675 OPT_CALLBACK_F(0, "recurse-submodules", NULL
,
1676 "checkout", "control recursive updating of submodules",
1677 PARSE_OPT_OPTARG
, option_parse_recurse_submodules_worktree_updater
),
1678 OPT_BOOL(0, "progress", &opts
->show_progress
, N_("force progress reporting")),
1679 OPT_BOOL('m', "merge", &opts
->merge
, N_("perform a 3-way merge with the new branch")),
1680 OPT_CALLBACK(0, "conflict", opts
, N_("style"),
1681 N_("conflict style (merge, diff3, or zdiff3)"),
1682 parse_opt_conflict
),
1685 struct option
*newopts
= parse_options_concat(prevopts
, options
);
1690 static struct option
*add_common_switch_branch_options(
1691 struct checkout_opts
*opts
, struct option
*prevopts
)
1693 struct option options
[] = {
1694 OPT_BOOL('d', "detach", &opts
->force_detach
, N_("detach HEAD at named commit")),
1695 OPT_CALLBACK_F('t', "track", &opts
->track
, "(direct|inherit)",
1696 N_("set branch tracking configuration"),
1698 parse_opt_tracking_mode
),
1699 OPT__FORCE(&opts
->force
, N_("force checkout (throw away local modifications)"),
1700 PARSE_OPT_NOCOMPLETE
),
1701 OPT_STRING(0, "orphan", &opts
->new_orphan_branch
, N_("new-branch"), N_("new unborn branch")),
1702 OPT_BOOL_F(0, "overwrite-ignore", &opts
->overwrite_ignore
,
1703 N_("update ignored files (default)"),
1704 PARSE_OPT_NOCOMPLETE
),
1705 OPT_BOOL(0, "ignore-other-worktrees", &opts
->ignore_other_worktrees
,
1706 N_("do not check if another worktree is holding the given ref")),
1709 struct option
*newopts
= parse_options_concat(prevopts
, options
);
1714 static struct option
*add_checkout_path_options(struct checkout_opts
*opts
,
1715 struct option
*prevopts
)
1717 struct option options
[] = {
1718 OPT_SET_INT_F('2', "ours", &opts
->writeout_stage
,
1719 N_("checkout our version for unmerged files"),
1720 2, PARSE_OPT_NONEG
),
1721 OPT_SET_INT_F('3', "theirs", &opts
->writeout_stage
,
1722 N_("checkout their version for unmerged files"),
1723 3, PARSE_OPT_NONEG
),
1724 OPT_BOOL('p', "patch", &opts
->patch_mode
, N_("select hunks interactively")),
1725 OPT_BOOL(0, "ignore-skip-worktree-bits", &opts
->ignore_skipworktree
,
1726 N_("do not limit pathspecs to sparse entries only")),
1727 OPT_PATHSPEC_FROM_FILE(&opts
->pathspec_from_file
),
1728 OPT_PATHSPEC_FILE_NUL(&opts
->pathspec_file_nul
),
1731 struct option
*newopts
= parse_options_concat(prevopts
, options
);
1736 /* create-branch option (either b or c) */
1737 static char cb_option
= 'b';
1739 static int checkout_main(int argc
, const char **argv
, const char *prefix
,
1740 struct checkout_opts
*opts
, struct option
*options
,
1741 const char * const usagestr
[])
1743 int parseopt_flags
= 0;
1744 struct branch_info new_branch_info
= { 0 };
1747 opts
->overwrite_ignore
= 1;
1748 opts
->prefix
= prefix
;
1749 opts
->show_progress
= -1;
1751 git_config(git_checkout_config
, opts
);
1752 if (the_repository
->gitdir
) {
1753 prepare_repo_settings(the_repository
);
1754 the_repository
->settings
.command_requires_full_index
= 0;
1757 opts
->track
= BRANCH_TRACK_UNSPECIFIED
;
1759 if (!opts
->accept_pathspec
&& !opts
->accept_ref
)
1760 BUG("make up your mind, you need to take _something_");
1761 if (opts
->accept_pathspec
&& opts
->accept_ref
)
1762 parseopt_flags
= PARSE_OPT_KEEP_DASHDASH
;
1764 argc
= parse_options(argc
, argv
, prefix
, options
,
1765 usagestr
, parseopt_flags
);
1767 if (opts
->show_progress
< 0) {
1769 opts
->show_progress
= 0;
1771 opts
->show_progress
= isatty(2);
1774 /* --conflicts implies --merge */
1775 if (opts
->merge
== -1)
1776 opts
->merge
= opts
->conflict_style
>= 0;
1779 opts
->discard_changes
= 1;
1780 opts
->ignore_unmerged_opt
= "--force";
1781 opts
->ignore_unmerged
= 1;
1784 if ((!!opts
->new_branch
+ !!opts
->new_branch_force
+ !!opts
->new_orphan_branch
) > 1)
1785 die(_("options '-%c', '-%c', and '%s' cannot be used together"),
1786 cb_option
, toupper(cb_option
), "--orphan");
1788 if (opts
->overlay_mode
== 1 && opts
->patch_mode
)
1789 die(_("options '%s' and '%s' cannot be used together"), "-p", "--overlay");
1791 if (opts
->checkout_index
>= 0 || opts
->checkout_worktree
>= 0) {
1792 if (opts
->checkout_index
< 0)
1793 opts
->checkout_index
= 0;
1794 if (opts
->checkout_worktree
< 0)
1795 opts
->checkout_worktree
= 0;
1797 if (opts
->checkout_index
< 0)
1798 opts
->checkout_index
= -opts
->checkout_index
- 1;
1799 if (opts
->checkout_worktree
< 0)
1800 opts
->checkout_worktree
= -opts
->checkout_worktree
- 1;
1802 if (opts
->checkout_index
< 0 || opts
->checkout_worktree
< 0)
1803 BUG("these flags should be non-negative by now");
1805 * convenient shortcut: "git restore --staged [--worktree]" equals
1806 * "git restore --staged [--worktree] --source HEAD"
1808 if (!opts
->from_treeish
&& opts
->checkout_index
)
1809 opts
->from_treeish
= "HEAD";
1812 * From here on, new_branch will contain the branch to be checked out,
1813 * and new_branch_force and new_orphan_branch will tell us which one of
1814 * -b/-B/-c/-C/--orphan is being used.
1816 if (opts
->new_branch_force
)
1817 opts
->new_branch
= opts
->new_branch_force
;
1819 if (opts
->new_orphan_branch
)
1820 opts
->new_branch
= opts
->new_orphan_branch
;
1822 /* --track without -c/-C/-b/-B/--orphan should DWIM */
1823 if (opts
->track
!= BRANCH_TRACK_UNSPECIFIED
&& !opts
->new_branch
) {
1824 const char *argv0
= argv
[0];
1825 if (!argc
|| !strcmp(argv0
, "--"))
1826 die(_("--track needs a branch name"));
1827 skip_prefix(argv0
, "refs/", &argv0
);
1828 skip_prefix(argv0
, "remotes/", &argv0
);
1829 argv0
= strchr(argv0
, '/');
1830 if (!argv0
|| !argv0
[1])
1831 die(_("missing branch name; try -%c"), cb_option
);
1832 opts
->new_branch
= argv0
+ 1;
1836 * Extract branch name from command line arguments, so
1837 * all that is left is pathspecs.
1841 * 1) git checkout <tree> -- [<paths>]
1842 * 2) git checkout -- [<paths>]
1843 * 3) git checkout <something> [<paths>]
1845 * including "last branch" syntax and DWIM-ery for names of
1846 * remote branches, erroring out for invalid or ambiguous cases.
1848 if (argc
&& opts
->accept_ref
) {
1849 struct object_id rev
;
1851 !opts
->patch_mode
&&
1852 opts
->dwim_new_local_branch
&&
1853 opts
->track
== BRANCH_TRACK_UNSPECIFIED
&&
1855 int n
= parse_branchname_arg(argc
, argv
, dwim_ok
,
1856 &new_branch_info
, opts
, &rev
);
1859 } else if (!opts
->accept_ref
&& opts
->from_treeish
) {
1860 struct object_id rev
;
1862 if (repo_get_oid_mb(the_repository
, opts
->from_treeish
, &rev
))
1863 die(_("could not resolve %s"), opts
->from_treeish
);
1865 setup_new_branch_info_and_source_tree(&new_branch_info
,
1867 opts
->from_treeish
);
1869 if (!opts
->source_tree
)
1870 die(_("reference is not a tree: %s"), opts
->from_treeish
);
1874 parse_pathspec(&opts
->pathspec
, 0,
1875 opts
->patch_mode
? PATHSPEC_PREFIX_ORIGIN
: 0,
1878 if (!opts
->pathspec
.nr
)
1879 die(_("invalid path specification"));
1882 * Try to give more helpful suggestion.
1883 * new_branch && argc > 1 will be caught later.
1885 if (opts
->new_branch
&& argc
== 1 && !new_branch_info
.commit
)
1886 die(_("'%s' is not a commit and a branch '%s' cannot be created from it"),
1887 argv
[0], opts
->new_branch
);
1889 if (opts
->force_detach
)
1890 die(_("git checkout: --detach does not take a path argument '%s'"),
1894 if (opts
->pathspec_from_file
) {
1895 if (opts
->pathspec
.nr
)
1896 die(_("'%s' and pathspec arguments cannot be used together"), "--pathspec-from-file");
1898 if (opts
->force_detach
)
1899 die(_("options '%s' and '%s' cannot be used together"), "--pathspec-from-file", "--detach");
1901 if (opts
->patch_mode
)
1902 die(_("options '%s' and '%s' cannot be used together"), "--pathspec-from-file", "--patch");
1904 parse_pathspec_file(&opts
->pathspec
, 0,
1906 prefix
, opts
->pathspec_from_file
, opts
->pathspec_file_nul
);
1907 } else if (opts
->pathspec_file_nul
) {
1908 die(_("the option '%s' requires '%s'"), "--pathspec-file-nul", "--pathspec-from-file");
1911 opts
->pathspec
.recursive
= 1;
1913 if (opts
->pathspec
.nr
) {
1914 if (1 < !!opts
->writeout_stage
+ !!opts
->force
+ !!opts
->merge
)
1915 die(_("git checkout: --ours/--theirs, --force and --merge are incompatible when\n"
1916 "checking out of the index."));
1918 if (opts
->accept_pathspec
&& !opts
->empty_pathspec_ok
&&
1919 !opts
->patch_mode
) /* patch mode is special */
1920 die(_("you must specify path(s) to restore"));
1923 if (opts
->new_branch
) {
1924 struct strbuf buf
= STRBUF_INIT
;
1926 if (opts
->new_branch_force
)
1927 opts
->branch_exists
= validate_branchname(opts
->new_branch
, &buf
);
1929 opts
->branch_exists
=
1930 validate_new_branchname(opts
->new_branch
, &buf
, 0);
1931 strbuf_release(&buf
);
1934 if (opts
->patch_mode
|| opts
->pathspec
.nr
)
1935 ret
= checkout_paths(opts
, &new_branch_info
);
1937 ret
= checkout_branch(opts
, &new_branch_info
);
1939 branch_info_release(&new_branch_info
);
1940 clear_pathspec(&opts
->pathspec
);
1941 free(opts
->pathspec_from_file
);
1947 int cmd_checkout(int argc
, const char **argv
, const char *prefix
)
1949 struct checkout_opts opts
= CHECKOUT_OPTS_INIT
;
1950 struct option
*options
;
1951 struct option checkout_options
[] = {
1952 OPT_STRING('b', NULL
, &opts
.new_branch
, N_("branch"),
1953 N_("create and checkout a new branch")),
1954 OPT_STRING('B', NULL
, &opts
.new_branch_force
, N_("branch"),
1955 N_("create/reset and checkout a branch")),
1956 OPT_BOOL('l', NULL
, &opts
.new_branch_log
, N_("create reflog for new branch")),
1957 OPT_BOOL(0, "guess", &opts
.dwim_new_local_branch
,
1958 N_("second guess 'git checkout <no-such-branch>' (default)")),
1959 OPT_BOOL(0, "overlay", &opts
.overlay_mode
, N_("use overlay mode (default)")),
1963 opts
.dwim_new_local_branch
= 1;
1964 opts
.switch_branch_doing_nothing_is_ok
= 1;
1965 opts
.only_merge_on_switching_branches
= 0;
1966 opts
.accept_ref
= 1;
1967 opts
.accept_pathspec
= 1;
1968 opts
.implicit_detach
= 1;
1969 opts
.can_switch_when_in_progress
= 1;
1970 opts
.orphan_from_empty_tree
= 0;
1971 opts
.empty_pathspec_ok
= 1;
1972 opts
.overlay_mode
= -1;
1973 opts
.checkout_index
= -2; /* default on */
1974 opts
.checkout_worktree
= -2; /* default on */
1976 if (argc
== 3 && !strcmp(argv
[1], "-b")) {
1978 * User ran 'git checkout -b <branch>' and expects
1979 * the same behavior as 'git switch -c <branch>'.
1981 opts
.switch_branch_doing_nothing_is_ok
= 0;
1982 opts
.only_merge_on_switching_branches
= 1;
1985 options
= parse_options_dup(checkout_options
);
1986 options
= add_common_options(&opts
, options
);
1987 options
= add_common_switch_branch_options(&opts
, options
);
1988 options
= add_checkout_path_options(&opts
, options
);
1990 return checkout_main(argc
, argv
, prefix
, &opts
, options
,
1994 int cmd_switch(int argc
, const char **argv
, const char *prefix
)
1996 struct checkout_opts opts
= CHECKOUT_OPTS_INIT
;
1997 struct option
*options
= NULL
;
1998 struct option switch_options
[] = {
1999 OPT_STRING('c', "create", &opts
.new_branch
, N_("branch"),
2000 N_("create and switch to a new branch")),
2001 OPT_STRING('C', "force-create", &opts
.new_branch_force
, N_("branch"),
2002 N_("create/reset and switch to a branch")),
2003 OPT_BOOL(0, "guess", &opts
.dwim_new_local_branch
,
2004 N_("second guess 'git switch <no-such-branch>'")),
2005 OPT_BOOL(0, "discard-changes", &opts
.discard_changes
,
2006 N_("throw away local modifications")),
2010 opts
.dwim_new_local_branch
= 1;
2011 opts
.accept_ref
= 1;
2012 opts
.accept_pathspec
= 0;
2013 opts
.switch_branch_doing_nothing_is_ok
= 0;
2014 opts
.only_merge_on_switching_branches
= 1;
2015 opts
.implicit_detach
= 0;
2016 opts
.can_switch_when_in_progress
= 0;
2017 opts
.orphan_from_empty_tree
= 1;
2018 opts
.overlay_mode
= -1;
2020 options
= parse_options_dup(switch_options
);
2021 options
= add_common_options(&opts
, options
);
2022 options
= add_common_switch_branch_options(&opts
, options
);
2026 return checkout_main(argc
, argv
, prefix
, &opts
, options
,
2027 switch_branch_usage
);
2030 int cmd_restore(int argc
, const char **argv
, const char *prefix
)
2032 struct checkout_opts opts
= CHECKOUT_OPTS_INIT
;
2033 struct option
*options
;
2034 struct option restore_options
[] = {
2035 OPT_STRING('s', "source", &opts
.from_treeish
, "<tree-ish>",
2036 N_("which tree-ish to checkout from")),
2037 OPT_BOOL('S', "staged", &opts
.checkout_index
,
2038 N_("restore the index")),
2039 OPT_BOOL('W', "worktree", &opts
.checkout_worktree
,
2040 N_("restore the working tree (default)")),
2041 OPT_BOOL(0, "ignore-unmerged", &opts
.ignore_unmerged
,
2042 N_("ignore unmerged entries")),
2043 OPT_BOOL(0, "overlay", &opts
.overlay_mode
, N_("use overlay mode")),
2047 opts
.accept_ref
= 0;
2048 opts
.accept_pathspec
= 1;
2049 opts
.empty_pathspec_ok
= 0;
2050 opts
.overlay_mode
= 0;
2051 opts
.checkout_index
= -1; /* default off */
2052 opts
.checkout_worktree
= -2; /* default on */
2053 opts
.ignore_unmerged_opt
= "--ignore-unmerged";
2055 options
= parse_options_dup(restore_options
);
2056 options
= add_common_options(&opts
, options
);
2057 options
= add_checkout_path_options(&opts
, options
);
2059 return checkout_main(argc
, argv
, prefix
, &opts
, options
,