1 #define USE_THE_REPOSITORY_VARIABLE
2 #define DISABLE_SIGN_COMPARE_WARNINGS
7 #include "cache-tree.h"
13 #include "environment.h"
20 #include "merge-ort-wrappers.h"
21 #include "object-file.h"
22 #include "object-name.h"
23 #include "object-store.h"
24 #include "parse-options.h"
26 #include "preload-index.h"
27 #include "read-cache.h"
30 #include "repo-settings.h"
31 #include "resolve-undo.h"
34 #include "submodule.h"
38 #include "tree-walk.h"
39 #include "unpack-trees.h"
40 #include "wt-status.h"
41 #include "xdiff-interface.h"
43 #include "parallel-checkout.h"
44 #include "add-interactive.h"
46 static const char * const checkout_usage
[] = {
47 N_("git checkout [<options>] <branch>"),
48 N_("git checkout [<options>] [<branch>] -- <file>..."),
52 static const char * const switch_branch_usage
[] = {
53 N_("git switch [<options>] [<branch>]"),
57 static const char * const restore_usage
[] = {
58 N_("git restore [<options>] [--source=<branch>] <file>..."),
62 struct checkout_opts
{
71 int ignore_skipworktree
;
72 int ignore_other_worktrees
;
74 int count_checkout_paths
;
76 int dwim_new_local_branch
;
80 int switch_branch_doing_nothing_is_ok
;
81 int only_merge_on_switching_branches
;
82 int can_switch_when_in_progress
;
83 int orphan_from_empty_tree
;
84 int empty_pathspec_ok
;
86 int checkout_worktree
;
87 const char *ignore_unmerged_opt
;
89 int pathspec_file_nul
;
90 char *pathspec_from_file
;
92 const char *new_branch
;
93 const char *new_branch_force
;
94 const char *new_orphan_branch
;
96 enum branch_track track
;
97 struct diff_options diff_options
;
102 struct pathspec pathspec
;
103 const char *from_treeish
;
104 struct tree
*source_tree
;
107 #define CHECKOUT_OPTS_INIT { .conflict_style = -1, .merge = -1 }
110 char *name
; /* The short name used */
111 char *path
; /* The full name of a real branch */
112 struct commit
*commit
; /* The named commit */
113 char *refname
; /* The full name of the ref being checked out. */
114 struct object_id oid
; /* The object ID of the commit being checked out. */
116 * if not null the branch is detached because it's already
117 * checked out in this checkout
122 static void branch_info_release(struct branch_info
*info
)
127 free(info
->checkout
);
130 static int post_checkout_hook(struct commit
*old_commit
, struct commit
*new_commit
,
133 return run_hooks_l(the_repository
, "post-checkout",
134 oid_to_hex(old_commit
? &old_commit
->object
.oid
: null_oid(the_hash_algo
)),
135 oid_to_hex(new_commit
? &new_commit
->object
.oid
: null_oid(the_hash_algo
)),
136 changed
? "1" : "0", NULL
);
137 /* "new_commit" can be NULL when checking out from the index before
142 static int update_some(const struct object_id
*oid
, struct strbuf
*base
,
143 const char *pathname
, unsigned mode
, void *context UNUSED
)
146 struct cache_entry
*ce
;
150 return READ_TREE_RECURSIVE
;
152 len
= base
->len
+ strlen(pathname
);
153 ce
= make_empty_cache_entry(the_repository
->index
, len
);
154 oidcpy(&ce
->oid
, oid
);
155 memcpy(ce
->name
, base
->buf
, base
->len
);
156 memcpy(ce
->name
+ base
->len
, pathname
, len
- base
->len
);
157 ce
->ce_flags
= create_ce_flags(0) | CE_UPDATE
;
158 ce
->ce_namelen
= len
;
159 ce
->ce_mode
= create_ce_mode(mode
);
162 * If the entry is the same as the current index, we can leave the old
163 * entry in place. Whether it is UPTODATE or not, checkout_entry will
164 * do the right thing.
166 pos
= index_name_pos(the_repository
->index
, ce
->name
, ce
->ce_namelen
);
168 struct cache_entry
*old
= the_repository
->index
->cache
[pos
];
169 if (ce
->ce_mode
== old
->ce_mode
&&
170 !ce_intent_to_add(old
) &&
171 oideq(&ce
->oid
, &old
->oid
)) {
172 old
->ce_flags
|= CE_UPDATE
;
173 discard_cache_entry(ce
);
178 add_index_entry(the_repository
->index
, ce
,
179 ADD_CACHE_OK_TO_ADD
| ADD_CACHE_OK_TO_REPLACE
);
183 static int read_tree_some(struct tree
*tree
, const struct pathspec
*pathspec
)
185 read_tree(the_repository
, tree
,
186 pathspec
, update_some
, NULL
);
188 /* update the index with the given tree's info
189 * for all args, expanding wildcards, and exit
190 * with any non-zero return code.
195 static int skip_same_name(const struct cache_entry
*ce
, int pos
)
197 while (++pos
< the_repository
->index
->cache_nr
&&
198 !strcmp(the_repository
->index
->cache
[pos
]->name
, ce
->name
))
203 static int check_stage(int stage
, const struct cache_entry
*ce
, int pos
,
206 while (pos
< the_repository
->index
->cache_nr
&&
207 !strcmp(the_repository
->index
->cache
[pos
]->name
, ce
->name
)) {
208 if (ce_stage(the_repository
->index
->cache
[pos
]) == stage
)
215 return error(_("path '%s' does not have our version"), ce
->name
);
217 return error(_("path '%s' does not have their version"), ce
->name
);
220 static int check_stages(unsigned stages
, const struct cache_entry
*ce
, int pos
)
223 const char *name
= ce
->name
;
225 while (pos
< the_repository
->index
->cache_nr
) {
226 ce
= the_repository
->index
->cache
[pos
];
227 if (strcmp(name
, ce
->name
))
229 seen
|= (1 << ce_stage(ce
));
232 if ((stages
& seen
) != stages
)
233 return error(_("path '%s' does not have all necessary versions"),
238 static int checkout_stage(int stage
, const struct cache_entry
*ce
, int pos
,
239 const struct checkout
*state
, int *nr_checkouts
,
242 while (pos
< the_repository
->index
->cache_nr
&&
243 !strcmp(the_repository
->index
->cache
[pos
]->name
, ce
->name
)) {
244 if (ce_stage(the_repository
->index
->cache
[pos
]) == stage
)
245 return checkout_entry(the_repository
->index
->cache
[pos
], state
,
250 unlink_entry(ce
, NULL
);
254 return error(_("path '%s' does not have our version"), ce
->name
);
256 return error(_("path '%s' does not have their version"), ce
->name
);
259 static int checkout_merged(int pos
, const struct checkout
*state
,
260 int *nr_checkouts
, struct mem_pool
*ce_mem_pool
,
263 struct cache_entry
*ce
= the_repository
->index
->cache
[pos
];
264 const char *path
= ce
->name
;
265 mmfile_t ancestor
, ours
, theirs
;
266 enum ll_merge_result merge_status
;
268 struct object_id oid
;
269 mmbuffer_t result_buf
;
270 struct object_id threeway
[3];
272 struct ll_merge_options ll_opts
= LL_MERGE_OPTIONS_INIT
;
275 memset(threeway
, 0, sizeof(threeway
));
276 while (pos
< the_repository
->index
->cache_nr
) {
278 stage
= ce_stage(ce
);
279 if (!stage
|| strcmp(path
, ce
->name
))
281 oidcpy(&threeway
[stage
- 1], &ce
->oid
);
283 mode
= create_ce_mode(ce
->ce_mode
);
285 ce
= the_repository
->index
->cache
[pos
];
287 if (is_null_oid(&threeway
[1]) || is_null_oid(&threeway
[2]))
288 return error(_("path '%s' does not have necessary versions"), path
);
290 read_mmblob(&ancestor
, &threeway
[0]);
291 read_mmblob(&ours
, &threeway
[1]);
292 read_mmblob(&theirs
, &threeway
[2]);
294 git_config_get_bool("merge.renormalize", &renormalize
);
295 ll_opts
.renormalize
= renormalize
;
296 ll_opts
.conflict_style
= conflict_style
;
297 merge_status
= ll_merge(&result_buf
, path
, &ancestor
, "base",
298 &ours
, "ours", &theirs
, "theirs",
299 state
->istate
, &ll_opts
);
303 if (merge_status
== LL_MERGE_BINARY_CONFLICT
)
304 warning("Cannot merge binary files: %s (%s vs. %s)",
305 path
, "ours", "theirs");
306 if (merge_status
< 0 || !result_buf
.ptr
) {
307 free(result_buf
.ptr
);
308 return error(_("path '%s': cannot merge"), path
);
313 * There is absolutely no reason to write this as a blob object
314 * and create a phony cache entry. This hack is primarily to get
315 * to the write_entry() machinery that massages the contents to
316 * work-tree format and writes out which only allows it for a
317 * cache entry. The code in write_entry() needs to be refactored
318 * to allow us to feed a <buffer, size, mode> instead of a cache
319 * entry. Such a refactoring would help merge_recursive as well
320 * (it also writes the merge result to the object database even
321 * when it may contain conflicts).
323 if (write_object_file(result_buf
.ptr
, result_buf
.size
, OBJ_BLOB
, &oid
))
324 die(_("Unable to add merge result for '%s'"), path
);
325 free(result_buf
.ptr
);
326 ce
= make_transient_cache_entry(mode
, &oid
, path
, 2, ce_mem_pool
);
328 die(_("make_cache_entry failed for path '%s'"), path
);
329 status
= checkout_entry(ce
, state
, NULL
, nr_checkouts
);
333 static void mark_ce_for_checkout_overlay(struct cache_entry
*ce
,
335 const struct checkout_opts
*opts
)
337 ce
->ce_flags
&= ~CE_MATCHED
;
338 if (!opts
->ignore_skipworktree
&& ce_skip_worktree(ce
))
340 if (opts
->source_tree
&& !(ce
->ce_flags
& CE_UPDATE
))
342 * "git checkout tree-ish -- path", but this entry
343 * is in the original index but is not in tree-ish
344 * or does not match the pathspec; it will not be
345 * checked out to the working tree. We will not do
346 * anything to this entry at all.
350 * Either this entry came from the tree-ish we are
351 * checking the paths out of, or we are checking out
354 * If it comes from the tree-ish, we already know it
355 * matches the pathspec and could just stamp
356 * CE_MATCHED to it from update_some(). But we still
357 * need ps_matched and read_tree (and
358 * eventually tree_entry_interesting) cannot fill
359 * ps_matched yet. Once it can, we can avoid calling
360 * match_pathspec() for _all_ entries when
361 * opts->source_tree != NULL.
363 if (ce_path_match(the_repository
->index
, ce
, &opts
->pathspec
, ps_matched
))
364 ce
->ce_flags
|= CE_MATCHED
;
367 static void mark_ce_for_checkout_no_overlay(struct cache_entry
*ce
,
369 const struct checkout_opts
*opts
)
371 ce
->ce_flags
&= ~CE_MATCHED
;
372 if (!opts
->ignore_skipworktree
&& ce_skip_worktree(ce
))
374 if (ce_path_match(the_repository
->index
, ce
, &opts
->pathspec
, ps_matched
)) {
375 ce
->ce_flags
|= CE_MATCHED
;
376 if (opts
->source_tree
&& !(ce
->ce_flags
& CE_UPDATE
))
378 * In overlay mode, but the path is not in
379 * tree-ish, which means we should remove it
380 * from the index and the working tree.
382 ce
->ce_flags
|= CE_REMOVE
| CE_WT_REMOVE
;
386 static int checkout_worktree(const struct checkout_opts
*opts
,
387 const struct branch_info
*info
)
389 struct checkout state
= CHECKOUT_INIT
;
390 int nr_checkouts
= 0, nr_unmerged
= 0;
393 int pc_workers
, pc_threshold
;
394 struct mem_pool ce_mem_pool
;
397 state
.refresh_cache
= 1;
398 state
.istate
= the_repository
->index
;
400 mem_pool_init(&ce_mem_pool
, 0);
401 get_parallel_checkout_configs(&pc_workers
, &pc_threshold
);
402 init_checkout_metadata(&state
.meta
, info
->refname
,
403 info
->commit
? &info
->commit
->object
.oid
: &info
->oid
,
406 enable_delayed_checkout(&state
);
409 init_parallel_checkout();
411 for (pos
= 0; pos
< the_repository
->index
->cache_nr
; pos
++) {
412 struct cache_entry
*ce
= the_repository
->index
->cache
[pos
];
413 if (ce
->ce_flags
& CE_MATCHED
) {
415 errs
|= checkout_entry(ce
, &state
,
416 NULL
, &nr_checkouts
);
419 if (opts
->writeout_stage
)
420 errs
|= checkout_stage(opts
->writeout_stage
,
423 &nr_checkouts
, opts
->overlay_mode
);
424 else if (opts
->merge
)
425 errs
|= checkout_merged(pos
, &state
,
428 opts
->conflict_style
);
429 pos
= skip_same_name(ce
, pos
) - 1;
433 errs
|= run_parallel_checkout(&state
, pc_workers
, pc_threshold
,
435 mem_pool_discard(&ce_mem_pool
, should_validate_cache_entries());
436 remove_marked_cache_entries(the_repository
->index
, 1);
437 remove_scheduled_dirs();
438 errs
|= finish_delayed_checkout(&state
, opts
->show_progress
);
440 if (opts
->count_checkout_paths
) {
442 fprintf_ln(stderr
, Q_("Recreated %d merge conflict",
443 "Recreated %d merge conflicts",
446 if (opts
->source_tree
)
447 fprintf_ln(stderr
, Q_("Updated %d path from %s",
448 "Updated %d paths from %s",
451 repo_find_unique_abbrev(the_repository
, &opts
->source_tree
->object
.oid
,
453 else if (!nr_unmerged
|| nr_checkouts
)
454 fprintf_ln(stderr
, Q_("Updated %d path from the index",
455 "Updated %d paths from the index",
463 static int checkout_paths(const struct checkout_opts
*opts
,
464 const struct branch_info
*new_branch_info
)
467 static char *ps_matched
;
468 struct object_id rev
;
471 struct lock_file lock_file
= LOCK_INIT
;
474 trace2_cmd_mode(opts
->patch_mode
? "patch" : "path");
476 if (opts
->track
!= BRANCH_TRACK_UNSPECIFIED
)
477 die(_("'%s' cannot be used with updating paths"), "--track");
479 if (opts
->new_branch_log
)
480 die(_("'%s' cannot be used with updating paths"), "-l");
482 if (opts
->ignore_unmerged
&& opts
->patch_mode
)
483 die(_("'%s' cannot be used with updating paths"),
484 opts
->ignore_unmerged_opt
);
486 if (opts
->force_detach
)
487 die(_("'%s' cannot be used with updating paths"), "--detach");
489 if (opts
->merge
&& opts
->patch_mode
)
490 die(_("options '%s' and '%s' cannot be used together"), "--merge", "--patch");
492 if (opts
->ignore_unmerged
&& opts
->merge
)
493 die(_("options '%s' and '%s' cannot be used together"),
494 opts
->ignore_unmerged_opt
, "-m");
496 if (opts
->new_branch
)
497 die(_("Cannot update paths and switch to branch '%s' at the same time."),
500 if (!opts
->checkout_worktree
&& !opts
->checkout_index
)
501 die(_("neither '%s' or '%s' is specified"),
502 "--staged", "--worktree");
504 if (!opts
->checkout_worktree
&& !opts
->from_treeish
)
505 die(_("'%s' must be used when '%s' is not specified"),
506 "--worktree", "--source");
509 * Reject --staged option to the restore command when combined with
510 * merge-related options. Use the accept_ref flag to distinguish it
511 * from the checkout command, which does not accept --staged anyway.
513 * `restore --ours|--theirs --worktree --staged` could mean resolving
514 * conflicted paths to one side in both the worktree and the index,
515 * but does not currently.
517 * `restore --merge|--conflict=<style>` already recreates conflicts
518 * in both the worktree and the index, so adding --staged would be
521 if (!opts
->accept_ref
&& opts
->checkout_index
) {
522 if (opts
->writeout_stage
)
523 die(_("'%s' or '%s' cannot be used with %s"),
524 "--ours", "--theirs", "--staged");
527 die(_("'%s' or '%s' cannot be used with %s"),
528 "--merge", "--conflict", "--staged");
532 * recreating unmerged index entries and writing out data from
533 * unmerged index entries would make no sense when checking out
536 if ((opts
->merge
|| opts
->writeout_stage
) && opts
->source_tree
)
537 die(_("'%s', '%s', or '%s' cannot be used when checking out of a tree"),
538 "--merge", "--ours", "--theirs");
540 if (opts
->patch_mode
) {
541 enum add_p_mode patch_mode
;
542 const char *rev
= new_branch_info
->name
;
543 char rev_oid
[GIT_MAX_HEXSZ
+ 1];
546 * Since rev can be in the form of `<a>...<b>` (which is not
547 * recognized by diff-index), we will always replace the name
548 * with the hex of the commit (whether it's in `...` form or
549 * not) for the run_add_interactive() machinery to work
550 * properly. However, there is special logic for the HEAD case
551 * so we mustn't replace that. Also, when we were given a
552 * tree-object, new_branch_info->commit would be NULL, but we
553 * do not have to do any replacement, either.
555 if (rev
&& new_branch_info
->commit
&& strcmp(rev
, "HEAD"))
556 rev
= oid_to_hex_r(rev_oid
, &new_branch_info
->commit
->object
.oid
);
558 if (opts
->checkout_index
&& opts
->checkout_worktree
)
559 patch_mode
= ADD_P_CHECKOUT
;
560 else if (opts
->checkout_index
&& !opts
->checkout_worktree
)
561 patch_mode
= ADD_P_RESET
;
562 else if (!opts
->checkout_index
&& opts
->checkout_worktree
)
563 patch_mode
= ADD_P_WORKTREE
;
565 BUG("either flag must have been set, worktree=%d, index=%d",
566 opts
->checkout_worktree
, opts
->checkout_index
);
567 return !!run_add_p(the_repository
, patch_mode
, rev
,
571 repo_hold_locked_index(the_repository
, &lock_file
, LOCK_DIE_ON_ERROR
);
572 if (repo_read_index_preload(the_repository
, &opts
->pathspec
, 0) < 0)
573 return error(_("index file corrupt"));
575 if (opts
->source_tree
)
576 read_tree_some(opts
->source_tree
, &opts
->pathspec
);
578 unmerge_index(the_repository
->index
, &opts
->pathspec
, CE_MATCHED
);
580 ps_matched
= xcalloc(opts
->pathspec
.nr
, 1);
583 * Make sure all pathspecs participated in locating the paths
586 for (pos
= 0; pos
< the_repository
->index
->cache_nr
; pos
++)
587 if (opts
->overlay_mode
)
588 mark_ce_for_checkout_overlay(the_repository
->index
->cache
[pos
],
592 mark_ce_for_checkout_no_overlay(the_repository
->index
->cache
[pos
],
596 if (report_path_error(ps_matched
, &opts
->pathspec
)) {
602 /* Any unmerged paths? */
603 for (pos
= 0; pos
< the_repository
->index
->cache_nr
; pos
++) {
604 const struct cache_entry
*ce
= the_repository
->index
->cache
[pos
];
605 if (ce
->ce_flags
& CE_MATCHED
) {
608 if (opts
->ignore_unmerged
) {
610 warning(_("path '%s' is unmerged"), ce
->name
);
611 } else if (opts
->writeout_stage
) {
612 errs
|= check_stage(opts
->writeout_stage
, ce
, pos
, opts
->overlay_mode
);
613 } else if (opts
->merge
) {
614 errs
|= check_stages((1<<2) | (1<<3), ce
, pos
);
617 error(_("path '%s' is unmerged"), ce
->name
);
619 pos
= skip_same_name(ce
, pos
) - 1;
625 /* Now we are committed to check them out */
626 if (opts
->checkout_worktree
)
627 errs
|= checkout_worktree(opts
, new_branch_info
);
629 remove_marked_cache_entries(the_repository
->index
, 1);
632 * Allow updating the index when checking out from the index.
633 * This is to save new stat info.
635 if (opts
->checkout_worktree
&& !opts
->checkout_index
&& !opts
->source_tree
)
638 checkout_index
= opts
->checkout_index
;
640 if (checkout_index
) {
641 if (write_locked_index(the_repository
->index
, &lock_file
, COMMIT_LOCK
))
642 die(_("unable to write new index file"));
645 * NEEDSWORK: if --worktree is not specified, we
646 * should save stat info of checked out files in the
647 * index to avoid the next (potentially costly)
648 * refresh. But it's a bit tricker to do...
650 rollback_lock_file(&lock_file
);
653 refs_read_ref_full(get_main_ref_store(the_repository
), "HEAD", 0,
655 head
= lookup_commit_reference_gently(the_repository
, &rev
, 1);
657 errs
|= post_checkout_hook(head
, head
, 0);
661 static void show_local_changes(struct object
*head
,
662 const struct diff_options
*opts
)
665 /* I think we want full paths, even if we're in a subdirectory. */
666 repo_init_revisions(the_repository
, &rev
, NULL
);
667 rev
.diffopt
.flags
= opts
->flags
;
668 rev
.diffopt
.output_format
|= DIFF_FORMAT_NAME_STATUS
;
669 rev
.diffopt
.flags
.recursive
= 1;
670 diff_setup_done(&rev
.diffopt
);
671 add_pending_object(&rev
, head
, NULL
);
672 run_diff_index(&rev
, 0);
673 release_revisions(&rev
);
676 static void describe_detached_head(const char *msg
, struct commit
*commit
)
678 struct strbuf sb
= STRBUF_INIT
;
680 if (!repo_parse_commit(the_repository
, commit
))
681 pp_commit_easy(CMIT_FMT_ONELINE
, commit
, &sb
);
682 if (print_sha1_ellipsis()) {
683 fprintf(stderr
, "%s %s... %s\n", msg
,
684 repo_find_unique_abbrev(the_repository
, &commit
->object
.oid
, DEFAULT_ABBREV
),
687 fprintf(stderr
, "%s %s %s\n", msg
,
688 repo_find_unique_abbrev(the_repository
, &commit
->object
.oid
, DEFAULT_ABBREV
),
694 static int reset_tree(struct tree
*tree
, const struct checkout_opts
*o
,
695 int worktree
, int *writeout_error
,
696 struct branch_info
*info
)
698 struct unpack_trees_options opts
;
699 struct tree_desc tree_desc
;
701 memset(&opts
, 0, sizeof(opts
));
703 opts
.update
= worktree
;
704 opts
.skip_unmerged
= !worktree
;
705 opts
.reset
= o
->force
? UNPACK_RESET_OVERWRITE_UNTRACKED
:
706 UNPACK_RESET_PROTECT_UNTRACKED
;
707 opts
.preserve_ignored
= (!o
->force
&& !o
->overwrite_ignore
);
709 opts
.fn
= oneway_merge
;
710 opts
.verbose_update
= o
->show_progress
;
711 opts
.src_index
= the_repository
->index
;
712 opts
.dst_index
= the_repository
->index
;
713 init_checkout_metadata(&opts
.meta
, info
->refname
,
714 info
->commit
? &info
->commit
->object
.oid
: null_oid(the_hash_algo
),
716 if (parse_tree(tree
) < 0)
718 init_tree_desc(&tree_desc
, &tree
->object
.oid
, tree
->buffer
, tree
->size
);
719 switch (unpack_trees(1, &tree_desc
, &opts
)) {
723 * We return 0 nevertheless, as the index is all right
724 * and more importantly we have made best efforts to
725 * update paths in the work tree, and we cannot revert
736 static void setup_branch_path(struct branch_info
*branch
)
738 struct strbuf buf
= STRBUF_INIT
;
741 * If this is a ref, resolve it; otherwise, look up the OID for our
742 * expression. Failure here is okay.
744 if (!repo_dwim_ref(the_repository
, branch
->name
, strlen(branch
->name
),
745 &branch
->oid
, &branch
->refname
, 0))
746 repo_get_oid_committish(the_repository
, branch
->name
, &branch
->oid
);
748 copy_branchname(&buf
, branch
->name
, INTERPRET_BRANCH_LOCAL
);
749 if (strcmp(buf
.buf
, branch
->name
)) {
751 branch
->name
= xstrdup(buf
.buf
);
753 strbuf_splice(&buf
, 0, 0, "refs/heads/", 11);
755 branch
->path
= strbuf_detach(&buf
, NULL
);
758 static void init_topts(struct unpack_trees_options
*topts
, int merge
,
759 int show_progress
, int overwrite_ignore
,
760 struct commit
*old_commit
)
762 memset(topts
, 0, sizeof(*topts
));
763 topts
->head_idx
= -1;
764 topts
->src_index
= the_repository
->index
;
765 topts
->dst_index
= the_repository
->index
;
767 setup_unpack_trees_porcelain(topts
, "checkout");
769 topts
->initial_checkout
= is_index_unborn(the_repository
->index
);
772 topts
->quiet
= merge
&& old_commit
;
773 topts
->verbose_update
= show_progress
;
774 topts
->fn
= twoway_merge
;
775 topts
->preserve_ignored
= !overwrite_ignore
;
778 static int merge_working_tree(const struct checkout_opts
*opts
,
779 struct branch_info
*old_branch_info
,
780 struct branch_info
*new_branch_info
,
784 struct lock_file lock_file
= LOCK_INIT
;
785 struct tree
*new_tree
;
787 repo_hold_locked_index(the_repository
, &lock_file
, LOCK_DIE_ON_ERROR
);
788 if (repo_read_index_preload(the_repository
, NULL
, 0) < 0)
789 return error(_("index file corrupt"));
791 resolve_undo_clear_index(the_repository
->index
);
792 if (opts
->new_orphan_branch
&& opts
->orphan_from_empty_tree
) {
793 if (new_branch_info
->commit
)
794 BUG("'switch --orphan' should never accept a commit as starting point");
795 new_tree
= parse_tree_indirect(the_hash_algo
->empty_tree
);
797 BUG("unable to read empty tree");
799 new_tree
= repo_get_commit_tree(the_repository
,
800 new_branch_info
->commit
);
802 return error(_("unable to read tree (%s)"),
803 oid_to_hex(&new_branch_info
->commit
->object
.oid
));
805 if (opts
->discard_changes
) {
806 ret
= reset_tree(new_tree
, opts
, 1, writeout_error
, new_branch_info
);
810 struct tree_desc trees
[2];
812 struct unpack_trees_options topts
;
813 const struct object_id
*old_commit_oid
;
815 refresh_index(the_repository
->index
, REFRESH_QUIET
, NULL
, NULL
, NULL
);
817 if (unmerged_index(the_repository
->index
)) {
818 error(_("you need to resolve your current index first"));
822 /* 2-way merge to the new branch */
823 init_topts(&topts
, opts
->merge
, opts
->show_progress
,
824 opts
->overwrite_ignore
, old_branch_info
->commit
);
825 init_checkout_metadata(&topts
.meta
, new_branch_info
->refname
,
826 new_branch_info
->commit
?
827 &new_branch_info
->commit
->object
.oid
:
828 &new_branch_info
->oid
, NULL
);
830 old_commit_oid
= old_branch_info
->commit
?
831 &old_branch_info
->commit
->object
.oid
:
832 the_hash_algo
->empty_tree
;
833 tree
= parse_tree_indirect(old_commit_oid
);
835 die(_("unable to parse commit %s"),
836 oid_to_hex(old_commit_oid
));
838 init_tree_desc(&trees
[0], &tree
->object
.oid
,
839 tree
->buffer
, tree
->size
);
840 if (parse_tree(new_tree
) < 0)
843 init_tree_desc(&trees
[1], &tree
->object
.oid
,
844 tree
->buffer
, tree
->size
);
846 ret
= unpack_trees(2, trees
, &topts
);
847 clear_unpack_trees_porcelain(&topts
);
850 * Unpack couldn't do a trivial merge; either
851 * give up or do a real merge, depending on
852 * whether the merge flag was used.
855 struct tree
*old_tree
;
856 struct merge_options o
;
857 struct strbuf sb
= STRBUF_INIT
;
858 struct strbuf old_commit_shortname
= STRBUF_INIT
;
864 * Without old_branch_info->commit, the below is the same as
865 * the two-tree unpack we already tried and failed.
867 if (!old_branch_info
->commit
)
869 old_tree
= repo_get_commit_tree(the_repository
,
870 old_branch_info
->commit
);
872 if (repo_index_has_changes(the_repository
, old_tree
, &sb
))
873 die(_("cannot continue with staged changes in "
874 "the following files:\n%s"), sb
.buf
);
877 /* Do more real merge */
880 * We update the index fully, then write the
881 * tree from the index, then merge the new
882 * branch with the current tree, with the old
883 * branch as the base. Then we reset the index
884 * (but not the working tree) to the new
885 * branch, leaving the working tree as the
886 * merged version, but skipping unmerged
887 * entries in the index.
890 add_files_to_cache(the_repository
, NULL
, NULL
, NULL
, 0,
892 init_ui_merge_options(&o
, the_repository
);
894 work
= write_in_core_index_as_tree(the_repository
);
896 ret
= reset_tree(new_tree
,
898 writeout_error
, new_branch_info
);
901 o
.ancestor
= old_branch_info
->name
;
902 if (!old_branch_info
->name
) {
903 strbuf_add_unique_abbrev(&old_commit_shortname
,
904 &old_branch_info
->commit
->object
.oid
,
906 o
.ancestor
= old_commit_shortname
.buf
;
908 o
.branch1
= new_branch_info
->name
;
910 o
.conflict_style
= opts
->conflict_style
;
911 ret
= merge_ort_nonrecursive(&o
,
917 ret
= reset_tree(new_tree
,
919 writeout_error
, new_branch_info
);
920 strbuf_release(&o
.obuf
);
921 strbuf_release(&old_commit_shortname
);
927 if (!cache_tree_fully_valid(the_repository
->index
->cache_tree
))
928 cache_tree_update(the_repository
->index
, WRITE_TREE_SILENT
| WRITE_TREE_REPAIR
);
930 if (write_locked_index(the_repository
->index
, &lock_file
, COMMIT_LOCK
))
931 die(_("unable to write new index file"));
933 if (!opts
->discard_changes
&& !opts
->quiet
&& new_branch_info
->commit
)
934 show_local_changes(&new_branch_info
->commit
->object
, &opts
->diff_options
);
939 static void report_tracking(struct branch_info
*new_branch_info
)
941 struct strbuf sb
= STRBUF_INIT
;
942 struct branch
*branch
= branch_get(new_branch_info
->name
);
944 if (!format_tracking_info(branch
, &sb
, AHEAD_BEHIND_FULL
, 1))
946 fputs(sb
.buf
, stdout
);
950 static void update_refs_for_switch(const struct checkout_opts
*opts
,
951 struct branch_info
*old_branch_info
,
952 struct branch_info
*new_branch_info
)
954 struct strbuf msg
= STRBUF_INIT
;
955 const char *old_desc
, *reflog_msg
;
956 if (opts
->new_branch
) {
957 if (opts
->new_orphan_branch
) {
958 enum log_refs_config log_all_ref_updates
=
959 repo_settings_get_log_all_ref_updates(the_repository
);
962 refname
= mkpathdup("refs/heads/%s", opts
->new_orphan_branch
);
963 if (opts
->new_branch_log
&&
964 !should_autocreate_reflog(log_all_ref_updates
, refname
)) {
966 struct strbuf err
= STRBUF_INIT
;
968 ret
= refs_create_reflog(get_main_ref_store(the_repository
),
971 fprintf(stderr
, _("Can not do reflog for '%s': %s\n"),
972 opts
->new_orphan_branch
, err
.buf
);
973 strbuf_release(&err
);
977 strbuf_release(&err
);
982 create_branch(the_repository
,
983 opts
->new_branch
, new_branch_info
->name
,
984 opts
->new_branch_force
? 1 : 0,
985 opts
->new_branch_force
? 1 : 0,
986 opts
->new_branch_log
,
990 free(new_branch_info
->name
);
991 free(new_branch_info
->refname
);
992 new_branch_info
->name
= xstrdup(opts
->new_branch
);
993 setup_branch_path(new_branch_info
);
996 old_desc
= old_branch_info
->name
;
997 if (!old_desc
&& old_branch_info
->commit
)
998 old_desc
= oid_to_hex(&old_branch_info
->commit
->object
.oid
);
1000 reflog_msg
= getenv("GIT_REFLOG_ACTION");
1002 strbuf_addf(&msg
, "checkout: moving from %s to %s",
1003 old_desc
? old_desc
: "(invalid)", new_branch_info
->name
);
1005 strbuf_insertstr(&msg
, 0, reflog_msg
);
1007 if (!strcmp(new_branch_info
->name
, "HEAD") && !new_branch_info
->path
&& !opts
->force_detach
) {
1008 /* Nothing to do. */
1009 } else if (opts
->force_detach
|| !new_branch_info
->path
) { /* No longer on any branch. */
1010 refs_update_ref(get_main_ref_store(the_repository
), msg
.buf
,
1011 "HEAD", &new_branch_info
->commit
->object
.oid
,
1013 REF_NO_DEREF
, UPDATE_REFS_DIE_ON_ERR
);
1015 if (old_branch_info
->path
&&
1016 advice_enabled(ADVICE_DETACHED_HEAD
) && !opts
->force_detach
)
1017 detach_advice(new_branch_info
->name
);
1018 describe_detached_head(_("HEAD is now at"), new_branch_info
->commit
);
1020 } else if (new_branch_info
->path
) { /* Switch branches. */
1021 if (refs_update_symref(get_main_ref_store(the_repository
), "HEAD", new_branch_info
->path
, msg
.buf
) < 0)
1022 die(_("unable to update HEAD"));
1024 if (old_branch_info
->path
&& !strcmp(new_branch_info
->path
, old_branch_info
->path
)) {
1025 if (opts
->new_branch_force
)
1026 fprintf(stderr
, _("Reset branch '%s'\n"),
1027 new_branch_info
->name
);
1029 fprintf(stderr
, _("Already on '%s'\n"),
1030 new_branch_info
->name
);
1031 } else if (opts
->new_branch
) {
1032 if (opts
->branch_exists
)
1033 fprintf(stderr
, _("Switched to and reset branch '%s'\n"), new_branch_info
->name
);
1035 fprintf(stderr
, _("Switched to a new branch '%s'\n"), new_branch_info
->name
);
1037 fprintf(stderr
, _("Switched to branch '%s'\n"),
1038 new_branch_info
->name
);
1041 if (old_branch_info
->path
&& old_branch_info
->name
) {
1042 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
))
1043 refs_delete_reflog(get_main_ref_store(the_repository
),
1044 old_branch_info
->path
);
1047 remove_branch_state(the_repository
, !opts
->quiet
);
1048 strbuf_release(&msg
);
1050 !opts
->force_detach
&&
1051 (new_branch_info
->path
|| !strcmp(new_branch_info
->name
, "HEAD")))
1052 report_tracking(new_branch_info
);
1055 static int add_pending_uninteresting_ref(const char *refname
, const char *referent UNUSED
,
1056 const struct object_id
*oid
,
1057 int flags UNUSED
, void *cb_data
)
1059 add_pending_oid(cb_data
, refname
, oid
, UNINTERESTING
);
1063 static void describe_one_orphan(struct strbuf
*sb
, struct commit
*commit
)
1065 strbuf_addstr(sb
, " ");
1066 strbuf_add_unique_abbrev(sb
, &commit
->object
.oid
, DEFAULT_ABBREV
);
1067 strbuf_addch(sb
, ' ');
1068 if (!repo_parse_commit(the_repository
, commit
))
1069 pp_commit_easy(CMIT_FMT_ONELINE
, commit
, sb
);
1070 strbuf_addch(sb
, '\n');
1073 #define ORPHAN_CUTOFF 4
1074 static void suggest_reattach(struct commit
*commit
, struct rev_info
*revs
)
1076 struct commit
*c
, *last
= NULL
;
1077 struct strbuf sb
= STRBUF_INIT
;
1079 while ((c
= get_revision(revs
)) != NULL
) {
1080 if (lost
< ORPHAN_CUTOFF
)
1081 describe_one_orphan(&sb
, c
);
1085 if (ORPHAN_CUTOFF
< lost
) {
1086 int more
= lost
- ORPHAN_CUTOFF
;
1088 describe_one_orphan(&sb
, last
);
1090 strbuf_addf(&sb
, _(" ... and %d more.\n"), more
);
1095 /* The singular version */
1096 "Warning: you are leaving %d commit behind, "
1097 "not connected to\n"
1098 "any of your branches:\n\n"
1100 /* The plural version */
1101 "Warning: you are leaving %d commits behind, "
1102 "not connected to\n"
1103 "any of your branches:\n\n"
1105 /* Give ngettext() the count */
1109 strbuf_release(&sb
);
1111 if (advice_enabled(ADVICE_DETACHED_HEAD
))
1114 /* The singular version */
1115 "If you want to keep it by creating a new branch, "
1116 "this may be a good time\nto do so with:\n\n"
1117 " git branch <new-branch-name> %s\n\n",
1118 /* The plural version */
1119 "If you want to keep them by creating a new branch, "
1120 "this may be a good time\nto do so with:\n\n"
1121 " git branch <new-branch-name> %s\n\n",
1122 /* Give ngettext() the count */
1124 repo_find_unique_abbrev(the_repository
, &commit
->object
.oid
, DEFAULT_ABBREV
));
1128 * We are about to leave commit that was at the tip of a detached
1129 * HEAD. If it is not reachable from any ref, this is the last chance
1130 * for the user to do so without resorting to reflog.
1132 static void orphaned_commit_warning(struct commit
*old_commit
, struct commit
*new_commit
)
1134 struct rev_info revs
;
1135 struct object
*object
= &old_commit
->object
;
1137 repo_init_revisions(the_repository
, &revs
, NULL
);
1138 setup_revisions(0, NULL
, &revs
, NULL
);
1140 object
->flags
&= ~UNINTERESTING
;
1141 add_pending_object(&revs
, object
, oid_to_hex(&object
->oid
));
1143 refs_for_each_ref(get_main_ref_store(the_repository
),
1144 add_pending_uninteresting_ref
, &revs
);
1146 add_pending_oid(&revs
, "HEAD",
1147 &new_commit
->object
.oid
,
1150 if (prepare_revision_walk(&revs
))
1151 die(_("internal error in revision walk"));
1152 if (!(old_commit
->object
.flags
& UNINTERESTING
))
1153 suggest_reattach(old_commit
, &revs
);
1155 describe_detached_head(_("Previous HEAD position was"), old_commit
);
1157 /* Clean up objects used, as they will be reused. */
1158 repo_clear_commit_marks(the_repository
, ALL_REV_FLAGS
);
1159 release_revisions(&revs
);
1162 static int switch_branches(const struct checkout_opts
*opts
,
1163 struct branch_info
*new_branch_info
)
1166 struct branch_info old_branch_info
= { 0 };
1167 struct object_id rev
;
1168 int flag
, writeout_error
= 0;
1171 trace2_cmd_mode("branch");
1173 memset(&old_branch_info
, 0, sizeof(old_branch_info
));
1174 old_branch_info
.path
= refs_resolve_refdup(get_main_ref_store(the_repository
),
1175 "HEAD", 0, &rev
, &flag
);
1176 if (old_branch_info
.path
)
1177 old_branch_info
.commit
= lookup_commit_reference_gently(the_repository
, &rev
, 1);
1178 if (!(flag
& REF_ISSYMREF
))
1179 FREE_AND_NULL(old_branch_info
.path
);
1181 if (old_branch_info
.path
) {
1182 const char *const prefix
= "refs/heads/";
1184 if (skip_prefix(old_branch_info
.path
, prefix
, &p
))
1185 old_branch_info
.name
= xstrdup(p
);
1188 if (opts
->new_orphan_branch
&& opts
->orphan_from_empty_tree
) {
1189 if (new_branch_info
->name
)
1190 BUG("'switch --orphan' should never accept a commit as starting point");
1191 new_branch_info
->commit
= NULL
;
1192 new_branch_info
->name
= xstrdup("(empty)");
1196 if (!new_branch_info
->name
) {
1197 new_branch_info
->name
= xstrdup("HEAD");
1198 new_branch_info
->commit
= old_branch_info
.commit
;
1199 if (!new_branch_info
->commit
)
1200 die(_("You are on a branch yet to be born"));
1201 parse_commit_or_die(new_branch_info
->commit
);
1203 if (opts
->only_merge_on_switching_branches
)
1208 ret
= merge_working_tree(opts
, &old_branch_info
, new_branch_info
, &writeout_error
);
1210 branch_info_release(&old_branch_info
);
1215 if (!opts
->quiet
&& !old_branch_info
.path
&& old_branch_info
.commit
&& new_branch_info
->commit
!= old_branch_info
.commit
)
1216 orphaned_commit_warning(old_branch_info
.commit
, new_branch_info
->commit
);
1218 update_refs_for_switch(opts
, &old_branch_info
, new_branch_info
);
1220 ret
= post_checkout_hook(old_branch_info
.commit
, new_branch_info
->commit
, 1);
1221 branch_info_release(&old_branch_info
);
1223 return ret
|| writeout_error
;
1226 static int git_checkout_config(const char *var
, const char *value
,
1227 const struct config_context
*ctx
, void *cb
)
1229 struct checkout_opts
*opts
= cb
;
1231 if (!strcmp(var
, "diff.ignoresubmodules")) {
1233 return config_error_nonbool(var
);
1234 handle_ignore_submodules_arg(&opts
->diff_options
, value
);
1237 if (!strcmp(var
, "checkout.guess")) {
1238 opts
->dwim_new_local_branch
= git_config_bool(var
, value
);
1242 if (starts_with(var
, "submodule."))
1243 return git_default_submodule_config(var
, value
, NULL
);
1245 return git_xmerge_config(var
, value
, ctx
, NULL
);
1248 static void setup_new_branch_info_and_source_tree(
1249 struct branch_info
*new_branch_info
,
1250 struct checkout_opts
*opts
,
1251 struct object_id
*rev
,
1254 struct tree
**source_tree
= &opts
->source_tree
;
1255 struct object_id branch_rev
;
1257 /* treat '@' as a shortcut for 'HEAD' */
1258 new_branch_info
->name
= !strcmp(arg
, "@") ? xstrdup("HEAD") :
1260 setup_branch_path(new_branch_info
);
1262 if (!check_refname_format(new_branch_info
->path
, 0) &&
1263 !refs_read_ref(get_main_ref_store(the_repository
), new_branch_info
->path
, &branch_rev
))
1264 oidcpy(rev
, &branch_rev
);
1266 /* not an existing branch */
1267 FREE_AND_NULL(new_branch_info
->path
);
1269 new_branch_info
->commit
= lookup_commit_reference_gently(the_repository
, rev
, 1);
1270 if (!new_branch_info
->commit
) {
1272 *source_tree
= parse_tree_indirect(rev
);
1274 die(_("unable to read tree (%s)"), oid_to_hex(rev
));
1276 parse_commit_or_die(new_branch_info
->commit
);
1277 *source_tree
= repo_get_commit_tree(the_repository
,
1278 new_branch_info
->commit
);
1280 die(_("unable to read tree (%s)"),
1281 oid_to_hex(&new_branch_info
->commit
->object
.oid
));
1285 static char *parse_remote_branch(const char *arg
,
1286 struct object_id
*rev
,
1287 int could_be_checkout_paths
)
1289 int num_matches
= 0;
1290 char *remote
= unique_tracking_name(arg
, rev
, &num_matches
);
1292 if (remote
&& could_be_checkout_paths
) {
1293 die(_("'%s' could be both a local file and a tracking branch.\n"
1294 "Please use -- (and optionally --no-guess) to disambiguate"),
1298 if (!remote
&& num_matches
> 1) {
1299 if (advice_enabled(ADVICE_CHECKOUT_AMBIGUOUS_REMOTE_BRANCH_NAME
)) {
1300 advise(_("If you meant to check out a remote tracking branch on, e.g. 'origin',\n"
1301 "you can do so by fully qualifying the name with the --track option:\n"
1303 " git checkout --track origin/<name>\n"
1305 "If you'd like to always have checkouts of an ambiguous <name> prefer\n"
1306 "one remote, e.g. the 'origin' remote, consider setting\n"
1307 "checkout.defaultRemote=origin in your config."));
1310 die(_("'%s' matched multiple (%d) remote tracking branches"),
1317 static int parse_branchname_arg(int argc
, const char **argv
,
1318 int dwim_new_local_branch_ok
,
1319 struct branch_info
*new_branch_info
,
1320 struct checkout_opts
*opts
,
1321 struct object_id
*rev
)
1323 const char **new_branch
= &opts
->new_branch
;
1326 char *remote
= NULL
;
1328 int has_dash_dash
= 0;
1332 * case 1: git checkout <ref> -- [<paths>]
1334 * <ref> must be a valid tree, everything after the '--' must be
1337 * case 2: git checkout -- [<paths>]
1339 * everything after the '--' must be paths.
1341 * case 3: git checkout <something> [--]
1343 * (a) If <something> is a commit, that is to
1344 * switch to the branch or detach HEAD at it. As a special case,
1345 * if <something> is A...B (missing A or B means HEAD but you can
1346 * omit at most one side), and if there is a unique merge base
1347 * between A and B, A...B names that merge base.
1349 * (b) If <something> is _not_ a commit, either "--" is present
1350 * or <something> is not a path, no -t or -b was given,
1351 * and there is a tracking branch whose name is <something>
1352 * in one and only one remote (or if the branch exists on the
1353 * remote named in checkout.defaultRemote), then this is a
1354 * short-hand to fork local <something> from that
1355 * remote-tracking branch.
1357 * (c) Otherwise, if "--" is present, treat it like case (1).
1360 * - if it's a reference, treat it like case (1)
1361 * - else if it's a path, treat it like case (2)
1364 * case 4: git checkout <something> <paths>
1366 * The first argument must not be ambiguous.
1367 * - If it's *only* a reference, treat it like case (1).
1368 * - If it's only a path, treat it like case (2).
1375 if (!opts
->accept_pathspec
) {
1377 die(_("only one reference expected"));
1378 has_dash_dash
= 1; /* helps disambiguate */
1383 for (i
= 0; i
< argc
; i
++) {
1384 if (opts
->accept_pathspec
&& !strcmp(argv
[i
], "--")) {
1389 if (dash_dash_pos
== 0)
1390 return 1; /* case (2) */
1391 else if (dash_dash_pos
== 1)
1392 has_dash_dash
= 1; /* case (3) or (1) */
1393 else if (dash_dash_pos
>= 2)
1394 die(_("only one reference expected, %d given."), dash_dash_pos
);
1395 opts
->count_checkout_paths
= !opts
->quiet
&& !has_dash_dash
;
1397 if (!strcmp(arg
, "-"))
1400 if (repo_get_oid_mb(the_repository
, arg
, rev
)) {
1402 * Either case (3) or (4), with <something> not being
1403 * a commit, or an attempt to use case (1) with an
1406 * It's likely an error, but we need to find out if
1407 * we should auto-create the branch, case (3).(b).
1409 int recover_with_dwim
= dwim_new_local_branch_ok
;
1411 int could_be_checkout_paths
= !has_dash_dash
&&
1412 check_filename(opts
->prefix
, arg
);
1414 if (!has_dash_dash
&& !no_wildcard(arg
))
1415 recover_with_dwim
= 0;
1418 * Accept "git checkout foo", "git checkout foo --"
1419 * and "git switch foo" as candidates for dwim.
1421 if (!(argc
== 1 && !has_dash_dash
) &&
1422 !(argc
== 2 && has_dash_dash
) &&
1423 opts
->accept_pathspec
)
1424 recover_with_dwim
= 0;
1426 if (recover_with_dwim
) {
1427 remote
= parse_remote_branch(arg
, rev
,
1428 could_be_checkout_paths
);
1432 /* DWIMmed to create local branch, case (3).(b) */
1434 recover_with_dwim
= 0;
1438 if (!recover_with_dwim
) {
1440 die(_("invalid reference: %s"), arg
);
1445 /* we can't end up being in (2) anymore, eat the argument */
1450 setup_new_branch_info_and_source_tree(new_branch_info
, opts
, rev
, arg
);
1452 if (!opts
->source_tree
) /* case (1): want a tree */
1453 die(_("reference is not a tree: %s"), arg
);
1455 if (!has_dash_dash
) { /* case (3).(d) -> (1) */
1457 * Do not complain the most common case
1458 * git checkout branch
1459 * even if there happen to be a file called 'branch';
1460 * it would be extremely annoying.
1463 verify_non_filename(opts
->prefix
, arg
);
1464 } else if (opts
->accept_pathspec
) {
1474 static int switch_unborn_to_new_branch(const struct checkout_opts
*opts
)
1477 struct strbuf branch_ref
= STRBUF_INIT
;
1479 trace2_cmd_mode("unborn");
1481 if (!opts
->new_branch
)
1482 die(_("You are on a branch yet to be born"));
1483 strbuf_addf(&branch_ref
, "refs/heads/%s", opts
->new_branch
);
1484 status
= refs_update_symref(get_main_ref_store(the_repository
),
1485 "HEAD", branch_ref
.buf
, "checkout -b");
1486 strbuf_release(&branch_ref
);
1488 fprintf(stderr
, _("Switched to a new branch '%s'\n"),
1493 static void die_expecting_a_branch(const struct branch_info
*branch_info
)
1495 struct object_id oid
;
1499 if (repo_dwim_ref(the_repository
, branch_info
->name
,
1500 strlen(branch_info
->name
), &oid
, &to_free
, 0) == 1) {
1501 const char *ref
= to_free
;
1503 if (skip_prefix(ref
, "refs/tags/", &ref
))
1504 code
= die_message(_("a branch is expected, got tag '%s'"), ref
);
1505 else if (skip_prefix(ref
, "refs/remotes/", &ref
))
1506 code
= die_message(_("a branch is expected, got remote branch '%s'"), ref
);
1508 code
= die_message(_("a branch is expected, got '%s'"), ref
);
1510 else if (branch_info
->commit
)
1511 code
= die_message(_("a branch is expected, got commit '%s'"), branch_info
->name
);
1514 * This case should never happen because we already die() on
1515 * non-commit, but just in case.
1517 code
= die_message(_("a branch is expected, got '%s'"), branch_info
->name
);
1519 if (advice_enabled(ADVICE_SUGGEST_DETACHING_HEAD
))
1520 advise(_("If you want to detach HEAD at the commit, try again with the --detach option."));
1525 static void die_if_some_operation_in_progress(void)
1527 struct wt_status_state state
;
1529 memset(&state
, 0, sizeof(state
));
1530 wt_status_get_state(the_repository
, &state
, 0);
1532 if (state
.merge_in_progress
)
1533 die(_("cannot switch branch while merging\n"
1534 "Consider \"git merge --quit\" "
1535 "or \"git worktree add\"."));
1536 if (state
.am_in_progress
)
1537 die(_("cannot switch branch in the middle of an am session\n"
1538 "Consider \"git am --quit\" "
1539 "or \"git worktree add\"."));
1540 if (state
.rebase_interactive_in_progress
|| state
.rebase_in_progress
)
1541 die(_("cannot switch branch while rebasing\n"
1542 "Consider \"git rebase --quit\" "
1543 "or \"git worktree add\"."));
1544 if (state
.cherry_pick_in_progress
)
1545 die(_("cannot switch branch while cherry-picking\n"
1546 "Consider \"git cherry-pick --quit\" "
1547 "or \"git worktree add\"."));
1548 if (state
.revert_in_progress
)
1549 die(_("cannot switch branch while reverting\n"
1550 "Consider \"git revert --quit\" "
1551 "or \"git worktree add\"."));
1552 if (state
.bisect_in_progress
)
1553 warning(_("you are switching branch while bisecting"));
1555 wt_status_state_free_buffers(&state
);
1559 * die if attempting to checkout an existing branch that is in use
1560 * in another worktree, unless ignore-other-wortrees option is given.
1561 * The check is bypassed when the branch is already the current one,
1562 * as it will not make things any worse.
1564 static void die_if_switching_to_a_branch_in_use(struct checkout_opts
*opts
,
1565 const char *full_ref
)
1570 if (opts
->ignore_other_worktrees
)
1572 head_ref
= refs_resolve_refdup(get_main_ref_store(the_repository
),
1573 "HEAD", 0, NULL
, &flags
);
1574 if (head_ref
&& (!(flags
& REF_ISSYMREF
) || strcmp(head_ref
, full_ref
)))
1575 die_if_checked_out(full_ref
, 1);
1579 static int checkout_branch(struct checkout_opts
*opts
,
1580 struct branch_info
*new_branch_info
)
1582 int noop_switch
= (!new_branch_info
->name
&&
1583 !opts
->new_branch
&&
1584 !opts
->force_detach
);
1586 if (opts
->pathspec
.nr
)
1587 die(_("paths cannot be used with switching branches"));
1589 if (opts
->patch_mode
)
1590 die(_("'%s' cannot be used with switching branches"),
1593 if (opts
->overlay_mode
!= -1)
1594 die(_("'%s' cannot be used with switching branches"),
1597 if (opts
->writeout_stage
) {
1600 msg
= _("'%s' needs the paths to check out");
1602 msg
= _("'%s' cannot be used with switching branches");
1603 die(msg
, "--ours/--theirs");
1606 if (opts
->force
&& opts
->merge
)
1607 die(_("'%s' cannot be used with '%s'"), "-f", "-m");
1609 if (opts
->discard_changes
&& opts
->merge
)
1610 die(_("'%s' cannot be used with '%s'"), "--discard-changes", "--merge");
1612 if (opts
->force_detach
&& opts
->new_branch
)
1613 die(_("'%s' cannot be used with '%s'"),
1614 "--detach", "-b/-B/--orphan");
1616 if (opts
->new_orphan_branch
) {
1617 if (opts
->track
!= BRANCH_TRACK_UNSPECIFIED
)
1618 die(_("'%s' cannot be used with '%s'"), "--orphan", "-t");
1619 if (opts
->orphan_from_empty_tree
&& new_branch_info
->name
)
1620 die(_("'%s' cannot take <start-point>"), "--orphan");
1621 } else if (opts
->force_detach
) {
1622 if (opts
->track
!= BRANCH_TRACK_UNSPECIFIED
)
1623 die(_("'%s' cannot be used with '%s'"), "--detach", "-t");
1624 } else if (opts
->track
== BRANCH_TRACK_UNSPECIFIED
)
1625 opts
->track
= git_branch_track
;
1627 if (new_branch_info
->name
&& !new_branch_info
->commit
)
1628 die(_("Cannot switch branch to a non-commit '%s'"),
1629 new_branch_info
->name
);
1632 !opts
->switch_branch_doing_nothing_is_ok
)
1633 die(_("missing branch or commit argument"));
1635 if (!opts
->implicit_detach
&&
1636 !opts
->force_detach
&&
1637 !opts
->new_branch
&&
1638 !opts
->new_branch_force
&&
1639 new_branch_info
->name
&&
1640 !new_branch_info
->path
)
1641 die_expecting_a_branch(new_branch_info
);
1643 if (!opts
->can_switch_when_in_progress
)
1644 die_if_some_operation_in_progress();
1646 /* "git checkout <branch>" */
1647 if (new_branch_info
->path
&& !opts
->force_detach
&& !opts
->new_branch
)
1648 die_if_switching_to_a_branch_in_use(opts
, new_branch_info
->path
);
1650 /* "git checkout -B <branch>" */
1651 if (opts
->new_branch_force
) {
1652 char *full_ref
= xstrfmt("refs/heads/%s", opts
->new_branch
);
1653 die_if_switching_to_a_branch_in_use(opts
, full_ref
);
1657 if (!new_branch_info
->commit
&& opts
->new_branch
) {
1658 struct object_id rev
;
1661 if (!refs_read_ref_full(get_main_ref_store(the_repository
), "HEAD", 0, &rev
, &flag
) &&
1662 (flag
& REF_ISSYMREF
) && is_null_oid(&rev
))
1663 return switch_unborn_to_new_branch(opts
);
1665 return switch_branches(opts
, new_branch_info
);
1668 static int parse_opt_conflict(const struct option
*o
, const char *arg
, int unset
)
1670 struct checkout_opts
*opts
= o
->value
;
1673 opts
->conflict_style
= -1;
1676 opts
->conflict_style
= parse_conflict_style_name(arg
);
1677 if (opts
->conflict_style
< 0)
1678 return error(_("unknown conflict style '%s'"), arg
);
1679 /* --conflict overrides a previous --no-merge */
1686 static struct option
*add_common_options(struct checkout_opts
*opts
,
1687 struct option
*prevopts
)
1689 struct option options
[] = {
1690 OPT__QUIET(&opts
->quiet
, N_("suppress progress reporting")),
1691 OPT_CALLBACK_F(0, "recurse-submodules", NULL
,
1692 "checkout", "control recursive updating of submodules",
1693 PARSE_OPT_OPTARG
, option_parse_recurse_submodules_worktree_updater
),
1694 OPT_BOOL(0, "progress", &opts
->show_progress
, N_("force progress reporting")),
1695 OPT_BOOL('m', "merge", &opts
->merge
, N_("perform a 3-way merge with the new branch")),
1696 OPT_CALLBACK(0, "conflict", opts
, N_("style"),
1697 N_("conflict style (merge, diff3, or zdiff3)"),
1698 parse_opt_conflict
),
1701 struct option
*newopts
= parse_options_concat(prevopts
, options
);
1706 static struct option
*add_common_switch_branch_options(
1707 struct checkout_opts
*opts
, struct option
*prevopts
)
1709 struct option options
[] = {
1710 OPT_BOOL('d', "detach", &opts
->force_detach
, N_("detach HEAD at named commit")),
1711 OPT_CALLBACK_F('t', "track", &opts
->track
, "(direct|inherit)",
1712 N_("set branch tracking configuration"),
1714 parse_opt_tracking_mode
),
1715 OPT__FORCE(&opts
->force
, N_("force checkout (throw away local modifications)"),
1716 PARSE_OPT_NOCOMPLETE
),
1717 OPT_STRING(0, "orphan", &opts
->new_orphan_branch
, N_("new-branch"), N_("new unborn branch")),
1718 OPT_BOOL_F(0, "overwrite-ignore", &opts
->overwrite_ignore
,
1719 N_("update ignored files (default)"),
1720 PARSE_OPT_NOCOMPLETE
),
1721 OPT_BOOL(0, "ignore-other-worktrees", &opts
->ignore_other_worktrees
,
1722 N_("do not check if another worktree is using this branch")),
1725 struct option
*newopts
= parse_options_concat(prevopts
, options
);
1730 static struct option
*add_checkout_path_options(struct checkout_opts
*opts
,
1731 struct option
*prevopts
)
1733 struct option options
[] = {
1734 OPT_SET_INT_F('2', "ours", &opts
->writeout_stage
,
1735 N_("checkout our version for unmerged files"),
1736 2, PARSE_OPT_NONEG
),
1737 OPT_SET_INT_F('3', "theirs", &opts
->writeout_stage
,
1738 N_("checkout their version for unmerged files"),
1739 3, PARSE_OPT_NONEG
),
1740 OPT_BOOL('p', "patch", &opts
->patch_mode
, N_("select hunks interactively")),
1741 OPT_BOOL(0, "ignore-skip-worktree-bits", &opts
->ignore_skipworktree
,
1742 N_("do not limit pathspecs to sparse entries only")),
1743 OPT_PATHSPEC_FROM_FILE(&opts
->pathspec_from_file
),
1744 OPT_PATHSPEC_FILE_NUL(&opts
->pathspec_file_nul
),
1747 struct option
*newopts
= parse_options_concat(prevopts
, options
);
1752 /* create-branch option (either b or c) */
1753 static char cb_option
= 'b';
1755 static int checkout_main(int argc
, const char **argv
, const char *prefix
,
1756 struct checkout_opts
*opts
, struct option
*options
,
1757 const char * const usagestr
[])
1759 int parseopt_flags
= 0;
1760 struct branch_info new_branch_info
= { 0 };
1763 opts
->overwrite_ignore
= 1;
1764 opts
->prefix
= prefix
;
1765 opts
->show_progress
= -1;
1767 git_config(git_checkout_config
, opts
);
1768 if (the_repository
->gitdir
) {
1769 prepare_repo_settings(the_repository
);
1770 the_repository
->settings
.command_requires_full_index
= 0;
1773 opts
->track
= BRANCH_TRACK_UNSPECIFIED
;
1775 if (!opts
->accept_pathspec
&& !opts
->accept_ref
)
1776 BUG("make up your mind, you need to take _something_");
1777 if (opts
->accept_pathspec
&& opts
->accept_ref
)
1778 parseopt_flags
= PARSE_OPT_KEEP_DASHDASH
;
1780 argc
= parse_options(argc
, argv
, prefix
, options
,
1781 usagestr
, parseopt_flags
);
1783 if (opts
->show_progress
< 0) {
1785 opts
->show_progress
= 0;
1787 opts
->show_progress
= isatty(2);
1790 /* --conflicts implies --merge */
1791 if (opts
->merge
== -1)
1792 opts
->merge
= opts
->conflict_style
>= 0;
1795 opts
->discard_changes
= 1;
1796 opts
->ignore_unmerged_opt
= "--force";
1797 opts
->ignore_unmerged
= 1;
1800 if ((!!opts
->new_branch
+ !!opts
->new_branch_force
+ !!opts
->new_orphan_branch
) > 1)
1801 die(_("options '-%c', '-%c', and '%s' cannot be used together"),
1802 cb_option
, toupper(cb_option
), "--orphan");
1804 if (opts
->overlay_mode
== 1 && opts
->patch_mode
)
1805 die(_("options '%s' and '%s' cannot be used together"), "-p", "--overlay");
1807 if (opts
->checkout_index
>= 0 || opts
->checkout_worktree
>= 0) {
1808 if (opts
->checkout_index
< 0)
1809 opts
->checkout_index
= 0;
1810 if (opts
->checkout_worktree
< 0)
1811 opts
->checkout_worktree
= 0;
1813 if (opts
->checkout_index
< 0)
1814 opts
->checkout_index
= -opts
->checkout_index
- 1;
1815 if (opts
->checkout_worktree
< 0)
1816 opts
->checkout_worktree
= -opts
->checkout_worktree
- 1;
1818 if (opts
->checkout_index
< 0 || opts
->checkout_worktree
< 0)
1819 BUG("these flags should be non-negative by now");
1821 * convenient shortcut: "git restore --staged [--worktree]" equals
1822 * "git restore --staged [--worktree] --source HEAD"
1824 if (!opts
->from_treeish
&& opts
->checkout_index
)
1825 opts
->from_treeish
= "HEAD";
1828 * From here on, new_branch will contain the branch to be checked out,
1829 * and new_branch_force and new_orphan_branch will tell us which one of
1830 * -b/-B/-c/-C/--orphan is being used.
1832 if (opts
->new_branch_force
)
1833 opts
->new_branch
= opts
->new_branch_force
;
1835 if (opts
->new_orphan_branch
)
1836 opts
->new_branch
= opts
->new_orphan_branch
;
1838 /* --track without -c/-C/-b/-B/--orphan should DWIM */
1839 if (opts
->track
!= BRANCH_TRACK_UNSPECIFIED
&& !opts
->new_branch
) {
1840 const char *argv0
= argv
[0];
1841 if (!argc
|| !strcmp(argv0
, "--"))
1842 die(_("--track needs a branch name"));
1843 skip_prefix(argv0
, "refs/", &argv0
);
1844 skip_prefix(argv0
, "remotes/", &argv0
);
1845 argv0
= strchr(argv0
, '/');
1846 if (!argv0
|| !argv0
[1])
1847 die(_("missing branch name; try -%c"), cb_option
);
1848 opts
->new_branch
= argv0
+ 1;
1852 * Extract branch name from command line arguments, so
1853 * all that is left is pathspecs.
1857 * 1) git checkout <tree> -- [<paths>]
1858 * 2) git checkout -- [<paths>]
1859 * 3) git checkout <something> [<paths>]
1861 * including "last branch" syntax and DWIM-ery for names of
1862 * remote branches, erroring out for invalid or ambiguous cases.
1864 if (argc
&& opts
->accept_ref
) {
1865 struct object_id rev
;
1867 !opts
->patch_mode
&&
1868 opts
->dwim_new_local_branch
&&
1869 opts
->track
== BRANCH_TRACK_UNSPECIFIED
&&
1871 int n
= parse_branchname_arg(argc
, argv
, dwim_ok
,
1872 &new_branch_info
, opts
, &rev
);
1875 } else if (!opts
->accept_ref
&& opts
->from_treeish
) {
1876 struct object_id rev
;
1878 if (repo_get_oid_mb(the_repository
, opts
->from_treeish
, &rev
))
1879 die(_("could not resolve %s"), opts
->from_treeish
);
1881 setup_new_branch_info_and_source_tree(&new_branch_info
,
1883 opts
->from_treeish
);
1885 if (!opts
->source_tree
)
1886 die(_("reference is not a tree: %s"), opts
->from_treeish
);
1890 parse_pathspec(&opts
->pathspec
, 0,
1891 opts
->patch_mode
? PATHSPEC_PREFIX_ORIGIN
: 0,
1894 if (!opts
->pathspec
.nr
)
1895 die(_("invalid path specification"));
1898 * Try to give more helpful suggestion.
1899 * new_branch && argc > 1 will be caught later.
1901 if (opts
->new_branch
&& argc
== 1 && !new_branch_info
.commit
)
1902 die(_("'%s' is not a commit and a branch '%s' cannot be created from it"),
1903 argv
[0], opts
->new_branch
);
1905 if (opts
->force_detach
)
1906 die(_("git checkout: --detach does not take a path argument '%s'"),
1910 if (opts
->pathspec_from_file
) {
1911 if (opts
->pathspec
.nr
)
1912 die(_("'%s' and pathspec arguments cannot be used together"), "--pathspec-from-file");
1914 if (opts
->force_detach
)
1915 die(_("options '%s' and '%s' cannot be used together"), "--pathspec-from-file", "--detach");
1917 if (opts
->patch_mode
)
1918 die(_("options '%s' and '%s' cannot be used together"), "--pathspec-from-file", "--patch");
1920 parse_pathspec_file(&opts
->pathspec
, 0,
1922 prefix
, opts
->pathspec_from_file
, opts
->pathspec_file_nul
);
1923 } else if (opts
->pathspec_file_nul
) {
1924 die(_("the option '%s' requires '%s'"), "--pathspec-file-nul", "--pathspec-from-file");
1927 opts
->pathspec
.recursive
= 1;
1929 if (opts
->pathspec
.nr
) {
1930 if (1 < !!opts
->writeout_stage
+ !!opts
->force
+ !!opts
->merge
)
1931 die(_("git checkout: --ours/--theirs, --force and --merge are incompatible when\n"
1932 "checking out of the index."));
1934 if (opts
->accept_pathspec
&& !opts
->empty_pathspec_ok
&&
1935 !opts
->patch_mode
) /* patch mode is special */
1936 die(_("you must specify path(s) to restore"));
1939 if (opts
->new_branch
) {
1940 struct strbuf buf
= STRBUF_INIT
;
1942 if (opts
->new_branch_force
)
1943 opts
->branch_exists
= validate_branchname(opts
->new_branch
, &buf
);
1945 opts
->branch_exists
=
1946 validate_new_branchname(opts
->new_branch
, &buf
, 0);
1947 strbuf_release(&buf
);
1950 if (opts
->patch_mode
|| opts
->pathspec
.nr
)
1951 ret
= checkout_paths(opts
, &new_branch_info
);
1953 ret
= checkout_branch(opts
, &new_branch_info
);
1955 branch_info_release(&new_branch_info
);
1956 clear_pathspec(&opts
->pathspec
);
1957 free(opts
->pathspec_from_file
);
1963 int cmd_checkout(int argc
,
1966 struct repository
*repo UNUSED
)
1968 struct checkout_opts opts
= CHECKOUT_OPTS_INIT
;
1969 struct option
*options
;
1970 struct option checkout_options
[] = {
1971 OPT_STRING('b', NULL
, &opts
.new_branch
, N_("branch"),
1972 N_("create and checkout a new branch")),
1973 OPT_STRING('B', NULL
, &opts
.new_branch_force
, N_("branch"),
1974 N_("create/reset and checkout a branch")),
1975 OPT_BOOL('l', NULL
, &opts
.new_branch_log
, N_("create reflog for new branch")),
1976 OPT_BOOL(0, "guess", &opts
.dwim_new_local_branch
,
1977 N_("second guess 'git checkout <no-such-branch>' (default)")),
1978 OPT_BOOL(0, "overlay", &opts
.overlay_mode
, N_("use overlay mode (default)")),
1982 opts
.dwim_new_local_branch
= 1;
1983 opts
.switch_branch_doing_nothing_is_ok
= 1;
1984 opts
.only_merge_on_switching_branches
= 0;
1985 opts
.accept_ref
= 1;
1986 opts
.accept_pathspec
= 1;
1987 opts
.implicit_detach
= 1;
1988 opts
.can_switch_when_in_progress
= 1;
1989 opts
.orphan_from_empty_tree
= 0;
1990 opts
.empty_pathspec_ok
= 1;
1991 opts
.overlay_mode
= -1;
1992 opts
.checkout_index
= -2; /* default on */
1993 opts
.checkout_worktree
= -2; /* default on */
1995 if (argc
== 3 && !strcmp(argv
[1], "-b")) {
1997 * User ran 'git checkout -b <branch>' and expects
1998 * the same behavior as 'git switch -c <branch>'.
2000 opts
.switch_branch_doing_nothing_is_ok
= 0;
2001 opts
.only_merge_on_switching_branches
= 1;
2004 options
= parse_options_dup(checkout_options
);
2005 options
= add_common_options(&opts
, options
);
2006 options
= add_common_switch_branch_options(&opts
, options
);
2007 options
= add_checkout_path_options(&opts
, options
);
2009 return checkout_main(argc
, argv
, prefix
, &opts
, options
,
2013 int cmd_switch(int argc
,
2016 struct repository
*repo UNUSED
)
2018 struct checkout_opts opts
= CHECKOUT_OPTS_INIT
;
2019 struct option
*options
= NULL
;
2020 struct option switch_options
[] = {
2021 OPT_STRING('c', "create", &opts
.new_branch
, N_("branch"),
2022 N_("create and switch to a new branch")),
2023 OPT_STRING('C', "force-create", &opts
.new_branch_force
, N_("branch"),
2024 N_("create/reset and switch to a branch")),
2025 OPT_BOOL(0, "guess", &opts
.dwim_new_local_branch
,
2026 N_("second guess 'git switch <no-such-branch>'")),
2027 OPT_BOOL(0, "discard-changes", &opts
.discard_changes
,
2028 N_("throw away local modifications")),
2032 opts
.dwim_new_local_branch
= 1;
2033 opts
.accept_ref
= 1;
2034 opts
.accept_pathspec
= 0;
2035 opts
.switch_branch_doing_nothing_is_ok
= 0;
2036 opts
.only_merge_on_switching_branches
= 1;
2037 opts
.implicit_detach
= 0;
2038 opts
.can_switch_when_in_progress
= 0;
2039 opts
.orphan_from_empty_tree
= 1;
2040 opts
.overlay_mode
= -1;
2042 options
= parse_options_dup(switch_options
);
2043 options
= add_common_options(&opts
, options
);
2044 options
= add_common_switch_branch_options(&opts
, options
);
2048 return checkout_main(argc
, argv
, prefix
, &opts
, options
,
2049 switch_branch_usage
);
2052 int cmd_restore(int argc
,
2055 struct repository
*repo UNUSED
)
2057 struct checkout_opts opts
= CHECKOUT_OPTS_INIT
;
2058 struct option
*options
;
2059 struct option restore_options
[] = {
2060 OPT_STRING('s', "source", &opts
.from_treeish
, "<tree-ish>",
2061 N_("which tree-ish to checkout from")),
2062 OPT_BOOL('S', "staged", &opts
.checkout_index
,
2063 N_("restore the index")),
2064 OPT_BOOL('W', "worktree", &opts
.checkout_worktree
,
2065 N_("restore the working tree (default)")),
2066 OPT_BOOL(0, "ignore-unmerged", &opts
.ignore_unmerged
,
2067 N_("ignore unmerged entries")),
2068 OPT_BOOL(0, "overlay", &opts
.overlay_mode
, N_("use overlay mode")),
2072 opts
.accept_ref
= 0;
2073 opts
.accept_pathspec
= 1;
2074 opts
.empty_pathspec_ok
= 0;
2075 opts
.overlay_mode
= 0;
2076 opts
.checkout_index
= -1; /* default off */
2077 opts
.checkout_worktree
= -2; /* default on */
2078 opts
.ignore_unmerged_opt
= "--ignore-unmerged";
2080 options
= parse_options_dup(restore_options
);
2081 options
= add_common_options(&opts
, options
);
2082 options
= add_checkout_path_options(&opts
, options
);
2084 return checkout_main(argc
, argv
, prefix
, &opts
, options
,