5 #include "parse-options.h"
7 #include "object-store.h"
10 #include "tree-walk.h"
11 #include "cache-tree.h"
12 #include "unpack-trees.h"
14 #include "run-command.h"
15 #include "merge-recursive.h"
21 #include "xdiff-interface.h"
23 #include "resolve-undo.h"
24 #include "submodule-config.h"
25 #include "submodule.h"
28 static int checkout_optimize_new_branch
;
30 static const char * const checkout_usage
[] = {
31 N_("git checkout [<options>] <branch>"),
32 N_("git checkout [<options>] [<branch>] -- <file>..."),
36 struct checkout_opts
{
44 int ignore_skipworktree
;
45 int ignore_other_worktrees
;
47 int count_checkout_paths
;
49 * If new checkout options are added, skip_merge_working_tree
50 * should be updated accordingly.
53 const char *new_branch
;
54 const char *new_branch_force
;
55 const char *new_orphan_branch
;
57 enum branch_track track
;
58 struct diff_options diff_options
;
62 struct pathspec pathspec
;
63 struct tree
*source_tree
;
66 static int post_checkout_hook(struct commit
*old_commit
, struct commit
*new_commit
,
69 return run_hook_le(NULL
, "post-checkout",
70 oid_to_hex(old_commit
? &old_commit
->object
.oid
: &null_oid
),
71 oid_to_hex(new_commit
? &new_commit
->object
.oid
: &null_oid
),
72 changed
? "1" : "0", NULL
);
73 /* "new_commit" can be NULL when checking out from the index before
78 static int update_some(const struct object_id
*oid
, struct strbuf
*base
,
79 const char *pathname
, unsigned mode
, int stage
, void *context
)
82 struct cache_entry
*ce
;
86 return READ_TREE_RECURSIVE
;
88 len
= base
->len
+ strlen(pathname
);
89 ce
= make_empty_cache_entry(&the_index
, len
);
90 oidcpy(&ce
->oid
, oid
);
91 memcpy(ce
->name
, base
->buf
, base
->len
);
92 memcpy(ce
->name
+ base
->len
, pathname
, len
- base
->len
);
93 ce
->ce_flags
= create_ce_flags(0) | CE_UPDATE
;
95 ce
->ce_mode
= create_ce_mode(mode
);
98 * If the entry is the same as the current index, we can leave the old
99 * entry in place. Whether it is UPTODATE or not, checkout_entry will
100 * do the right thing.
102 pos
= cache_name_pos(ce
->name
, ce
->ce_namelen
);
104 struct cache_entry
*old
= active_cache
[pos
];
105 if (ce
->ce_mode
== old
->ce_mode
&&
106 oideq(&ce
->oid
, &old
->oid
)) {
107 old
->ce_flags
|= CE_UPDATE
;
108 discard_cache_entry(ce
);
113 add_cache_entry(ce
, ADD_CACHE_OK_TO_ADD
| ADD_CACHE_OK_TO_REPLACE
);
117 static int read_tree_some(struct tree
*tree
, const struct pathspec
*pathspec
)
119 read_tree_recursive(tree
, "", 0, 0, pathspec
, update_some
, NULL
);
121 /* update the index with the given tree's info
122 * for all args, expanding wildcards, and exit
123 * with any non-zero return code.
128 static int skip_same_name(const struct cache_entry
*ce
, int pos
)
130 while (++pos
< active_nr
&&
131 !strcmp(active_cache
[pos
]->name
, ce
->name
))
136 static int check_stage(int stage
, const struct cache_entry
*ce
, int pos
)
138 while (pos
< active_nr
&&
139 !strcmp(active_cache
[pos
]->name
, ce
->name
)) {
140 if (ce_stage(active_cache
[pos
]) == stage
)
145 return error(_("path '%s' does not have our version"), ce
->name
);
147 return error(_("path '%s' does not have their version"), ce
->name
);
150 static int check_stages(unsigned stages
, const struct cache_entry
*ce
, int pos
)
153 const char *name
= ce
->name
;
155 while (pos
< active_nr
) {
156 ce
= active_cache
[pos
];
157 if (strcmp(name
, ce
->name
))
159 seen
|= (1 << ce_stage(ce
));
162 if ((stages
& seen
) != stages
)
163 return error(_("path '%s' does not have all necessary versions"),
168 static int checkout_stage(int stage
, const struct cache_entry
*ce
, int pos
,
169 const struct checkout
*state
, int *nr_checkouts
)
171 while (pos
< active_nr
&&
172 !strcmp(active_cache
[pos
]->name
, ce
->name
)) {
173 if (ce_stage(active_cache
[pos
]) == stage
)
174 return checkout_entry(active_cache
[pos
], state
,
179 return error(_("path '%s' does not have our version"), ce
->name
);
181 return error(_("path '%s' does not have their version"), ce
->name
);
184 static int checkout_merged(int pos
, const struct checkout
*state
, int *nr_checkouts
)
186 struct cache_entry
*ce
= active_cache
[pos
];
187 const char *path
= ce
->name
;
188 mmfile_t ancestor
, ours
, theirs
;
190 struct object_id oid
;
191 mmbuffer_t result_buf
;
192 struct object_id threeway
[3];
195 memset(threeway
, 0, sizeof(threeway
));
196 while (pos
< active_nr
) {
198 stage
= ce_stage(ce
);
199 if (!stage
|| strcmp(path
, ce
->name
))
201 oidcpy(&threeway
[stage
- 1], &ce
->oid
);
203 mode
= create_ce_mode(ce
->ce_mode
);
205 ce
= active_cache
[pos
];
207 if (is_null_oid(&threeway
[1]) || is_null_oid(&threeway
[2]))
208 return error(_("path '%s' does not have necessary versions"), path
);
210 read_mmblob(&ancestor
, &threeway
[0]);
211 read_mmblob(&ours
, &threeway
[1]);
212 read_mmblob(&theirs
, &threeway
[2]);
215 * NEEDSWORK: re-create conflicts from merges with
216 * merge.renormalize set, too
218 status
= ll_merge(&result_buf
, path
, &ancestor
, "base",
219 &ours
, "ours", &theirs
, "theirs",
220 state
->istate
, NULL
);
224 if (status
< 0 || !result_buf
.ptr
) {
225 free(result_buf
.ptr
);
226 return error(_("path '%s': cannot merge"), path
);
231 * There is absolutely no reason to write this as a blob object
232 * and create a phony cache entry. This hack is primarily to get
233 * to the write_entry() machinery that massages the contents to
234 * work-tree format and writes out which only allows it for a
235 * cache entry. The code in write_entry() needs to be refactored
236 * to allow us to feed a <buffer, size, mode> instead of a cache
237 * entry. Such a refactoring would help merge_recursive as well
238 * (it also writes the merge result to the object database even
239 * when it may contain conflicts).
241 if (write_object_file(result_buf
.ptr
, result_buf
.size
, blob_type
, &oid
))
242 die(_("Unable to add merge result for '%s'"), path
);
243 free(result_buf
.ptr
);
244 ce
= make_transient_cache_entry(mode
, &oid
, path
, 2);
246 die(_("make_cache_entry failed for path '%s'"), path
);
247 status
= checkout_entry(ce
, state
, NULL
, nr_checkouts
);
248 discard_cache_entry(ce
);
252 static int checkout_paths(const struct checkout_opts
*opts
,
253 const char *revision
)
256 struct checkout state
= CHECKOUT_INIT
;
257 static char *ps_matched
;
258 struct object_id rev
;
261 struct lock_file lock_file
= LOCK_INIT
;
262 int nr_checkouts
= 0;
264 if (opts
->track
!= BRANCH_TRACK_UNSPECIFIED
)
265 die(_("'%s' cannot be used with updating paths"), "--track");
267 if (opts
->new_branch_log
)
268 die(_("'%s' cannot be used with updating paths"), "-l");
270 if (opts
->force
&& opts
->patch_mode
)
271 die(_("'%s' cannot be used with updating paths"), "-f");
273 if (opts
->force_detach
)
274 die(_("'%s' cannot be used with updating paths"), "--detach");
276 if (opts
->merge
&& opts
->patch_mode
)
277 die(_("'%s' cannot be used with %s"), "--merge", "--patch");
279 if (opts
->force
&& opts
->merge
)
280 die(_("'%s' cannot be used with %s"), "-f", "-m");
282 if (opts
->new_branch
)
283 die(_("Cannot update paths and switch to branch '%s' at the same time."),
286 if (opts
->patch_mode
)
287 return run_add_interactive(revision
, "--patch=checkout",
290 hold_locked_index(&lock_file
, LOCK_DIE_ON_ERROR
);
291 if (read_cache_preload(&opts
->pathspec
) < 0)
292 return error(_("index file corrupt"));
294 if (opts
->source_tree
)
295 read_tree_some(opts
->source_tree
, &opts
->pathspec
);
297 ps_matched
= xcalloc(opts
->pathspec
.nr
, 1);
300 * Make sure all pathspecs participated in locating the paths
303 for (pos
= 0; pos
< active_nr
; pos
++) {
304 struct cache_entry
*ce
= active_cache
[pos
];
305 ce
->ce_flags
&= ~CE_MATCHED
;
306 if (!opts
->ignore_skipworktree
&& ce_skip_worktree(ce
))
308 if (opts
->source_tree
&& !(ce
->ce_flags
& CE_UPDATE
))
310 * "git checkout tree-ish -- path", but this entry
311 * is in the original index; it will not be checked
312 * out to the working tree and it does not matter
313 * if pathspec matched this entry. We will not do
314 * anything to this entry at all.
318 * Either this entry came from the tree-ish we are
319 * checking the paths out of, or we are checking out
322 * If it comes from the tree-ish, we already know it
323 * matches the pathspec and could just stamp
324 * CE_MATCHED to it from update_some(). But we still
325 * need ps_matched and read_tree_recursive (and
326 * eventually tree_entry_interesting) cannot fill
327 * ps_matched yet. Once it can, we can avoid calling
328 * match_pathspec() for _all_ entries when
329 * opts->source_tree != NULL.
331 if (ce_path_match(&the_index
, ce
, &opts
->pathspec
, ps_matched
))
332 ce
->ce_flags
|= CE_MATCHED
;
335 if (report_path_error(ps_matched
, &opts
->pathspec
, opts
->prefix
)) {
341 /* "checkout -m path" to recreate conflicted state */
343 unmerge_marked_index(&the_index
);
345 /* Any unmerged paths? */
346 for (pos
= 0; pos
< active_nr
; pos
++) {
347 const struct cache_entry
*ce
= active_cache
[pos
];
348 if (ce
->ce_flags
& CE_MATCHED
) {
352 warning(_("path '%s' is unmerged"), ce
->name
);
353 } else if (opts
->writeout_stage
) {
354 errs
|= check_stage(opts
->writeout_stage
, ce
, pos
);
355 } else if (opts
->merge
) {
356 errs
|= check_stages((1<<2) | (1<<3), ce
, pos
);
359 error(_("path '%s' is unmerged"), ce
->name
);
361 pos
= skip_same_name(ce
, pos
) - 1;
367 /* Now we are committed to check them out */
369 state
.refresh_cache
= 1;
370 state
.istate
= &the_index
;
372 enable_delayed_checkout(&state
);
373 for (pos
= 0; pos
< active_nr
; pos
++) {
374 struct cache_entry
*ce
= active_cache
[pos
];
375 if (ce
->ce_flags
& CE_MATCHED
) {
377 errs
|= checkout_entry(ce
, &state
,
378 NULL
, &nr_checkouts
);
381 if (opts
->writeout_stage
)
382 errs
|= checkout_stage(opts
->writeout_stage
,
384 &state
, &nr_checkouts
);
385 else if (opts
->merge
)
386 errs
|= checkout_merged(pos
, &state
,
388 pos
= skip_same_name(ce
, pos
) - 1;
391 errs
|= finish_delayed_checkout(&state
, &nr_checkouts
);
393 if (opts
->count_checkout_paths
) {
394 if (opts
->source_tree
)
395 fprintf_ln(stderr
, Q_("Checked out %d path out of %s",
396 "Checked out %d paths out of %s",
399 find_unique_abbrev(&opts
->source_tree
->object
.oid
,
402 fprintf_ln(stderr
, Q_("Checked out %d path out of the index",
403 "Checked out %d paths out of the index",
408 if (write_locked_index(&the_index
, &lock_file
, COMMIT_LOCK
))
409 die(_("unable to write new index file"));
411 read_ref_full("HEAD", 0, &rev
, NULL
);
412 head
= lookup_commit_reference_gently(the_repository
, &rev
, 1);
414 errs
|= post_checkout_hook(head
, head
, 0);
418 static void show_local_changes(struct object
*head
,
419 const struct diff_options
*opts
)
422 /* I think we want full paths, even if we're in a subdirectory. */
423 repo_init_revisions(the_repository
, &rev
, NULL
);
424 rev
.diffopt
.flags
= opts
->flags
;
425 rev
.diffopt
.output_format
|= DIFF_FORMAT_NAME_STATUS
;
426 diff_setup_done(&rev
.diffopt
);
427 add_pending_object(&rev
, head
, NULL
);
428 run_diff_index(&rev
, 0);
431 static void describe_detached_head(const char *msg
, struct commit
*commit
)
433 struct strbuf sb
= STRBUF_INIT
;
435 if (!parse_commit(commit
))
436 pp_commit_easy(CMIT_FMT_ONELINE
, commit
, &sb
);
437 if (print_sha1_ellipsis()) {
438 fprintf(stderr
, "%s %s... %s\n", msg
,
439 find_unique_abbrev(&commit
->object
.oid
, DEFAULT_ABBREV
), sb
.buf
);
441 fprintf(stderr
, "%s %s %s\n", msg
,
442 find_unique_abbrev(&commit
->object
.oid
, DEFAULT_ABBREV
), sb
.buf
);
447 static int reset_tree(struct tree
*tree
, const struct checkout_opts
*o
,
448 int worktree
, int *writeout_error
)
450 struct unpack_trees_options opts
;
451 struct tree_desc tree_desc
;
453 memset(&opts
, 0, sizeof(opts
));
455 opts
.update
= worktree
;
456 opts
.skip_unmerged
= !worktree
;
459 opts
.fn
= oneway_merge
;
460 opts
.verbose_update
= o
->show_progress
;
461 opts
.src_index
= &the_index
;
462 opts
.dst_index
= &the_index
;
464 init_tree_desc(&tree_desc
, tree
->buffer
, tree
->size
);
465 switch (unpack_trees(1, &tree_desc
, &opts
)) {
469 * We return 0 nevertheless, as the index is all right
470 * and more importantly we have made best efforts to
471 * update paths in the work tree, and we cannot revert
483 const char *name
; /* The short name used */
484 const char *path
; /* The full name of a real branch */
485 struct commit
*commit
; /* The named commit */
487 * if not null the branch is detached because it's already
488 * checked out in this checkout
493 static void setup_branch_path(struct branch_info
*branch
)
495 struct strbuf buf
= STRBUF_INIT
;
497 strbuf_branchname(&buf
, branch
->name
, INTERPRET_BRANCH_LOCAL
);
498 if (strcmp(buf
.buf
, branch
->name
))
499 branch
->name
= xstrdup(buf
.buf
);
500 strbuf_splice(&buf
, 0, 0, "refs/heads/", 11);
501 branch
->path
= strbuf_detach(&buf
, NULL
);
505 * Skip merging the trees, updating the index and working directory if and
506 * only if we are creating a new branch via "git checkout -b <new_branch>."
508 static int skip_merge_working_tree(const struct checkout_opts
*opts
,
509 const struct branch_info
*old_branch_info
,
510 const struct branch_info
*new_branch_info
)
513 * Do the merge if sparse checkout is on and the user has not opted in
514 * to the optimized behavior
516 if (core_apply_sparse_checkout
&& !checkout_optimize_new_branch
)
520 * We must do the merge if we are actually moving to a new commit.
522 if (!old_branch_info
->commit
|| !new_branch_info
->commit
||
523 !oideq(&old_branch_info
->commit
->object
.oid
,
524 &new_branch_info
->commit
->object
.oid
))
528 * opts->patch_mode cannot be used with switching branches so is
533 * opts->quiet only impacts output so doesn't require a merge
537 * Honor the explicit request for a three-way merge or to throw away
540 if (opts
->merge
|| opts
->force
)
544 * --detach is documented as "updating the index and the files in the
545 * working tree" but this optimization skips those steps so fall through
546 * to the regular code path.
548 if (opts
->force_detach
)
552 * opts->writeout_stage cannot be used with switching branches so is
557 * Honor the explicit ignore requests
559 if (!opts
->overwrite_ignore
|| opts
->ignore_skipworktree
||
560 opts
->ignore_other_worktrees
)
564 * opts->show_progress only impacts output so doesn't require a merge
568 * If we aren't creating a new branch any changes or updates will
569 * happen in the existing branch. Since that could only be updating
570 * the index and working directory, we don't want to skip those steps
571 * or we've defeated any purpose in running the command.
573 if (!opts
->new_branch
)
577 * new_branch_force is defined to "create/reset and checkout a branch"
578 * so needs to go through the merge to do the reset
580 if (opts
->new_branch_force
)
584 * A new orphaned branch requrires the index and the working tree to be
585 * adjusted to <start_point>
587 if (opts
->new_orphan_branch
)
591 * Remaining variables are not checkout options but used to track state
597 static int merge_working_tree(const struct checkout_opts
*opts
,
598 struct branch_info
*old_branch_info
,
599 struct branch_info
*new_branch_info
,
603 struct lock_file lock_file
= LOCK_INIT
;
605 hold_locked_index(&lock_file
, LOCK_DIE_ON_ERROR
);
606 if (read_cache_preload(NULL
) < 0)
607 return error(_("index file corrupt"));
609 resolve_undo_clear();
611 ret
= reset_tree(get_commit_tree(new_branch_info
->commit
),
612 opts
, 1, writeout_error
);
616 struct tree_desc trees
[2];
618 struct unpack_trees_options topts
;
620 memset(&topts
, 0, sizeof(topts
));
622 topts
.src_index
= &the_index
;
623 topts
.dst_index
= &the_index
;
625 setup_unpack_trees_porcelain(&topts
, "checkout");
627 refresh_cache(REFRESH_QUIET
);
629 if (unmerged_cache()) {
630 error(_("you need to resolve your current index first"));
634 /* 2-way merge to the new branch */
635 topts
.initial_checkout
= is_cache_unborn();
638 topts
.gently
= opts
->merge
&& old_branch_info
->commit
;
639 topts
.verbose_update
= opts
->show_progress
;
640 topts
.fn
= twoway_merge
;
641 if (opts
->overwrite_ignore
) {
642 topts
.dir
= xcalloc(1, sizeof(*topts
.dir
));
643 topts
.dir
->flags
|= DIR_SHOW_IGNORED
;
644 setup_standard_excludes(topts
.dir
);
646 tree
= parse_tree_indirect(old_branch_info
->commit
?
647 &old_branch_info
->commit
->object
.oid
:
648 the_hash_algo
->empty_tree
);
649 init_tree_desc(&trees
[0], tree
->buffer
, tree
->size
);
650 tree
= parse_tree_indirect(&new_branch_info
->commit
->object
.oid
);
651 init_tree_desc(&trees
[1], tree
->buffer
, tree
->size
);
653 ret
= unpack_trees(2, trees
, &topts
);
654 clear_unpack_trees_porcelain(&topts
);
657 * Unpack couldn't do a trivial merge; either
658 * give up or do a real merge, depending on
659 * whether the merge flag was used.
663 struct merge_options o
;
668 * Without old_branch_info->commit, the below is the same as
669 * the two-tree unpack we already tried and failed.
671 if (!old_branch_info
->commit
)
674 /* Do more real merge */
677 * We update the index fully, then write the
678 * tree from the index, then merge the new
679 * branch with the current tree, with the old
680 * branch as the base. Then we reset the index
681 * (but not the working tree) to the new
682 * branch, leaving the working tree as the
683 * merged version, but skipping unmerged
684 * entries in the index.
687 add_files_to_cache(NULL
, NULL
, 0);
689 * NEEDSWORK: carrying over local changes
690 * when branches have different end-of-line
691 * normalization (or clean+smudge rules) is
692 * a pain; plumb in an option to set
695 init_merge_options(&o
);
697 work
= write_tree_from_memory(&o
);
699 ret
= reset_tree(get_commit_tree(new_branch_info
->commit
),
704 o
.ancestor
= old_branch_info
->name
;
705 o
.branch1
= new_branch_info
->name
;
707 ret
= merge_trees(&o
,
708 get_commit_tree(new_branch_info
->commit
),
710 get_commit_tree(old_branch_info
->commit
),
714 ret
= reset_tree(get_commit_tree(new_branch_info
->commit
),
717 strbuf_release(&o
.obuf
);
723 if (!active_cache_tree
)
724 active_cache_tree
= cache_tree();
726 if (!cache_tree_fully_valid(active_cache_tree
))
727 cache_tree_update(&the_index
, WRITE_TREE_SILENT
| WRITE_TREE_REPAIR
);
729 if (write_locked_index(&the_index
, &lock_file
, COMMIT_LOCK
))
730 die(_("unable to write new index file"));
732 if (!opts
->force
&& !opts
->quiet
)
733 show_local_changes(&new_branch_info
->commit
->object
, &opts
->diff_options
);
738 static void report_tracking(struct branch_info
*new_branch_info
)
740 struct strbuf sb
= STRBUF_INIT
;
741 struct branch
*branch
= branch_get(new_branch_info
->name
);
743 if (!format_tracking_info(branch
, &sb
, AHEAD_BEHIND_FULL
))
745 fputs(sb
.buf
, stdout
);
749 static void update_refs_for_switch(const struct checkout_opts
*opts
,
750 struct branch_info
*old_branch_info
,
751 struct branch_info
*new_branch_info
)
753 struct strbuf msg
= STRBUF_INIT
;
754 const char *old_desc
, *reflog_msg
;
755 if (opts
->new_branch
) {
756 if (opts
->new_orphan_branch
) {
759 refname
= mkpathdup("refs/heads/%s", opts
->new_orphan_branch
);
760 if (opts
->new_branch_log
&&
761 !should_autocreate_reflog(refname
)) {
763 struct strbuf err
= STRBUF_INIT
;
765 ret
= safe_create_reflog(refname
, 1, &err
);
767 fprintf(stderr
, _("Can not do reflog for '%s': %s\n"),
768 opts
->new_orphan_branch
, err
.buf
);
769 strbuf_release(&err
);
773 strbuf_release(&err
);
778 create_branch(opts
->new_branch
, new_branch_info
->name
,
779 opts
->new_branch_force
? 1 : 0,
780 opts
->new_branch_force
? 1 : 0,
781 opts
->new_branch_log
,
784 new_branch_info
->name
= opts
->new_branch
;
785 setup_branch_path(new_branch_info
);
788 old_desc
= old_branch_info
->name
;
789 if (!old_desc
&& old_branch_info
->commit
)
790 old_desc
= oid_to_hex(&old_branch_info
->commit
->object
.oid
);
792 reflog_msg
= getenv("GIT_REFLOG_ACTION");
794 strbuf_addf(&msg
, "checkout: moving from %s to %s",
795 old_desc
? old_desc
: "(invalid)", new_branch_info
->name
);
797 strbuf_insert(&msg
, 0, reflog_msg
, strlen(reflog_msg
));
799 if (!strcmp(new_branch_info
->name
, "HEAD") && !new_branch_info
->path
&& !opts
->force_detach
) {
801 } else if (opts
->force_detach
|| !new_branch_info
->path
) { /* No longer on any branch. */
802 update_ref(msg
.buf
, "HEAD", &new_branch_info
->commit
->object
.oid
, NULL
,
803 REF_NO_DEREF
, UPDATE_REFS_DIE_ON_ERR
);
805 if (old_branch_info
->path
&&
806 advice_detached_head
&& !opts
->force_detach
)
807 detach_advice(new_branch_info
->name
);
808 describe_detached_head(_("HEAD is now at"), new_branch_info
->commit
);
810 } else if (new_branch_info
->path
) { /* Switch branches. */
811 if (create_symref("HEAD", new_branch_info
->path
, msg
.buf
) < 0)
812 die(_("unable to update HEAD"));
814 if (old_branch_info
->path
&& !strcmp(new_branch_info
->path
, old_branch_info
->path
)) {
815 if (opts
->new_branch_force
)
816 fprintf(stderr
, _("Reset branch '%s'\n"),
817 new_branch_info
->name
);
819 fprintf(stderr
, _("Already on '%s'\n"),
820 new_branch_info
->name
);
821 } else if (opts
->new_branch
) {
822 if (opts
->branch_exists
)
823 fprintf(stderr
, _("Switched to and reset branch '%s'\n"), new_branch_info
->name
);
825 fprintf(stderr
, _("Switched to a new branch '%s'\n"), new_branch_info
->name
);
827 fprintf(stderr
, _("Switched to branch '%s'\n"),
828 new_branch_info
->name
);
831 if (old_branch_info
->path
&& old_branch_info
->name
) {
832 if (!ref_exists(old_branch_info
->path
) && reflog_exists(old_branch_info
->path
))
833 delete_reflog(old_branch_info
->path
);
836 remove_branch_state();
837 strbuf_release(&msg
);
839 (new_branch_info
->path
|| (!opts
->force_detach
&& !strcmp(new_branch_info
->name
, "HEAD"))))
840 report_tracking(new_branch_info
);
843 static int add_pending_uninteresting_ref(const char *refname
,
844 const struct object_id
*oid
,
845 int flags
, void *cb_data
)
847 add_pending_oid(cb_data
, refname
, oid
, UNINTERESTING
);
851 static void describe_one_orphan(struct strbuf
*sb
, struct commit
*commit
)
853 strbuf_addstr(sb
, " ");
854 strbuf_add_unique_abbrev(sb
, &commit
->object
.oid
, DEFAULT_ABBREV
);
855 strbuf_addch(sb
, ' ');
856 if (!parse_commit(commit
))
857 pp_commit_easy(CMIT_FMT_ONELINE
, commit
, sb
);
858 strbuf_addch(sb
, '\n');
861 #define ORPHAN_CUTOFF 4
862 static void suggest_reattach(struct commit
*commit
, struct rev_info
*revs
)
864 struct commit
*c
, *last
= NULL
;
865 struct strbuf sb
= STRBUF_INIT
;
867 while ((c
= get_revision(revs
)) != NULL
) {
868 if (lost
< ORPHAN_CUTOFF
)
869 describe_one_orphan(&sb
, c
);
873 if (ORPHAN_CUTOFF
< lost
) {
874 int more
= lost
- ORPHAN_CUTOFF
;
876 describe_one_orphan(&sb
, last
);
878 strbuf_addf(&sb
, _(" ... and %d more.\n"), more
);
883 /* The singular version */
884 "Warning: you are leaving %d commit behind, "
886 "any of your branches:\n\n"
888 /* The plural version */
889 "Warning: you are leaving %d commits behind, "
891 "any of your branches:\n\n"
893 /* Give ngettext() the count */
899 if (advice_detached_head
)
902 /* The singular version */
903 "If you want to keep it by creating a new branch, "
904 "this may be a good time\nto do so with:\n\n"
905 " git branch <new-branch-name> %s\n\n",
906 /* The plural version */
907 "If you want to keep them by creating a new branch, "
908 "this may be a good time\nto do so with:\n\n"
909 " git branch <new-branch-name> %s\n\n",
910 /* Give ngettext() the count */
912 find_unique_abbrev(&commit
->object
.oid
, DEFAULT_ABBREV
));
916 * We are about to leave commit that was at the tip of a detached
917 * HEAD. If it is not reachable from any ref, this is the last chance
918 * for the user to do so without resorting to reflog.
920 static void orphaned_commit_warning(struct commit
*old_commit
, struct commit
*new_commit
)
922 struct rev_info revs
;
923 struct object
*object
= &old_commit
->object
;
925 repo_init_revisions(the_repository
, &revs
, NULL
);
926 setup_revisions(0, NULL
, &revs
, NULL
);
928 object
->flags
&= ~UNINTERESTING
;
929 add_pending_object(&revs
, object
, oid_to_hex(&object
->oid
));
931 for_each_ref(add_pending_uninteresting_ref
, &revs
);
932 add_pending_oid(&revs
, "HEAD", &new_commit
->object
.oid
, UNINTERESTING
);
934 if (prepare_revision_walk(&revs
))
935 die(_("internal error in revision walk"));
936 if (!(old_commit
->object
.flags
& UNINTERESTING
))
937 suggest_reattach(old_commit
, &revs
);
939 describe_detached_head(_("Previous HEAD position was"), old_commit
);
941 /* Clean up objects used, as they will be reused. */
942 clear_commit_marks_all(ALL_REV_FLAGS
);
945 static int switch_branches(const struct checkout_opts
*opts
,
946 struct branch_info
*new_branch_info
)
949 struct branch_info old_branch_info
;
951 struct object_id rev
;
952 int flag
, writeout_error
= 0;
953 memset(&old_branch_info
, 0, sizeof(old_branch_info
));
954 old_branch_info
.path
= path_to_free
= resolve_refdup("HEAD", 0, &rev
, &flag
);
955 if (old_branch_info
.path
)
956 old_branch_info
.commit
= lookup_commit_reference_gently(the_repository
, &rev
, 1);
957 if (!(flag
& REF_ISSYMREF
))
958 old_branch_info
.path
= NULL
;
960 if (old_branch_info
.path
)
961 skip_prefix(old_branch_info
.path
, "refs/heads/", &old_branch_info
.name
);
963 if (!new_branch_info
->name
) {
964 new_branch_info
->name
= "HEAD";
965 new_branch_info
->commit
= old_branch_info
.commit
;
966 if (!new_branch_info
->commit
)
967 die(_("You are on a branch yet to be born"));
968 parse_commit_or_die(new_branch_info
->commit
);
971 /* optimize the "checkout -b <new_branch> path */
972 if (skip_merge_working_tree(opts
, &old_branch_info
, new_branch_info
)) {
973 if (!checkout_optimize_new_branch
&& !opts
->quiet
) {
974 if (read_cache_preload(NULL
) < 0)
975 return error(_("index file corrupt"));
976 show_local_changes(&new_branch_info
->commit
->object
, &opts
->diff_options
);
979 ret
= merge_working_tree(opts
, &old_branch_info
, new_branch_info
, &writeout_error
);
986 if (!opts
->quiet
&& !old_branch_info
.path
&& old_branch_info
.commit
&& new_branch_info
->commit
!= old_branch_info
.commit
)
987 orphaned_commit_warning(old_branch_info
.commit
, new_branch_info
->commit
);
989 update_refs_for_switch(opts
, &old_branch_info
, new_branch_info
);
991 ret
= post_checkout_hook(old_branch_info
.commit
, new_branch_info
->commit
, 1);
993 return ret
|| writeout_error
;
996 static int git_checkout_config(const char *var
, const char *value
, void *cb
)
998 if (!strcmp(var
, "checkout.optimizenewbranch")) {
999 checkout_optimize_new_branch
= git_config_bool(var
, value
);
1003 if (!strcmp(var
, "diff.ignoresubmodules")) {
1004 struct checkout_opts
*opts
= cb
;
1005 handle_ignore_submodules_arg(&opts
->diff_options
, value
);
1009 if (starts_with(var
, "submodule."))
1010 return git_default_submodule_config(var
, value
, NULL
);
1012 return git_xmerge_config(var
, value
, NULL
);
1015 static int parse_branchname_arg(int argc
, const char **argv
,
1016 int dwim_new_local_branch_ok
,
1017 struct branch_info
*new_branch_info
,
1018 struct checkout_opts
*opts
,
1019 struct object_id
*rev
,
1020 int *dwim_remotes_matched
)
1022 struct tree
**source_tree
= &opts
->source_tree
;
1023 const char **new_branch
= &opts
->new_branch
;
1025 struct object_id branch_rev
;
1028 int has_dash_dash
= 0;
1032 * case 1: git checkout <ref> -- [<paths>]
1034 * <ref> must be a valid tree, everything after the '--' must be
1037 * case 2: git checkout -- [<paths>]
1039 * everything after the '--' must be paths.
1041 * case 3: git checkout <something> [--]
1043 * (a) If <something> is a commit, that is to
1044 * switch to the branch or detach HEAD at it. As a special case,
1045 * if <something> is A...B (missing A or B means HEAD but you can
1046 * omit at most one side), and if there is a unique merge base
1047 * between A and B, A...B names that merge base.
1049 * (b) If <something> is _not_ a commit, either "--" is present
1050 * or <something> is not a path, no -t or -b was given, and
1051 * and there is a tracking branch whose name is <something>
1052 * in one and only one remote (or if the branch exists on the
1053 * remote named in checkout.defaultRemote), then this is a
1054 * short-hand to fork local <something> from that
1055 * remote-tracking branch.
1057 * (c) Otherwise, if "--" is present, treat it like case (1).
1060 * - if it's a reference, treat it like case (1)
1061 * - else if it's a path, treat it like case (2)
1064 * case 4: git checkout <something> <paths>
1066 * The first argument must not be ambiguous.
1067 * - If it's *only* a reference, treat it like case (1).
1068 * - If it's only a path, treat it like case (2).
1077 for (i
= 0; i
< argc
; i
++) {
1078 if (!strcmp(argv
[i
], "--")) {
1083 if (dash_dash_pos
== 0)
1084 return 1; /* case (2) */
1085 else if (dash_dash_pos
== 1)
1086 has_dash_dash
= 1; /* case (3) or (1) */
1087 else if (dash_dash_pos
>= 2)
1088 die(_("only one reference expected, %d given."), dash_dash_pos
);
1089 opts
->count_checkout_paths
= !opts
->quiet
&& !has_dash_dash
;
1091 if (!strcmp(arg
, "-"))
1094 if (get_oid_mb(arg
, rev
)) {
1096 * Either case (3) or (4), with <something> not being
1097 * a commit, or an attempt to use case (1) with an
1100 * It's likely an error, but we need to find out if
1101 * we should auto-create the branch, case (3).(b).
1103 int recover_with_dwim
= dwim_new_local_branch_ok
;
1105 if (!has_dash_dash
&&
1106 (check_filename(opts
->prefix
, arg
) || !no_wildcard(arg
)))
1107 recover_with_dwim
= 0;
1109 * Accept "git checkout foo" and "git checkout foo --"
1110 * as candidates for dwim.
1112 if (!(argc
== 1 && !has_dash_dash
) &&
1113 !(argc
== 2 && has_dash_dash
))
1114 recover_with_dwim
= 0;
1116 if (recover_with_dwim
) {
1117 const char *remote
= unique_tracking_name(arg
, rev
,
1118 dwim_remotes_matched
);
1122 /* DWIMmed to create local branch, case (3).(b) */
1124 recover_with_dwim
= 0;
1128 if (!recover_with_dwim
) {
1130 die(_("invalid reference: %s"), arg
);
1135 /* we can't end up being in (2) anymore, eat the argument */
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 new_branch_info
->path
= NULL
; /* not an existing branch */
1149 new_branch_info
->commit
= lookup_commit_reference_gently(the_repository
, rev
, 1);
1150 if (!new_branch_info
->commit
) {
1152 *source_tree
= parse_tree_indirect(rev
);
1154 parse_commit_or_die(new_branch_info
->commit
);
1155 *source_tree
= get_commit_tree(new_branch_info
->commit
);
1158 if (!*source_tree
) /* case (1): want a tree */
1159 die(_("reference is not a tree: %s"), arg
);
1160 if (!has_dash_dash
) { /* case (3).(d) -> (1) */
1162 * Do not complain the most common case
1163 * git checkout branch
1164 * even if there happen to be a file called 'branch';
1165 * it would be extremely annoying.
1168 verify_non_filename(opts
->prefix
, arg
);
1178 static int switch_unborn_to_new_branch(const struct checkout_opts
*opts
)
1181 struct strbuf branch_ref
= STRBUF_INIT
;
1183 if (!opts
->new_branch
)
1184 die(_("You are on a branch yet to be born"));
1185 strbuf_addf(&branch_ref
, "refs/heads/%s", opts
->new_branch
);
1186 status
= create_symref("HEAD", branch_ref
.buf
, "checkout -b");
1187 strbuf_release(&branch_ref
);
1189 fprintf(stderr
, _("Switched to a new branch '%s'\n"),
1194 static int checkout_branch(struct checkout_opts
*opts
,
1195 struct branch_info
*new_branch_info
)
1197 if (opts
->pathspec
.nr
)
1198 die(_("paths cannot be used with switching branches"));
1200 if (opts
->patch_mode
)
1201 die(_("'%s' cannot be used with switching branches"),
1204 if (opts
->writeout_stage
)
1205 die(_("'%s' cannot be used with switching branches"),
1208 if (opts
->force
&& opts
->merge
)
1209 die(_("'%s' cannot be used with '%s'"), "-f", "-m");
1211 if (opts
->force_detach
&& opts
->new_branch
)
1212 die(_("'%s' cannot be used with '%s'"),
1213 "--detach", "-b/-B/--orphan");
1215 if (opts
->new_orphan_branch
) {
1216 if (opts
->track
!= BRANCH_TRACK_UNSPECIFIED
)
1217 die(_("'%s' cannot be used with '%s'"), "--orphan", "-t");
1218 } else if (opts
->force_detach
) {
1219 if (opts
->track
!= BRANCH_TRACK_UNSPECIFIED
)
1220 die(_("'%s' cannot be used with '%s'"), "--detach", "-t");
1221 } else if (opts
->track
== BRANCH_TRACK_UNSPECIFIED
)
1222 opts
->track
= git_branch_track
;
1224 if (new_branch_info
->name
&& !new_branch_info
->commit
)
1225 die(_("Cannot switch branch to a non-commit '%s'"),
1226 new_branch_info
->name
);
1228 if (new_branch_info
->path
&& !opts
->force_detach
&& !opts
->new_branch
&&
1229 !opts
->ignore_other_worktrees
) {
1231 char *head_ref
= resolve_refdup("HEAD", 0, NULL
, &flag
);
1233 (!(flag
& REF_ISSYMREF
) || strcmp(head_ref
, new_branch_info
->path
)))
1234 die_if_checked_out(new_branch_info
->path
, 1);
1238 if (!new_branch_info
->commit
&& opts
->new_branch
) {
1239 struct object_id rev
;
1242 if (!read_ref_full("HEAD", 0, &rev
, &flag
) &&
1243 (flag
& REF_ISSYMREF
) && is_null_oid(&rev
))
1244 return switch_unborn_to_new_branch(opts
);
1246 return switch_branches(opts
, new_branch_info
);
1249 int cmd_checkout(int argc
, const char **argv
, const char *prefix
)
1251 struct checkout_opts opts
;
1252 struct branch_info new_branch_info
;
1253 char *conflict_style
= NULL
;
1254 int dwim_new_local_branch
= 1;
1255 int dwim_remotes_matched
= 0;
1256 struct option options
[] = {
1257 OPT__QUIET(&opts
.quiet
, N_("suppress progress reporting")),
1258 OPT_STRING('b', NULL
, &opts
.new_branch
, N_("branch"),
1259 N_("create and checkout a new branch")),
1260 OPT_STRING('B', NULL
, &opts
.new_branch_force
, N_("branch"),
1261 N_("create/reset and checkout a branch")),
1262 OPT_BOOL('l', NULL
, &opts
.new_branch_log
, N_("create reflog for new branch")),
1263 OPT_BOOL(0, "detach", &opts
.force_detach
, N_("detach HEAD at named commit")),
1264 OPT_SET_INT('t', "track", &opts
.track
, N_("set upstream info for new branch"),
1265 BRANCH_TRACK_EXPLICIT
),
1266 OPT_STRING(0, "orphan", &opts
.new_orphan_branch
, N_("new-branch"), N_("new unparented branch")),
1267 OPT_SET_INT_F('2', "ours", &opts
.writeout_stage
,
1268 N_("checkout our version for unmerged files"),
1269 2, PARSE_OPT_NONEG
),
1270 OPT_SET_INT_F('3', "theirs", &opts
.writeout_stage
,
1271 N_("checkout their version for unmerged files"),
1272 3, PARSE_OPT_NONEG
),
1273 OPT__FORCE(&opts
.force
, N_("force checkout (throw away local modifications)"),
1274 PARSE_OPT_NOCOMPLETE
),
1275 OPT_BOOL('m', "merge", &opts
.merge
, N_("perform a 3-way merge with the new branch")),
1276 OPT_BOOL_F(0, "overwrite-ignore", &opts
.overwrite_ignore
,
1277 N_("update ignored files (default)"),
1278 PARSE_OPT_NOCOMPLETE
),
1279 OPT_STRING(0, "conflict", &conflict_style
, N_("style"),
1280 N_("conflict style (merge or diff3)")),
1281 OPT_BOOL('p', "patch", &opts
.patch_mode
, N_("select hunks interactively")),
1282 OPT_BOOL(0, "ignore-skip-worktree-bits", &opts
.ignore_skipworktree
,
1283 N_("do not limit pathspecs to sparse entries only")),
1284 OPT_HIDDEN_BOOL(0, "guess", &dwim_new_local_branch
,
1285 N_("second guess 'git checkout <no-such-branch>'")),
1286 OPT_BOOL(0, "ignore-other-worktrees", &opts
.ignore_other_worktrees
,
1287 N_("do not check if another worktree is holding the given ref")),
1288 { OPTION_CALLBACK
, 0, "recurse-submodules", NULL
,
1289 "checkout", "control recursive updating of submodules",
1290 PARSE_OPT_OPTARG
, option_parse_recurse_submodules_worktree_updater
},
1291 OPT_BOOL(0, "progress", &opts
.show_progress
, N_("force progress reporting")),
1295 memset(&opts
, 0, sizeof(opts
));
1296 memset(&new_branch_info
, 0, sizeof(new_branch_info
));
1297 opts
.overwrite_ignore
= 1;
1298 opts
.prefix
= prefix
;
1299 opts
.show_progress
= -1;
1301 git_config(git_checkout_config
, &opts
);
1303 opts
.track
= BRANCH_TRACK_UNSPECIFIED
;
1305 argc
= parse_options(argc
, argv
, prefix
, options
, checkout_usage
,
1306 PARSE_OPT_KEEP_DASHDASH
);
1308 if (opts
.show_progress
< 0) {
1310 opts
.show_progress
= 0;
1312 opts
.show_progress
= isatty(2);
1315 if (conflict_style
) {
1316 opts
.merge
= 1; /* implied */
1317 git_xmerge_config("merge.conflictstyle", conflict_style
, NULL
);
1320 if ((!!opts
.new_branch
+ !!opts
.new_branch_force
+ !!opts
.new_orphan_branch
) > 1)
1321 die(_("-b, -B and --orphan are mutually exclusive"));
1324 * From here on, new_branch will contain the branch to be checked out,
1325 * and new_branch_force and new_orphan_branch will tell us which one of
1326 * -b/-B/--orphan is being used.
1328 if (opts
.new_branch_force
)
1329 opts
.new_branch
= opts
.new_branch_force
;
1331 if (opts
.new_orphan_branch
)
1332 opts
.new_branch
= opts
.new_orphan_branch
;
1334 /* --track without -b/-B/--orphan should DWIM */
1335 if (opts
.track
!= BRANCH_TRACK_UNSPECIFIED
&& !opts
.new_branch
) {
1336 const char *argv0
= argv
[0];
1337 if (!argc
|| !strcmp(argv0
, "--"))
1338 die(_("--track needs a branch name"));
1339 skip_prefix(argv0
, "refs/", &argv0
);
1340 skip_prefix(argv0
, "remotes/", &argv0
);
1341 argv0
= strchr(argv0
, '/');
1342 if (!argv0
|| !argv0
[1])
1343 die(_("missing branch name; try -b"));
1344 opts
.new_branch
= argv0
+ 1;
1348 * Extract branch name from command line arguments, so
1349 * all that is left is pathspecs.
1353 * 1) git checkout <tree> -- [<paths>]
1354 * 2) git checkout -- [<paths>]
1355 * 3) git checkout <something> [<paths>]
1357 * including "last branch" syntax and DWIM-ery for names of
1358 * remote branches, erroring out for invalid or ambiguous cases.
1361 struct object_id rev
;
1364 dwim_new_local_branch
&&
1365 opts
.track
== BRANCH_TRACK_UNSPECIFIED
&&
1367 int n
= parse_branchname_arg(argc
, argv
, dwim_ok
,
1368 &new_branch_info
, &opts
, &rev
,
1369 &dwim_remotes_matched
);
1375 parse_pathspec(&opts
.pathspec
, 0,
1376 opts
.patch_mode
? PATHSPEC_PREFIX_ORIGIN
: 0,
1379 if (!opts
.pathspec
.nr
)
1380 die(_("invalid path specification"));
1383 * Try to give more helpful suggestion.
1384 * new_branch && argc > 1 will be caught later.
1386 if (opts
.new_branch
&& argc
== 1)
1387 die(_("'%s' is not a commit and a branch '%s' cannot be created from it"),
1388 argv
[0], opts
.new_branch
);
1390 if (opts
.force_detach
)
1391 die(_("git checkout: --detach does not take a path argument '%s'"),
1394 if (1 < !!opts
.writeout_stage
+ !!opts
.force
+ !!opts
.merge
)
1395 die(_("git checkout: --ours/--theirs, --force and --merge are incompatible when\n"
1396 "checking out of the index."));
1399 if (opts
.new_branch
) {
1400 struct strbuf buf
= STRBUF_INIT
;
1402 if (opts
.new_branch_force
)
1403 opts
.branch_exists
= validate_branchname(opts
.new_branch
, &buf
);
1405 opts
.branch_exists
=
1406 validate_new_branchname(opts
.new_branch
, &buf
, 0);
1407 strbuf_release(&buf
);
1411 if (opts
.patch_mode
|| opts
.pathspec
.nr
) {
1412 int ret
= checkout_paths(&opts
, new_branch_info
.name
);
1413 if (ret
&& dwim_remotes_matched
> 1 &&
1414 advice_checkout_ambiguous_remote_branch_name
)
1415 advise(_("'%s' matched more than one remote tracking branch.\n"
1416 "We found %d remotes with a reference that matched. So we fell back\n"
1417 "on trying to resolve the argument as a path, but failed there too!\n"
1419 "If you meant to check out a remote tracking branch on, e.g. 'origin',\n"
1420 "you can do so by fully qualifying the name with the --track option:\n"
1422 " git checkout --track origin/<name>\n"
1424 "If you'd like to always have checkouts of an ambiguous <name> prefer\n"
1425 "one remote, e.g. the 'origin' remote, consider setting\n"
1426 "checkout.defaultRemote=origin in your config."),
1428 dwim_remotes_matched
);
1431 return checkout_branch(&opts
, &new_branch_info
);