1 #define USE_THE_INDEX_COMPATIBILITY_MACROS
6 #include "cache-tree.h"
14 #include "merge-recursive.h"
15 #include "object-store.h"
16 #include "parse-options.h"
19 #include "resolve-undo.h"
21 #include "run-command.h"
22 #include "submodule.h"
23 #include "submodule-config.h"
25 #include "tree-walk.h"
26 #include "unpack-trees.h"
27 #include "wt-status.h"
28 #include "xdiff-interface.h"
31 static const char * const checkout_usage
[] = {
32 N_("git checkout [<options>] <branch>"),
33 N_("git checkout [<options>] [<branch>] -- <file>..."),
37 static const char * const switch_branch_usage
[] = {
38 N_("git switch [<options>] [<branch>]"),
42 static const char * const restore_usage
[] = {
43 N_("git restore [<options>] [--source=<branch>] <file>..."),
47 struct checkout_opts
{
56 int ignore_skipworktree
;
57 int ignore_other_worktrees
;
59 int count_checkout_paths
;
61 int dwim_new_local_branch
;
65 int switch_branch_doing_nothing_is_ok
;
66 int only_merge_on_switching_branches
;
67 int can_switch_when_in_progress
;
68 int orphan_from_empty_tree
;
69 int empty_pathspec_ok
;
71 int checkout_worktree
;
72 const char *ignore_unmerged_opt
;
74 int pathspec_file_nul
;
75 const char *pathspec_from_file
;
77 const char *new_branch
;
78 const char *new_branch_force
;
79 const char *new_orphan_branch
;
81 enum branch_track track
;
82 struct diff_options diff_options
;
87 struct pathspec pathspec
;
88 const char *from_treeish
;
89 struct tree
*source_tree
;
93 const char *name
; /* The short name used */
94 const char *path
; /* The full name of a real branch */
95 struct commit
*commit
; /* The named commit */
96 char *refname
; /* The full name of the ref being checked out. */
97 struct object_id oid
; /* The object ID of the commit being checked out. */
99 * if not null the branch is detached because it's already
100 * checked out in this checkout
105 static int post_checkout_hook(struct commit
*old_commit
, struct commit
*new_commit
,
108 return run_hook_le(NULL
, "post-checkout",
109 oid_to_hex(old_commit
? &old_commit
->object
.oid
: &null_oid
),
110 oid_to_hex(new_commit
? &new_commit
->object
.oid
: &null_oid
),
111 changed
? "1" : "0", NULL
);
112 /* "new_commit" can be NULL when checking out from the index before
117 static int update_some(const struct object_id
*oid
, struct strbuf
*base
,
118 const char *pathname
, unsigned mode
, void *context
)
121 struct cache_entry
*ce
;
125 return READ_TREE_RECURSIVE
;
127 len
= base
->len
+ strlen(pathname
);
128 ce
= make_empty_cache_entry(&the_index
, len
);
129 oidcpy(&ce
->oid
, oid
);
130 memcpy(ce
->name
, base
->buf
, base
->len
);
131 memcpy(ce
->name
+ base
->len
, pathname
, len
- base
->len
);
132 ce
->ce_flags
= create_ce_flags(0) | CE_UPDATE
;
133 ce
->ce_namelen
= len
;
134 ce
->ce_mode
= create_ce_mode(mode
);
137 * If the entry is the same as the current index, we can leave the old
138 * entry in place. Whether it is UPTODATE or not, checkout_entry will
139 * do the right thing.
141 pos
= cache_name_pos(ce
->name
, ce
->ce_namelen
);
143 struct cache_entry
*old
= active_cache
[pos
];
144 if (ce
->ce_mode
== old
->ce_mode
&&
145 !ce_intent_to_add(old
) &&
146 oideq(&ce
->oid
, &old
->oid
)) {
147 old
->ce_flags
|= CE_UPDATE
;
148 discard_cache_entry(ce
);
153 add_cache_entry(ce
, ADD_CACHE_OK_TO_ADD
| ADD_CACHE_OK_TO_REPLACE
);
157 static int read_tree_some(struct tree
*tree
, const struct pathspec
*pathspec
)
159 read_tree(the_repository
, tree
,
160 pathspec
, update_some
, NULL
);
162 /* update the index with the given tree's info
163 * for all args, expanding wildcards, and exit
164 * with any non-zero return code.
169 static int skip_same_name(const struct cache_entry
*ce
, int pos
)
171 while (++pos
< active_nr
&&
172 !strcmp(active_cache
[pos
]->name
, ce
->name
))
177 static int check_stage(int stage
, const struct cache_entry
*ce
, int pos
,
180 while (pos
< active_nr
&&
181 !strcmp(active_cache
[pos
]->name
, ce
->name
)) {
182 if (ce_stage(active_cache
[pos
]) == stage
)
189 return error(_("path '%s' does not have our version"), ce
->name
);
191 return error(_("path '%s' does not have their version"), ce
->name
);
194 static int check_stages(unsigned stages
, const struct cache_entry
*ce
, int pos
)
197 const char *name
= ce
->name
;
199 while (pos
< active_nr
) {
200 ce
= active_cache
[pos
];
201 if (strcmp(name
, ce
->name
))
203 seen
|= (1 << ce_stage(ce
));
206 if ((stages
& seen
) != stages
)
207 return error(_("path '%s' does not have all necessary versions"),
212 static int checkout_stage(int stage
, const struct cache_entry
*ce
, int pos
,
213 const struct checkout
*state
, int *nr_checkouts
,
216 while (pos
< active_nr
&&
217 !strcmp(active_cache
[pos
]->name
, ce
->name
)) {
218 if (ce_stage(active_cache
[pos
]) == stage
)
219 return checkout_entry(active_cache
[pos
], state
,
228 return error(_("path '%s' does not have our version"), ce
->name
);
230 return error(_("path '%s' does not have their version"), ce
->name
);
233 static int checkout_merged(int pos
, const struct checkout
*state
, int *nr_checkouts
)
235 struct cache_entry
*ce
= active_cache
[pos
];
236 const char *path
= ce
->name
;
237 mmfile_t ancestor
, ours
, theirs
;
239 struct object_id oid
;
240 mmbuffer_t result_buf
;
241 struct object_id threeway
[3];
243 struct ll_merge_options ll_opts
;
246 memset(threeway
, 0, sizeof(threeway
));
247 while (pos
< active_nr
) {
249 stage
= ce_stage(ce
);
250 if (!stage
|| strcmp(path
, ce
->name
))
252 oidcpy(&threeway
[stage
- 1], &ce
->oid
);
254 mode
= create_ce_mode(ce
->ce_mode
);
256 ce
= active_cache
[pos
];
258 if (is_null_oid(&threeway
[1]) || is_null_oid(&threeway
[2]))
259 return error(_("path '%s' does not have necessary versions"), path
);
261 read_mmblob(&ancestor
, &threeway
[0]);
262 read_mmblob(&ours
, &threeway
[1]);
263 read_mmblob(&theirs
, &threeway
[2]);
265 memset(&ll_opts
, 0, sizeof(ll_opts
));
266 git_config_get_bool("merge.renormalize", &renormalize
);
267 ll_opts
.renormalize
= renormalize
;
268 status
= ll_merge(&result_buf
, path
, &ancestor
, "base",
269 &ours
, "ours", &theirs
, "theirs",
270 state
->istate
, &ll_opts
);
274 if (status
< 0 || !result_buf
.ptr
) {
275 free(result_buf
.ptr
);
276 return error(_("path '%s': cannot merge"), path
);
281 * There is absolutely no reason to write this as a blob object
282 * and create a phony cache entry. This hack is primarily to get
283 * to the write_entry() machinery that massages the contents to
284 * work-tree format and writes out which only allows it for a
285 * cache entry. The code in write_entry() needs to be refactored
286 * to allow us to feed a <buffer, size, mode> instead of a cache
287 * entry. Such a refactoring would help merge_recursive as well
288 * (it also writes the merge result to the object database even
289 * when it may contain conflicts).
291 if (write_object_file(result_buf
.ptr
, result_buf
.size
, blob_type
, &oid
))
292 die(_("Unable to add merge result for '%s'"), path
);
293 free(result_buf
.ptr
);
294 ce
= make_transient_cache_entry(mode
, &oid
, path
, 2);
296 die(_("make_cache_entry failed for path '%s'"), path
);
297 status
= checkout_entry(ce
, state
, NULL
, nr_checkouts
);
298 discard_cache_entry(ce
);
302 static void mark_ce_for_checkout_overlay(struct cache_entry
*ce
,
304 const struct checkout_opts
*opts
)
306 ce
->ce_flags
&= ~CE_MATCHED
;
307 if (!opts
->ignore_skipworktree
&& ce_skip_worktree(ce
))
309 if (opts
->source_tree
&& !(ce
->ce_flags
& CE_UPDATE
))
311 * "git checkout tree-ish -- path", but this entry
312 * is in the original index but is not in tree-ish
313 * or does not match the pathspec; it will not be
314 * checked out to the working tree. We will not do
315 * anything to this entry at all.
319 * Either this entry came from the tree-ish we are
320 * checking the paths out of, or we are checking out
323 * If it comes from the tree-ish, we already know it
324 * matches the pathspec and could just stamp
325 * CE_MATCHED to it from update_some(). But we still
326 * need ps_matched and read_tree (and
327 * eventually tree_entry_interesting) cannot fill
328 * ps_matched yet. Once it can, we can avoid calling
329 * match_pathspec() for _all_ entries when
330 * opts->source_tree != NULL.
332 if (ce_path_match(&the_index
, ce
, &opts
->pathspec
, ps_matched
))
333 ce
->ce_flags
|= CE_MATCHED
;
336 static void mark_ce_for_checkout_no_overlay(struct cache_entry
*ce
,
338 const struct checkout_opts
*opts
)
340 ce
->ce_flags
&= ~CE_MATCHED
;
341 if (!opts
->ignore_skipworktree
&& ce_skip_worktree(ce
))
343 if (ce_path_match(&the_index
, ce
, &opts
->pathspec
, ps_matched
)) {
344 ce
->ce_flags
|= CE_MATCHED
;
345 if (opts
->source_tree
&& !(ce
->ce_flags
& CE_UPDATE
))
347 * In overlay mode, but the path is not in
348 * tree-ish, which means we should remove it
349 * from the index and the working tree.
351 ce
->ce_flags
|= CE_REMOVE
| CE_WT_REMOVE
;
355 static int checkout_worktree(const struct checkout_opts
*opts
,
356 const struct branch_info
*info
)
358 struct checkout state
= CHECKOUT_INIT
;
359 int nr_checkouts
= 0, nr_unmerged
= 0;
364 state
.refresh_cache
= 1;
365 state
.istate
= &the_index
;
367 init_checkout_metadata(&state
.meta
, info
->refname
,
368 info
->commit
? &info
->commit
->object
.oid
: &info
->oid
,
371 enable_delayed_checkout(&state
);
373 /* TODO: audit for interaction with sparse-index. */
374 ensure_full_index(&the_index
);
375 for (pos
= 0; pos
< active_nr
; pos
++) {
376 struct cache_entry
*ce
= active_cache
[pos
];
377 if (ce
->ce_flags
& CE_MATCHED
) {
379 errs
|= checkout_entry(ce
, &state
,
380 NULL
, &nr_checkouts
);
383 if (opts
->writeout_stage
)
384 errs
|= checkout_stage(opts
->writeout_stage
,
387 &nr_checkouts
, opts
->overlay_mode
);
388 else if (opts
->merge
)
389 errs
|= checkout_merged(pos
, &state
,
391 pos
= skip_same_name(ce
, pos
) - 1;
394 remove_marked_cache_entries(&the_index
, 1);
395 remove_scheduled_dirs();
396 errs
|= finish_delayed_checkout(&state
, &nr_checkouts
);
398 if (opts
->count_checkout_paths
) {
400 fprintf_ln(stderr
, Q_("Recreated %d merge conflict",
401 "Recreated %d merge conflicts",
404 if (opts
->source_tree
)
405 fprintf_ln(stderr
, Q_("Updated %d path from %s",
406 "Updated %d paths from %s",
409 find_unique_abbrev(&opts
->source_tree
->object
.oid
,
411 else if (!nr_unmerged
|| nr_checkouts
)
412 fprintf_ln(stderr
, Q_("Updated %d path from the index",
413 "Updated %d paths from the index",
421 static int checkout_paths(const struct checkout_opts
*opts
,
422 const struct branch_info
*new_branch_info
)
425 static char *ps_matched
;
426 struct object_id rev
;
429 struct lock_file lock_file
= LOCK_INIT
;
432 trace2_cmd_mode(opts
->patch_mode
? "patch" : "path");
434 if (opts
->track
!= BRANCH_TRACK_UNSPECIFIED
)
435 die(_("'%s' cannot be used with updating paths"), "--track");
437 if (opts
->new_branch_log
)
438 die(_("'%s' cannot be used with updating paths"), "-l");
440 if (opts
->ignore_unmerged
&& opts
->patch_mode
)
441 die(_("'%s' cannot be used with updating paths"),
442 opts
->ignore_unmerged_opt
);
444 if (opts
->force_detach
)
445 die(_("'%s' cannot be used with updating paths"), "--detach");
447 if (opts
->merge
&& opts
->patch_mode
)
448 die(_("'%s' cannot be used with %s"), "--merge", "--patch");
450 if (opts
->ignore_unmerged
&& opts
->merge
)
451 die(_("'%s' cannot be used with %s"),
452 opts
->ignore_unmerged_opt
, "-m");
454 if (opts
->new_branch
)
455 die(_("Cannot update paths and switch to branch '%s' at the same time."),
458 if (!opts
->checkout_worktree
&& !opts
->checkout_index
)
459 die(_("neither '%s' or '%s' is specified"),
460 "--staged", "--worktree");
462 if (!opts
->checkout_worktree
&& !opts
->from_treeish
)
463 die(_("'%s' must be used when '%s' is not specified"),
464 "--worktree", "--source");
466 if (opts
->checkout_index
&& !opts
->checkout_worktree
&&
467 opts
->writeout_stage
)
468 die(_("'%s' or '%s' cannot be used with %s"),
469 "--ours", "--theirs", "--staged");
471 if (opts
->checkout_index
&& !opts
->checkout_worktree
&&
473 die(_("'%s' or '%s' cannot be used with %s"),
474 "--merge", "--conflict", "--staged");
476 if (opts
->patch_mode
) {
477 const char *patch_mode
;
478 const char *rev
= new_branch_info
->name
;
479 char rev_oid
[GIT_MAX_HEXSZ
+ 1];
482 * Since rev can be in the form of `<a>...<b>` (which is not
483 * recognized by diff-index), we will always replace the name
484 * with the hex of the commit (whether it's in `...` form or
485 * not) for the run_add_interactive() machinery to work
486 * properly. However, there is special logic for the HEAD case
487 * so we mustn't replace that. Also, when we were given a
488 * tree-object, new_branch_info->commit would be NULL, but we
489 * do not have to do any replacement, either.
491 if (rev
&& new_branch_info
->commit
&& strcmp(rev
, "HEAD"))
492 rev
= oid_to_hex_r(rev_oid
, &new_branch_info
->commit
->object
.oid
);
494 if (opts
->checkout_index
&& opts
->checkout_worktree
)
495 patch_mode
= "--patch=checkout";
496 else if (opts
->checkout_index
&& !opts
->checkout_worktree
)
497 patch_mode
= "--patch=reset";
498 else if (!opts
->checkout_index
&& opts
->checkout_worktree
)
499 patch_mode
= "--patch=worktree";
501 BUG("either flag must have been set, worktree=%d, index=%d",
502 opts
->checkout_worktree
, opts
->checkout_index
);
503 return run_add_interactive(rev
, patch_mode
, &opts
->pathspec
);
506 repo_hold_locked_index(the_repository
, &lock_file
, LOCK_DIE_ON_ERROR
);
507 if (read_cache_preload(&opts
->pathspec
) < 0)
508 return error(_("index file corrupt"));
510 if (opts
->source_tree
)
511 read_tree_some(opts
->source_tree
, &opts
->pathspec
);
513 ps_matched
= xcalloc(opts
->pathspec
.nr
, 1);
516 * Make sure all pathspecs participated in locating the paths
519 /* TODO: audit for interaction with sparse-index. */
520 ensure_full_index(&the_index
);
521 for (pos
= 0; pos
< active_nr
; pos
++)
522 if (opts
->overlay_mode
)
523 mark_ce_for_checkout_overlay(active_cache
[pos
],
527 mark_ce_for_checkout_no_overlay(active_cache
[pos
],
531 if (report_path_error(ps_matched
, &opts
->pathspec
)) {
537 /* "checkout -m path" to recreate conflicted state */
539 unmerge_marked_index(&the_index
);
541 /* Any unmerged paths? */
542 for (pos
= 0; pos
< active_nr
; pos
++) {
543 const struct cache_entry
*ce
= active_cache
[pos
];
544 if (ce
->ce_flags
& CE_MATCHED
) {
547 if (opts
->ignore_unmerged
) {
549 warning(_("path '%s' is unmerged"), ce
->name
);
550 } else if (opts
->writeout_stage
) {
551 errs
|= check_stage(opts
->writeout_stage
, ce
, pos
, opts
->overlay_mode
);
552 } else if (opts
->merge
) {
553 errs
|= check_stages((1<<2) | (1<<3), ce
, pos
);
556 error(_("path '%s' is unmerged"), ce
->name
);
558 pos
= skip_same_name(ce
, pos
) - 1;
564 /* Now we are committed to check them out */
565 if (opts
->checkout_worktree
)
566 errs
|= checkout_worktree(opts
, new_branch_info
);
568 remove_marked_cache_entries(&the_index
, 1);
571 * Allow updating the index when checking out from the index.
572 * This is to save new stat info.
574 if (opts
->checkout_worktree
&& !opts
->checkout_index
&& !opts
->source_tree
)
577 checkout_index
= opts
->checkout_index
;
579 if (checkout_index
) {
580 if (write_locked_index(&the_index
, &lock_file
, COMMIT_LOCK
))
581 die(_("unable to write new index file"));
584 * NEEDSWORK: if --worktree is not specified, we
585 * should save stat info of checked out files in the
586 * index to avoid the next (potentially costly)
587 * refresh. But it's a bit tricker to do...
589 rollback_lock_file(&lock_file
);
592 read_ref_full("HEAD", 0, &rev
, NULL
);
593 head
= lookup_commit_reference_gently(the_repository
, &rev
, 1);
595 errs
|= post_checkout_hook(head
, head
, 0);
599 static void show_local_changes(struct object
*head
,
600 const struct diff_options
*opts
)
603 /* I think we want full paths, even if we're in a subdirectory. */
604 repo_init_revisions(the_repository
, &rev
, NULL
);
605 rev
.diffopt
.flags
= opts
->flags
;
606 rev
.diffopt
.output_format
|= DIFF_FORMAT_NAME_STATUS
;
607 diff_setup_done(&rev
.diffopt
);
608 add_pending_object(&rev
, head
, NULL
);
609 run_diff_index(&rev
, 0);
612 static void describe_detached_head(const char *msg
, struct commit
*commit
)
614 struct strbuf sb
= STRBUF_INIT
;
616 if (!parse_commit(commit
))
617 pp_commit_easy(CMIT_FMT_ONELINE
, commit
, &sb
);
618 if (print_sha1_ellipsis()) {
619 fprintf(stderr
, "%s %s... %s\n", msg
,
620 find_unique_abbrev(&commit
->object
.oid
, DEFAULT_ABBREV
), sb
.buf
);
622 fprintf(stderr
, "%s %s %s\n", msg
,
623 find_unique_abbrev(&commit
->object
.oid
, DEFAULT_ABBREV
), sb
.buf
);
628 static int reset_tree(struct tree
*tree
, const struct checkout_opts
*o
,
629 int worktree
, int *writeout_error
,
630 struct branch_info
*info
)
632 struct unpack_trees_options opts
;
633 struct tree_desc tree_desc
;
635 memset(&opts
, 0, sizeof(opts
));
637 opts
.update
= worktree
;
638 opts
.skip_unmerged
= !worktree
;
641 opts
.fn
= oneway_merge
;
642 opts
.verbose_update
= o
->show_progress
;
643 opts
.src_index
= &the_index
;
644 opts
.dst_index
= &the_index
;
645 init_checkout_metadata(&opts
.meta
, info
->refname
,
646 info
->commit
? &info
->commit
->object
.oid
: &null_oid
,
649 init_tree_desc(&tree_desc
, tree
->buffer
, tree
->size
);
650 switch (unpack_trees(1, &tree_desc
, &opts
)) {
654 * We return 0 nevertheless, as the index is all right
655 * and more importantly we have made best efforts to
656 * update paths in the work tree, and we cannot revert
667 static void setup_branch_path(struct branch_info
*branch
)
669 struct strbuf buf
= STRBUF_INIT
;
672 * If this is a ref, resolve it; otherwise, look up the OID for our
673 * expression. Failure here is okay.
675 if (!dwim_ref(branch
->name
, strlen(branch
->name
), &branch
->oid
, &branch
->refname
, 0))
676 repo_get_oid_committish(the_repository
, branch
->name
, &branch
->oid
);
678 strbuf_branchname(&buf
, branch
->name
, INTERPRET_BRANCH_LOCAL
);
679 if (strcmp(buf
.buf
, branch
->name
))
680 branch
->name
= xstrdup(buf
.buf
);
681 strbuf_splice(&buf
, 0, 0, "refs/heads/", 11);
682 branch
->path
= strbuf_detach(&buf
, NULL
);
685 static int merge_working_tree(const struct checkout_opts
*opts
,
686 struct branch_info
*old_branch_info
,
687 struct branch_info
*new_branch_info
,
691 struct lock_file lock_file
= LOCK_INIT
;
692 struct tree
*new_tree
;
694 hold_locked_index(&lock_file
, LOCK_DIE_ON_ERROR
);
695 if (read_cache_preload(NULL
) < 0)
696 return error(_("index file corrupt"));
698 resolve_undo_clear();
699 if (opts
->new_orphan_branch
&& opts
->orphan_from_empty_tree
) {
700 if (new_branch_info
->commit
)
701 BUG("'switch --orphan' should never accept a commit as starting point");
702 new_tree
= parse_tree_indirect(the_hash_algo
->empty_tree
);
704 new_tree
= get_commit_tree(new_branch_info
->commit
);
705 if (opts
->discard_changes
) {
706 ret
= reset_tree(new_tree
, opts
, 1, writeout_error
, new_branch_info
);
710 struct tree_desc trees
[2];
712 struct unpack_trees_options topts
;
714 memset(&topts
, 0, sizeof(topts
));
716 topts
.src_index
= &the_index
;
717 topts
.dst_index
= &the_index
;
719 setup_unpack_trees_porcelain(&topts
, "checkout");
721 refresh_cache(REFRESH_QUIET
);
723 if (unmerged_cache()) {
724 error(_("you need to resolve your current index first"));
728 /* 2-way merge to the new branch */
729 topts
.initial_checkout
= is_cache_unborn();
732 topts
.quiet
= opts
->merge
&& old_branch_info
->commit
;
733 topts
.verbose_update
= opts
->show_progress
;
734 topts
.fn
= twoway_merge
;
735 init_checkout_metadata(&topts
.meta
, new_branch_info
->refname
,
736 new_branch_info
->commit
?
737 &new_branch_info
->commit
->object
.oid
:
738 &new_branch_info
->oid
, NULL
);
739 if (opts
->overwrite_ignore
) {
740 topts
.dir
= xcalloc(1, sizeof(*topts
.dir
));
741 topts
.dir
->flags
|= DIR_SHOW_IGNORED
;
742 setup_standard_excludes(topts
.dir
);
744 tree
= parse_tree_indirect(old_branch_info
->commit
?
745 &old_branch_info
->commit
->object
.oid
:
746 the_hash_algo
->empty_tree
);
747 init_tree_desc(&trees
[0], tree
->buffer
, tree
->size
);
748 parse_tree(new_tree
);
750 init_tree_desc(&trees
[1], tree
->buffer
, tree
->size
);
752 ret
= unpack_trees(2, trees
, &topts
);
753 clear_unpack_trees_porcelain(&topts
);
756 * Unpack couldn't do a trivial merge; either
757 * give up or do a real merge, depending on
758 * whether the merge flag was used.
761 struct tree
*old_tree
;
762 struct merge_options o
;
763 struct strbuf sb
= STRBUF_INIT
;
764 struct strbuf old_commit_shortname
= STRBUF_INIT
;
770 * Without old_branch_info->commit, the below is the same as
771 * the two-tree unpack we already tried and failed.
773 if (!old_branch_info
->commit
)
775 old_tree
= get_commit_tree(old_branch_info
->commit
);
777 if (repo_index_has_changes(the_repository
, old_tree
, &sb
))
778 die(_("cannot continue with staged changes in "
779 "the following files:\n%s"), sb
.buf
);
782 /* Do more real merge */
785 * We update the index fully, then write the
786 * tree from the index, then merge the new
787 * branch with the current tree, with the old
788 * branch as the base. Then we reset the index
789 * (but not the working tree) to the new
790 * branch, leaving the working tree as the
791 * merged version, but skipping unmerged
792 * entries in the index.
795 add_files_to_cache(NULL
, NULL
, 0);
796 init_merge_options(&o
, the_repository
);
798 work
= write_in_core_index_as_tree(the_repository
);
800 ret
= reset_tree(new_tree
,
802 writeout_error
, new_branch_info
);
805 o
.ancestor
= old_branch_info
->name
;
806 if (old_branch_info
->name
== NULL
) {
807 strbuf_add_unique_abbrev(&old_commit_shortname
,
808 &old_branch_info
->commit
->object
.oid
,
810 o
.ancestor
= old_commit_shortname
.buf
;
812 o
.branch1
= new_branch_info
->name
;
814 ret
= merge_trees(&o
,
820 ret
= reset_tree(new_tree
,
822 writeout_error
, new_branch_info
);
823 strbuf_release(&o
.obuf
);
824 strbuf_release(&old_commit_shortname
);
830 if (!cache_tree_fully_valid(active_cache_tree
))
831 cache_tree_update(&the_index
, WRITE_TREE_SILENT
| WRITE_TREE_REPAIR
);
833 if (write_locked_index(&the_index
, &lock_file
, COMMIT_LOCK
))
834 die(_("unable to write new index file"));
836 if (!opts
->discard_changes
&& !opts
->quiet
&& new_branch_info
->commit
)
837 show_local_changes(&new_branch_info
->commit
->object
, &opts
->diff_options
);
842 static void report_tracking(struct branch_info
*new_branch_info
)
844 struct strbuf sb
= STRBUF_INIT
;
845 struct branch
*branch
= branch_get(new_branch_info
->name
);
847 if (!format_tracking_info(branch
, &sb
, AHEAD_BEHIND_FULL
))
849 fputs(sb
.buf
, stdout
);
853 static void update_refs_for_switch(const struct checkout_opts
*opts
,
854 struct branch_info
*old_branch_info
,
855 struct branch_info
*new_branch_info
)
857 struct strbuf msg
= STRBUF_INIT
;
858 const char *old_desc
, *reflog_msg
;
859 if (opts
->new_branch
) {
860 if (opts
->new_orphan_branch
) {
863 refname
= mkpathdup("refs/heads/%s", opts
->new_orphan_branch
);
864 if (opts
->new_branch_log
&&
865 !should_autocreate_reflog(refname
)) {
867 struct strbuf err
= STRBUF_INIT
;
869 ret
= safe_create_reflog(refname
, 1, &err
);
871 fprintf(stderr
, _("Can not do reflog for '%s': %s\n"),
872 opts
->new_orphan_branch
, err
.buf
);
873 strbuf_release(&err
);
877 strbuf_release(&err
);
882 create_branch(the_repository
,
883 opts
->new_branch
, new_branch_info
->name
,
884 opts
->new_branch_force
? 1 : 0,
885 opts
->new_branch_force
? 1 : 0,
886 opts
->new_branch_log
,
889 new_branch_info
->name
= opts
->new_branch
;
890 setup_branch_path(new_branch_info
);
893 old_desc
= old_branch_info
->name
;
894 if (!old_desc
&& old_branch_info
->commit
)
895 old_desc
= oid_to_hex(&old_branch_info
->commit
->object
.oid
);
897 reflog_msg
= getenv("GIT_REFLOG_ACTION");
899 strbuf_addf(&msg
, "checkout: moving from %s to %s",
900 old_desc
? old_desc
: "(invalid)", new_branch_info
->name
);
902 strbuf_insertstr(&msg
, 0, reflog_msg
);
904 if (!strcmp(new_branch_info
->name
, "HEAD") && !new_branch_info
->path
&& !opts
->force_detach
) {
906 } else if (opts
->force_detach
|| !new_branch_info
->path
) { /* No longer on any branch. */
907 update_ref(msg
.buf
, "HEAD", &new_branch_info
->commit
->object
.oid
, NULL
,
908 REF_NO_DEREF
, UPDATE_REFS_DIE_ON_ERR
);
910 if (old_branch_info
->path
&&
911 advice_detached_head
&& !opts
->force_detach
)
912 detach_advice(new_branch_info
->name
);
913 describe_detached_head(_("HEAD is now at"), new_branch_info
->commit
);
915 } else if (new_branch_info
->path
) { /* Switch branches. */
916 if (create_symref("HEAD", new_branch_info
->path
, msg
.buf
) < 0)
917 die(_("unable to update HEAD"));
919 if (old_branch_info
->path
&& !strcmp(new_branch_info
->path
, old_branch_info
->path
)) {
920 if (opts
->new_branch_force
)
921 fprintf(stderr
, _("Reset branch '%s'\n"),
922 new_branch_info
->name
);
924 fprintf(stderr
, _("Already on '%s'\n"),
925 new_branch_info
->name
);
926 } else if (opts
->new_branch
) {
927 if (opts
->branch_exists
)
928 fprintf(stderr
, _("Switched to and reset branch '%s'\n"), new_branch_info
->name
);
930 fprintf(stderr
, _("Switched to a new branch '%s'\n"), new_branch_info
->name
);
932 fprintf(stderr
, _("Switched to branch '%s'\n"),
933 new_branch_info
->name
);
936 if (old_branch_info
->path
&& old_branch_info
->name
) {
937 if (!ref_exists(old_branch_info
->path
) && reflog_exists(old_branch_info
->path
))
938 delete_reflog(old_branch_info
->path
);
941 remove_branch_state(the_repository
, !opts
->quiet
);
942 strbuf_release(&msg
);
944 (new_branch_info
->path
|| (!opts
->force_detach
&& !strcmp(new_branch_info
->name
, "HEAD"))))
945 report_tracking(new_branch_info
);
948 static int add_pending_uninteresting_ref(const char *refname
,
949 const struct object_id
*oid
,
950 int flags
, void *cb_data
)
952 add_pending_oid(cb_data
, refname
, oid
, UNINTERESTING
);
956 static void describe_one_orphan(struct strbuf
*sb
, struct commit
*commit
)
958 strbuf_addstr(sb
, " ");
959 strbuf_add_unique_abbrev(sb
, &commit
->object
.oid
, DEFAULT_ABBREV
);
960 strbuf_addch(sb
, ' ');
961 if (!parse_commit(commit
))
962 pp_commit_easy(CMIT_FMT_ONELINE
, commit
, sb
);
963 strbuf_addch(sb
, '\n');
966 #define ORPHAN_CUTOFF 4
967 static void suggest_reattach(struct commit
*commit
, struct rev_info
*revs
)
969 struct commit
*c
, *last
= NULL
;
970 struct strbuf sb
= STRBUF_INIT
;
972 while ((c
= get_revision(revs
)) != NULL
) {
973 if (lost
< ORPHAN_CUTOFF
)
974 describe_one_orphan(&sb
, c
);
978 if (ORPHAN_CUTOFF
< lost
) {
979 int more
= lost
- ORPHAN_CUTOFF
;
981 describe_one_orphan(&sb
, last
);
983 strbuf_addf(&sb
, _(" ... and %d more.\n"), more
);
988 /* The singular version */
989 "Warning: you are leaving %d commit behind, "
991 "any of your branches:\n\n"
993 /* The plural version */
994 "Warning: you are leaving %d commits behind, "
996 "any of your branches:\n\n"
998 /* Give ngettext() the count */
1002 strbuf_release(&sb
);
1004 if (advice_detached_head
)
1007 /* The singular version */
1008 "If you want to keep it by creating a new branch, "
1009 "this may be a good time\nto do so with:\n\n"
1010 " git branch <new-branch-name> %s\n\n",
1011 /* The plural version */
1012 "If you want to keep them by creating a new branch, "
1013 "this may be a good time\nto do so with:\n\n"
1014 " git branch <new-branch-name> %s\n\n",
1015 /* Give ngettext() the count */
1017 find_unique_abbrev(&commit
->object
.oid
, DEFAULT_ABBREV
));
1021 * We are about to leave commit that was at the tip of a detached
1022 * HEAD. If it is not reachable from any ref, this is the last chance
1023 * for the user to do so without resorting to reflog.
1025 static void orphaned_commit_warning(struct commit
*old_commit
, struct commit
*new_commit
)
1027 struct rev_info revs
;
1028 struct object
*object
= &old_commit
->object
;
1030 repo_init_revisions(the_repository
, &revs
, NULL
);
1031 setup_revisions(0, NULL
, &revs
, NULL
);
1033 object
->flags
&= ~UNINTERESTING
;
1034 add_pending_object(&revs
, object
, oid_to_hex(&object
->oid
));
1036 for_each_ref(add_pending_uninteresting_ref
, &revs
);
1038 add_pending_oid(&revs
, "HEAD",
1039 &new_commit
->object
.oid
,
1042 if (prepare_revision_walk(&revs
))
1043 die(_("internal error in revision walk"));
1044 if (!(old_commit
->object
.flags
& UNINTERESTING
))
1045 suggest_reattach(old_commit
, &revs
);
1047 describe_detached_head(_("Previous HEAD position was"), old_commit
);
1049 /* Clean up objects used, as they will be reused. */
1050 repo_clear_commit_marks(the_repository
, ALL_REV_FLAGS
);
1053 static int switch_branches(const struct checkout_opts
*opts
,
1054 struct branch_info
*new_branch_info
)
1057 struct branch_info old_branch_info
;
1059 struct object_id rev
;
1060 int flag
, writeout_error
= 0;
1063 trace2_cmd_mode("branch");
1065 memset(&old_branch_info
, 0, sizeof(old_branch_info
));
1066 old_branch_info
.path
= path_to_free
= resolve_refdup("HEAD", 0, &rev
, &flag
);
1067 if (old_branch_info
.path
)
1068 old_branch_info
.commit
= lookup_commit_reference_gently(the_repository
, &rev
, 1);
1069 if (!(flag
& REF_ISSYMREF
))
1070 old_branch_info
.path
= NULL
;
1072 if (old_branch_info
.path
)
1073 skip_prefix(old_branch_info
.path
, "refs/heads/", &old_branch_info
.name
);
1075 if (opts
->new_orphan_branch
&& opts
->orphan_from_empty_tree
) {
1076 if (new_branch_info
->name
)
1077 BUG("'switch --orphan' should never accept a commit as starting point");
1078 new_branch_info
->commit
= NULL
;
1079 new_branch_info
->name
= "(empty)";
1083 if (!new_branch_info
->name
) {
1084 new_branch_info
->name
= "HEAD";
1085 new_branch_info
->commit
= old_branch_info
.commit
;
1086 if (!new_branch_info
->commit
)
1087 die(_("You are on a branch yet to be born"));
1088 parse_commit_or_die(new_branch_info
->commit
);
1090 if (opts
->only_merge_on_switching_branches
)
1095 ret
= merge_working_tree(opts
, &old_branch_info
, new_branch_info
, &writeout_error
);
1102 if (!opts
->quiet
&& !old_branch_info
.path
&& old_branch_info
.commit
&& new_branch_info
->commit
!= old_branch_info
.commit
)
1103 orphaned_commit_warning(old_branch_info
.commit
, new_branch_info
->commit
);
1105 update_refs_for_switch(opts
, &old_branch_info
, new_branch_info
);
1107 ret
= post_checkout_hook(old_branch_info
.commit
, new_branch_info
->commit
, 1);
1109 return ret
|| writeout_error
;
1112 static int git_checkout_config(const char *var
, const char *value
, void *cb
)
1114 struct checkout_opts
*opts
= cb
;
1116 if (!strcmp(var
, "diff.ignoresubmodules")) {
1117 handle_ignore_submodules_arg(&opts
->diff_options
, value
);
1120 if (!strcmp(var
, "checkout.guess")) {
1121 opts
->dwim_new_local_branch
= git_config_bool(var
, value
);
1125 if (starts_with(var
, "submodule."))
1126 return git_default_submodule_config(var
, value
, NULL
);
1128 return git_xmerge_config(var
, value
, NULL
);
1131 static void setup_new_branch_info_and_source_tree(
1132 struct branch_info
*new_branch_info
,
1133 struct checkout_opts
*opts
,
1134 struct object_id
*rev
,
1137 struct tree
**source_tree
= &opts
->source_tree
;
1138 struct object_id branch_rev
;
1140 new_branch_info
->name
= arg
;
1141 setup_branch_path(new_branch_info
);
1143 if (!check_refname_format(new_branch_info
->path
, 0) &&
1144 !read_ref(new_branch_info
->path
, &branch_rev
))
1145 oidcpy(rev
, &branch_rev
);
1147 free((char *)new_branch_info
->path
);
1148 new_branch_info
->path
= NULL
; /* not an existing branch */
1151 new_branch_info
->commit
= lookup_commit_reference_gently(the_repository
, rev
, 1);
1152 if (!new_branch_info
->commit
) {
1154 *source_tree
= parse_tree_indirect(rev
);
1156 parse_commit_or_die(new_branch_info
->commit
);
1157 *source_tree
= get_commit_tree(new_branch_info
->commit
);
1161 static const char *parse_remote_branch(const char *arg
,
1162 struct object_id
*rev
,
1163 int could_be_checkout_paths
)
1165 int num_matches
= 0;
1166 const char *remote
= unique_tracking_name(arg
, rev
, &num_matches
);
1168 if (remote
&& could_be_checkout_paths
) {
1169 die(_("'%s' could be both a local file and a tracking branch.\n"
1170 "Please use -- (and optionally --no-guess) to disambiguate"),
1174 if (!remote
&& num_matches
> 1) {
1175 if (advice_checkout_ambiguous_remote_branch_name
) {
1176 advise(_("If you meant to check out a remote tracking branch on, e.g. 'origin',\n"
1177 "you can do so by fully qualifying the name with the --track option:\n"
1179 " git checkout --track origin/<name>\n"
1181 "If you'd like to always have checkouts of an ambiguous <name> prefer\n"
1182 "one remote, e.g. the 'origin' remote, consider setting\n"
1183 "checkout.defaultRemote=origin in your config."));
1186 die(_("'%s' matched multiple (%d) remote tracking branches"),
1193 static int parse_branchname_arg(int argc
, const char **argv
,
1194 int dwim_new_local_branch_ok
,
1195 struct branch_info
*new_branch_info
,
1196 struct checkout_opts
*opts
,
1197 struct object_id
*rev
)
1199 const char **new_branch
= &opts
->new_branch
;
1203 int has_dash_dash
= 0;
1207 * case 1: git checkout <ref> -- [<paths>]
1209 * <ref> must be a valid tree, everything after the '--' must be
1212 * case 2: git checkout -- [<paths>]
1214 * everything after the '--' must be paths.
1216 * case 3: git checkout <something> [--]
1218 * (a) If <something> is a commit, that is to
1219 * switch to the branch or detach HEAD at it. As a special case,
1220 * if <something> is A...B (missing A or B means HEAD but you can
1221 * omit at most one side), and if there is a unique merge base
1222 * between A and B, A...B names that merge base.
1224 * (b) If <something> is _not_ a commit, either "--" is present
1225 * or <something> is not a path, no -t or -b was given, and
1226 * and there is a tracking branch whose name is <something>
1227 * in one and only one remote (or if the branch exists on the
1228 * remote named in checkout.defaultRemote), then this is a
1229 * short-hand to fork local <something> from that
1230 * remote-tracking branch.
1232 * (c) Otherwise, if "--" is present, treat it like case (1).
1235 * - if it's a reference, treat it like case (1)
1236 * - else if it's a path, treat it like case (2)
1239 * case 4: git checkout <something> <paths>
1241 * The first argument must not be ambiguous.
1242 * - If it's *only* a reference, treat it like case (1).
1243 * - If it's only a path, treat it like case (2).
1250 if (!opts
->accept_pathspec
) {
1252 die(_("only one reference expected"));
1253 has_dash_dash
= 1; /* helps disambiguate */
1258 for (i
= 0; i
< argc
; i
++) {
1259 if (opts
->accept_pathspec
&& !strcmp(argv
[i
], "--")) {
1264 if (dash_dash_pos
== 0)
1265 return 1; /* case (2) */
1266 else if (dash_dash_pos
== 1)
1267 has_dash_dash
= 1; /* case (3) or (1) */
1268 else if (dash_dash_pos
>= 2)
1269 die(_("only one reference expected, %d given."), dash_dash_pos
);
1270 opts
->count_checkout_paths
= !opts
->quiet
&& !has_dash_dash
;
1272 if (!strcmp(arg
, "-"))
1275 if (get_oid_mb(arg
, rev
)) {
1277 * Either case (3) or (4), with <something> not being
1278 * a commit, or an attempt to use case (1) with an
1281 * It's likely an error, but we need to find out if
1282 * we should auto-create the branch, case (3).(b).
1284 int recover_with_dwim
= dwim_new_local_branch_ok
;
1286 int could_be_checkout_paths
= !has_dash_dash
&&
1287 check_filename(opts
->prefix
, arg
);
1289 if (!has_dash_dash
&& !no_wildcard(arg
))
1290 recover_with_dwim
= 0;
1293 * Accept "git checkout foo", "git checkout foo --"
1294 * and "git switch foo" as candidates for dwim.
1296 if (!(argc
== 1 && !has_dash_dash
) &&
1297 !(argc
== 2 && has_dash_dash
) &&
1298 opts
->accept_pathspec
)
1299 recover_with_dwim
= 0;
1301 if (recover_with_dwim
) {
1302 const char *remote
= parse_remote_branch(arg
, rev
,
1303 could_be_checkout_paths
);
1307 /* DWIMmed to create local branch, case (3).(b) */
1309 recover_with_dwim
= 0;
1313 if (!recover_with_dwim
) {
1315 die(_("invalid reference: %s"), arg
);
1320 /* we can't end up being in (2) anymore, eat the argument */
1325 setup_new_branch_info_and_source_tree(new_branch_info
, opts
, rev
, arg
);
1327 if (!opts
->source_tree
) /* case (1): want a tree */
1328 die(_("reference is not a tree: %s"), arg
);
1330 if (!has_dash_dash
) { /* case (3).(d) -> (1) */
1332 * Do not complain the most common case
1333 * git checkout branch
1334 * even if there happen to be a file called 'branch';
1335 * it would be extremely annoying.
1338 verify_non_filename(opts
->prefix
, arg
);
1339 } else if (opts
->accept_pathspec
) {
1348 static int switch_unborn_to_new_branch(const struct checkout_opts
*opts
)
1351 struct strbuf branch_ref
= STRBUF_INIT
;
1353 trace2_cmd_mode("unborn");
1355 if (!opts
->new_branch
)
1356 die(_("You are on a branch yet to be born"));
1357 strbuf_addf(&branch_ref
, "refs/heads/%s", opts
->new_branch
);
1358 status
= create_symref("HEAD", branch_ref
.buf
, "checkout -b");
1359 strbuf_release(&branch_ref
);
1361 fprintf(stderr
, _("Switched to a new branch '%s'\n"),
1366 static void die_expecting_a_branch(const struct branch_info
*branch_info
)
1368 struct object_id oid
;
1371 if (dwim_ref(branch_info
->name
, strlen(branch_info
->name
), &oid
, &to_free
, 0) == 1) {
1372 const char *ref
= to_free
;
1374 if (skip_prefix(ref
, "refs/tags/", &ref
))
1375 die(_("a branch is expected, got tag '%s'"), ref
);
1376 if (skip_prefix(ref
, "refs/remotes/", &ref
))
1377 die(_("a branch is expected, got remote branch '%s'"), ref
);
1378 die(_("a branch is expected, got '%s'"), ref
);
1380 if (branch_info
->commit
)
1381 die(_("a branch is expected, got commit '%s'"), branch_info
->name
);
1383 * This case should never happen because we already die() on
1384 * non-commit, but just in case.
1386 die(_("a branch is expected, got '%s'"), branch_info
->name
);
1389 static void die_if_some_operation_in_progress(void)
1391 struct wt_status_state state
;
1393 memset(&state
, 0, sizeof(state
));
1394 wt_status_get_state(the_repository
, &state
, 0);
1396 if (state
.merge_in_progress
)
1397 die(_("cannot switch branch while merging\n"
1398 "Consider \"git merge --quit\" "
1399 "or \"git worktree add\"."));
1400 if (state
.am_in_progress
)
1401 die(_("cannot switch branch in the middle of an am session\n"
1402 "Consider \"git am --quit\" "
1403 "or \"git worktree add\"."));
1404 if (state
.rebase_interactive_in_progress
|| state
.rebase_in_progress
)
1405 die(_("cannot switch branch while rebasing\n"
1406 "Consider \"git rebase --quit\" "
1407 "or \"git worktree add\"."));
1408 if (state
.cherry_pick_in_progress
)
1409 die(_("cannot switch branch while cherry-picking\n"
1410 "Consider \"git cherry-pick --quit\" "
1411 "or \"git worktree add\"."));
1412 if (state
.revert_in_progress
)
1413 die(_("cannot switch branch while reverting\n"
1414 "Consider \"git revert --quit\" "
1415 "or \"git worktree add\"."));
1416 if (state
.bisect_in_progress
)
1417 warning(_("you are switching branch while bisecting"));
1420 static int checkout_branch(struct checkout_opts
*opts
,
1421 struct branch_info
*new_branch_info
)
1423 if (opts
->pathspec
.nr
)
1424 die(_("paths cannot be used with switching branches"));
1426 if (opts
->patch_mode
)
1427 die(_("'%s' cannot be used with switching branches"),
1430 if (opts
->overlay_mode
!= -1)
1431 die(_("'%s' cannot be used with switching branches"),
1434 if (opts
->writeout_stage
)
1435 die(_("'%s' cannot be used with switching branches"),
1438 if (opts
->force
&& opts
->merge
)
1439 die(_("'%s' cannot be used with '%s'"), "-f", "-m");
1441 if (opts
->discard_changes
&& opts
->merge
)
1442 die(_("'%s' cannot be used with '%s'"), "--discard-changes", "--merge");
1444 if (opts
->force_detach
&& opts
->new_branch
)
1445 die(_("'%s' cannot be used with '%s'"),
1446 "--detach", "-b/-B/--orphan");
1448 if (opts
->new_orphan_branch
) {
1449 if (opts
->track
!= BRANCH_TRACK_UNSPECIFIED
)
1450 die(_("'%s' cannot be used with '%s'"), "--orphan", "-t");
1451 if (opts
->orphan_from_empty_tree
&& new_branch_info
->name
)
1452 die(_("'%s' cannot take <start-point>"), "--orphan");
1453 } else if (opts
->force_detach
) {
1454 if (opts
->track
!= BRANCH_TRACK_UNSPECIFIED
)
1455 die(_("'%s' cannot be used with '%s'"), "--detach", "-t");
1456 } else if (opts
->track
== BRANCH_TRACK_UNSPECIFIED
)
1457 opts
->track
= git_branch_track
;
1459 if (new_branch_info
->name
&& !new_branch_info
->commit
)
1460 die(_("Cannot switch branch to a non-commit '%s'"),
1461 new_branch_info
->name
);
1463 if (!opts
->switch_branch_doing_nothing_is_ok
&&
1464 !new_branch_info
->name
&&
1465 !opts
->new_branch
&&
1466 !opts
->force_detach
)
1467 die(_("missing branch or commit argument"));
1469 if (!opts
->implicit_detach
&&
1470 !opts
->force_detach
&&
1471 !opts
->new_branch
&&
1472 !opts
->new_branch_force
&&
1473 new_branch_info
->name
&&
1474 !new_branch_info
->path
)
1475 die_expecting_a_branch(new_branch_info
);
1477 if (!opts
->can_switch_when_in_progress
)
1478 die_if_some_operation_in_progress();
1480 if (new_branch_info
->path
&& !opts
->force_detach
&& !opts
->new_branch
&&
1481 !opts
->ignore_other_worktrees
) {
1483 char *head_ref
= resolve_refdup("HEAD", 0, NULL
, &flag
);
1485 (!(flag
& REF_ISSYMREF
) || strcmp(head_ref
, new_branch_info
->path
)))
1486 die_if_checked_out(new_branch_info
->path
, 1);
1490 if (!new_branch_info
->commit
&& opts
->new_branch
) {
1491 struct object_id rev
;
1494 if (!read_ref_full("HEAD", 0, &rev
, &flag
) &&
1495 (flag
& REF_ISSYMREF
) && is_null_oid(&rev
))
1496 return switch_unborn_to_new_branch(opts
);
1498 return switch_branches(opts
, new_branch_info
);
1501 static struct option
*add_common_options(struct checkout_opts
*opts
,
1502 struct option
*prevopts
)
1504 struct option options
[] = {
1505 OPT__QUIET(&opts
->quiet
, N_("suppress progress reporting")),
1506 OPT_CALLBACK_F(0, "recurse-submodules", NULL
,
1507 "checkout", "control recursive updating of submodules",
1508 PARSE_OPT_OPTARG
, option_parse_recurse_submodules_worktree_updater
),
1509 OPT_BOOL(0, "progress", &opts
->show_progress
, N_("force progress reporting")),
1510 OPT_BOOL('m', "merge", &opts
->merge
, N_("perform a 3-way merge with the new branch")),
1511 OPT_STRING(0, "conflict", &opts
->conflict_style
, N_("style"),
1512 N_("conflict style (merge or diff3)")),
1515 struct option
*newopts
= parse_options_concat(prevopts
, options
);
1520 static struct option
*add_common_switch_branch_options(
1521 struct checkout_opts
*opts
, struct option
*prevopts
)
1523 struct option options
[] = {
1524 OPT_BOOL('d', "detach", &opts
->force_detach
, N_("detach HEAD at named commit")),
1525 OPT_SET_INT('t', "track", &opts
->track
, N_("set upstream info for new branch"),
1526 BRANCH_TRACK_EXPLICIT
),
1527 OPT__FORCE(&opts
->force
, N_("force checkout (throw away local modifications)"),
1528 PARSE_OPT_NOCOMPLETE
),
1529 OPT_STRING(0, "orphan", &opts
->new_orphan_branch
, N_("new-branch"), N_("new unparented branch")),
1530 OPT_BOOL_F(0, "overwrite-ignore", &opts
->overwrite_ignore
,
1531 N_("update ignored files (default)"),
1532 PARSE_OPT_NOCOMPLETE
),
1533 OPT_BOOL(0, "ignore-other-worktrees", &opts
->ignore_other_worktrees
,
1534 N_("do not check if another worktree is holding the given ref")),
1537 struct option
*newopts
= parse_options_concat(prevopts
, options
);
1542 static struct option
*add_checkout_path_options(struct checkout_opts
*opts
,
1543 struct option
*prevopts
)
1545 struct option options
[] = {
1546 OPT_SET_INT_F('2', "ours", &opts
->writeout_stage
,
1547 N_("checkout our version for unmerged files"),
1548 2, PARSE_OPT_NONEG
),
1549 OPT_SET_INT_F('3', "theirs", &opts
->writeout_stage
,
1550 N_("checkout their version for unmerged files"),
1551 3, PARSE_OPT_NONEG
),
1552 OPT_BOOL('p', "patch", &opts
->patch_mode
, N_("select hunks interactively")),
1553 OPT_BOOL(0, "ignore-skip-worktree-bits", &opts
->ignore_skipworktree
,
1554 N_("do not limit pathspecs to sparse entries only")),
1555 OPT_PATHSPEC_FROM_FILE(&opts
->pathspec_from_file
),
1556 OPT_PATHSPEC_FILE_NUL(&opts
->pathspec_file_nul
),
1559 struct option
*newopts
= parse_options_concat(prevopts
, options
);
1564 /* create-branch option (either b or c) */
1565 static char cb_option
= 'b';
1567 static int checkout_main(int argc
, const char **argv
, const char *prefix
,
1568 struct checkout_opts
*opts
, struct option
*options
,
1569 const char * const usagestr
[])
1571 struct branch_info new_branch_info
;
1572 int parseopt_flags
= 0;
1574 memset(&new_branch_info
, 0, sizeof(new_branch_info
));
1575 opts
->overwrite_ignore
= 1;
1576 opts
->prefix
= prefix
;
1577 opts
->show_progress
= -1;
1579 git_config(git_checkout_config
, opts
);
1581 opts
->track
= BRANCH_TRACK_UNSPECIFIED
;
1583 if (!opts
->accept_pathspec
&& !opts
->accept_ref
)
1584 BUG("make up your mind, you need to take _something_");
1585 if (opts
->accept_pathspec
&& opts
->accept_ref
)
1586 parseopt_flags
= PARSE_OPT_KEEP_DASHDASH
;
1588 argc
= parse_options(argc
, argv
, prefix
, options
,
1589 usagestr
, parseopt_flags
);
1591 if (opts
->show_progress
< 0) {
1593 opts
->show_progress
= 0;
1595 opts
->show_progress
= isatty(2);
1598 if (opts
->conflict_style
) {
1599 opts
->merge
= 1; /* implied */
1600 git_xmerge_config("merge.conflictstyle", opts
->conflict_style
, NULL
);
1603 opts
->discard_changes
= 1;
1604 opts
->ignore_unmerged_opt
= "--force";
1605 opts
->ignore_unmerged
= 1;
1608 if ((!!opts
->new_branch
+ !!opts
->new_branch_force
+ !!opts
->new_orphan_branch
) > 1)
1609 die(_("-%c, -%c and --orphan are mutually exclusive"),
1610 cb_option
, toupper(cb_option
));
1612 if (opts
->overlay_mode
== 1 && opts
->patch_mode
)
1613 die(_("-p and --overlay are mutually exclusive"));
1615 if (opts
->checkout_index
>= 0 || opts
->checkout_worktree
>= 0) {
1616 if (opts
->checkout_index
< 0)
1617 opts
->checkout_index
= 0;
1618 if (opts
->checkout_worktree
< 0)
1619 opts
->checkout_worktree
= 0;
1621 if (opts
->checkout_index
< 0)
1622 opts
->checkout_index
= -opts
->checkout_index
- 1;
1623 if (opts
->checkout_worktree
< 0)
1624 opts
->checkout_worktree
= -opts
->checkout_worktree
- 1;
1626 if (opts
->checkout_index
< 0 || opts
->checkout_worktree
< 0)
1627 BUG("these flags should be non-negative by now");
1629 * convenient shortcut: "git restore --staged [--worktree]" equals
1630 * "git restore --staged [--worktree] --source HEAD"
1632 if (!opts
->from_treeish
&& opts
->checkout_index
)
1633 opts
->from_treeish
= "HEAD";
1636 * From here on, new_branch will contain the branch to be checked out,
1637 * and new_branch_force and new_orphan_branch will tell us which one of
1638 * -b/-B/-c/-C/--orphan is being used.
1640 if (opts
->new_branch_force
)
1641 opts
->new_branch
= opts
->new_branch_force
;
1643 if (opts
->new_orphan_branch
)
1644 opts
->new_branch
= opts
->new_orphan_branch
;
1646 /* --track without -c/-C/-b/-B/--orphan should DWIM */
1647 if (opts
->track
!= BRANCH_TRACK_UNSPECIFIED
&& !opts
->new_branch
) {
1648 const char *argv0
= argv
[0];
1649 if (!argc
|| !strcmp(argv0
, "--"))
1650 die(_("--track needs a branch name"));
1651 skip_prefix(argv0
, "refs/", &argv0
);
1652 skip_prefix(argv0
, "remotes/", &argv0
);
1653 argv0
= strchr(argv0
, '/');
1654 if (!argv0
|| !argv0
[1])
1655 die(_("missing branch name; try -%c"), cb_option
);
1656 opts
->new_branch
= argv0
+ 1;
1660 * Extract branch name from command line arguments, so
1661 * all that is left is pathspecs.
1665 * 1) git checkout <tree> -- [<paths>]
1666 * 2) git checkout -- [<paths>]
1667 * 3) git checkout <something> [<paths>]
1669 * including "last branch" syntax and DWIM-ery for names of
1670 * remote branches, erroring out for invalid or ambiguous cases.
1672 if (argc
&& opts
->accept_ref
) {
1673 struct object_id rev
;
1675 !opts
->patch_mode
&&
1676 opts
->dwim_new_local_branch
&&
1677 opts
->track
== BRANCH_TRACK_UNSPECIFIED
&&
1679 int n
= parse_branchname_arg(argc
, argv
, dwim_ok
,
1680 &new_branch_info
, opts
, &rev
);
1683 } else if (!opts
->accept_ref
&& opts
->from_treeish
) {
1684 struct object_id rev
;
1686 if (get_oid_mb(opts
->from_treeish
, &rev
))
1687 die(_("could not resolve %s"), opts
->from_treeish
);
1689 setup_new_branch_info_and_source_tree(&new_branch_info
,
1691 opts
->from_treeish
);
1693 if (!opts
->source_tree
)
1694 die(_("reference is not a tree: %s"), opts
->from_treeish
);
1698 parse_pathspec(&opts
->pathspec
, 0,
1699 opts
->patch_mode
? PATHSPEC_PREFIX_ORIGIN
: 0,
1702 if (!opts
->pathspec
.nr
)
1703 die(_("invalid path specification"));
1706 * Try to give more helpful suggestion.
1707 * new_branch && argc > 1 will be caught later.
1709 if (opts
->new_branch
&& argc
== 1 && !new_branch_info
.commit
)
1710 die(_("'%s' is not a commit and a branch '%s' cannot be created from it"),
1711 argv
[0], opts
->new_branch
);
1713 if (opts
->force_detach
)
1714 die(_("git checkout: --detach does not take a path argument '%s'"),
1718 if (opts
->pathspec_from_file
) {
1719 if (opts
->pathspec
.nr
)
1720 die(_("--pathspec-from-file is incompatible with pathspec arguments"));
1722 if (opts
->force_detach
)
1723 die(_("--pathspec-from-file is incompatible with --detach"));
1725 if (opts
->patch_mode
)
1726 die(_("--pathspec-from-file is incompatible with --patch"));
1728 parse_pathspec_file(&opts
->pathspec
, 0,
1730 prefix
, opts
->pathspec_from_file
, opts
->pathspec_file_nul
);
1731 } else if (opts
->pathspec_file_nul
) {
1732 die(_("--pathspec-file-nul requires --pathspec-from-file"));
1735 opts
->pathspec
.recursive
= 1;
1737 if (opts
->pathspec
.nr
) {
1738 if (1 < !!opts
->writeout_stage
+ !!opts
->force
+ !!opts
->merge
)
1739 die(_("git checkout: --ours/--theirs, --force and --merge are incompatible when\n"
1740 "checking out of the index."));
1742 if (opts
->accept_pathspec
&& !opts
->empty_pathspec_ok
&&
1743 !opts
->patch_mode
) /* patch mode is special */
1744 die(_("you must specify path(s) to restore"));
1747 if (opts
->new_branch
) {
1748 struct strbuf buf
= STRBUF_INIT
;
1750 if (opts
->new_branch_force
)
1751 opts
->branch_exists
= validate_branchname(opts
->new_branch
, &buf
);
1753 opts
->branch_exists
=
1754 validate_new_branchname(opts
->new_branch
, &buf
, 0);
1755 strbuf_release(&buf
);
1759 if (opts
->patch_mode
|| opts
->pathspec
.nr
)
1760 return checkout_paths(opts
, &new_branch_info
);
1762 return checkout_branch(opts
, &new_branch_info
);
1765 int cmd_checkout(int argc
, const char **argv
, const char *prefix
)
1767 struct checkout_opts opts
;
1768 struct option
*options
;
1769 struct option checkout_options
[] = {
1770 OPT_STRING('b', NULL
, &opts
.new_branch
, N_("branch"),
1771 N_("create and checkout a new branch")),
1772 OPT_STRING('B', NULL
, &opts
.new_branch_force
, N_("branch"),
1773 N_("create/reset and checkout a branch")),
1774 OPT_BOOL('l', NULL
, &opts
.new_branch_log
, N_("create reflog for new branch")),
1775 OPT_BOOL(0, "guess", &opts
.dwim_new_local_branch
,
1776 N_("second guess 'git checkout <no-such-branch>' (default)")),
1777 OPT_BOOL(0, "overlay", &opts
.overlay_mode
, N_("use overlay mode (default)")),
1782 memset(&opts
, 0, sizeof(opts
));
1783 opts
.dwim_new_local_branch
= 1;
1784 opts
.switch_branch_doing_nothing_is_ok
= 1;
1785 opts
.only_merge_on_switching_branches
= 0;
1786 opts
.accept_ref
= 1;
1787 opts
.accept_pathspec
= 1;
1788 opts
.implicit_detach
= 1;
1789 opts
.can_switch_when_in_progress
= 1;
1790 opts
.orphan_from_empty_tree
= 0;
1791 opts
.empty_pathspec_ok
= 1;
1792 opts
.overlay_mode
= -1;
1793 opts
.checkout_index
= -2; /* default on */
1794 opts
.checkout_worktree
= -2; /* default on */
1796 if (argc
== 3 && !strcmp(argv
[1], "-b")) {
1798 * User ran 'git checkout -b <branch>' and expects
1799 * the same behavior as 'git switch -c <branch>'.
1801 opts
.switch_branch_doing_nothing_is_ok
= 0;
1802 opts
.only_merge_on_switching_branches
= 1;
1805 options
= parse_options_dup(checkout_options
);
1806 options
= add_common_options(&opts
, options
);
1807 options
= add_common_switch_branch_options(&opts
, options
);
1808 options
= add_checkout_path_options(&opts
, options
);
1810 ret
= checkout_main(argc
, argv
, prefix
, &opts
,
1811 options
, checkout_usage
);
1812 FREE_AND_NULL(options
);
1816 int cmd_switch(int argc
, const char **argv
, const char *prefix
)
1818 struct checkout_opts opts
;
1819 struct option
*options
= NULL
;
1820 struct option switch_options
[] = {
1821 OPT_STRING('c', "create", &opts
.new_branch
, N_("branch"),
1822 N_("create and switch to a new branch")),
1823 OPT_STRING('C', "force-create", &opts
.new_branch_force
, N_("branch"),
1824 N_("create/reset and switch to a branch")),
1825 OPT_BOOL(0, "guess", &opts
.dwim_new_local_branch
,
1826 N_("second guess 'git switch <no-such-branch>'")),
1827 OPT_BOOL(0, "discard-changes", &opts
.discard_changes
,
1828 N_("throw away local modifications")),
1833 memset(&opts
, 0, sizeof(opts
));
1834 opts
.dwim_new_local_branch
= 1;
1835 opts
.accept_ref
= 1;
1836 opts
.accept_pathspec
= 0;
1837 opts
.switch_branch_doing_nothing_is_ok
= 0;
1838 opts
.only_merge_on_switching_branches
= 1;
1839 opts
.implicit_detach
= 0;
1840 opts
.can_switch_when_in_progress
= 0;
1841 opts
.orphan_from_empty_tree
= 1;
1842 opts
.overlay_mode
= -1;
1844 options
= parse_options_dup(switch_options
);
1845 options
= add_common_options(&opts
, options
);
1846 options
= add_common_switch_branch_options(&opts
, options
);
1850 ret
= checkout_main(argc
, argv
, prefix
, &opts
,
1851 options
, switch_branch_usage
);
1852 FREE_AND_NULL(options
);
1856 int cmd_restore(int argc
, const char **argv
, const char *prefix
)
1858 struct checkout_opts opts
;
1859 struct option
*options
;
1860 struct option restore_options
[] = {
1861 OPT_STRING('s', "source", &opts
.from_treeish
, "<tree-ish>",
1862 N_("which tree-ish to checkout from")),
1863 OPT_BOOL('S', "staged", &opts
.checkout_index
,
1864 N_("restore the index")),
1865 OPT_BOOL('W', "worktree", &opts
.checkout_worktree
,
1866 N_("restore the working tree (default)")),
1867 OPT_BOOL(0, "ignore-unmerged", &opts
.ignore_unmerged
,
1868 N_("ignore unmerged entries")),
1869 OPT_BOOL(0, "overlay", &opts
.overlay_mode
, N_("use overlay mode")),
1874 memset(&opts
, 0, sizeof(opts
));
1875 opts
.accept_ref
= 0;
1876 opts
.accept_pathspec
= 1;
1877 opts
.empty_pathspec_ok
= 0;
1878 opts
.overlay_mode
= 0;
1879 opts
.checkout_index
= -1; /* default off */
1880 opts
.checkout_worktree
= -2; /* default on */
1881 opts
.ignore_unmerged_opt
= "--ignore-unmerged";
1883 options
= parse_options_dup(restore_options
);
1884 options
= add_common_options(&opts
, options
);
1885 options
= add_checkout_path_options(&opts
, options
);
1887 ret
= checkout_main(argc
, argv
, prefix
, &opts
,
1888 options
, restore_usage
);
1889 FREE_AND_NULL(options
);