t0410: make test description clearer
[git/gitster.git] / builtin / checkout.c
blobc449558e663a34b5aadfd9d18f3ca36d18432301
1 #define USE_THE_REPOSITORY_VARIABLE
2 #include "builtin.h"
3 #include "advice.h"
4 #include "branch.h"
5 #include "cache-tree.h"
6 #include "checkout.h"
7 #include "commit.h"
8 #include "config.h"
9 #include "diff.h"
10 #include "dir.h"
11 #include "environment.h"
12 #include "gettext.h"
13 #include "hex.h"
14 #include "hook.h"
15 #include "merge-ll.h"
16 #include "lockfile.h"
17 #include "mem-pool.h"
18 #include "merge-recursive.h"
19 #include "object-name.h"
20 #include "object-store-ll.h"
21 #include "parse-options.h"
22 #include "path.h"
23 #include "preload-index.h"
24 #include "read-cache.h"
25 #include "refs.h"
26 #include "remote.h"
27 #include "repo-settings.h"
28 #include "resolve-undo.h"
29 #include "revision.h"
30 #include "setup.h"
31 #include "submodule.h"
32 #include "symlinks.h"
33 #include "trace2.h"
34 #include "tree.h"
35 #include "tree-walk.h"
36 #include "unpack-trees.h"
37 #include "wt-status.h"
38 #include "xdiff-interface.h"
39 #include "entry.h"
40 #include "parallel-checkout.h"
41 #include "add-interactive.h"
43 static const char * const checkout_usage[] = {
44 N_("git checkout [<options>] <branch>"),
45 N_("git checkout [<options>] [<branch>] -- <file>..."),
46 NULL,
49 static const char * const switch_branch_usage[] = {
50 N_("git switch [<options>] [<branch>]"),
51 NULL,
54 static const char * const restore_usage[] = {
55 N_("git restore [<options>] [--source=<branch>] <file>..."),
56 NULL,
59 struct checkout_opts {
60 int patch_mode;
61 int quiet;
62 int merge;
63 int force;
64 int force_detach;
65 int implicit_detach;
66 int writeout_stage;
67 int overwrite_ignore;
68 int ignore_skipworktree;
69 int ignore_other_worktrees;
70 int show_progress;
71 int count_checkout_paths;
72 int overlay_mode;
73 int dwim_new_local_branch;
74 int discard_changes;
75 int accept_ref;
76 int accept_pathspec;
77 int switch_branch_doing_nothing_is_ok;
78 int only_merge_on_switching_branches;
79 int can_switch_when_in_progress;
80 int orphan_from_empty_tree;
81 int empty_pathspec_ok;
82 int checkout_index;
83 int checkout_worktree;
84 const char *ignore_unmerged_opt;
85 int ignore_unmerged;
86 int pathspec_file_nul;
87 char *pathspec_from_file;
89 const char *new_branch;
90 const char *new_branch_force;
91 const char *new_orphan_branch;
92 int new_branch_log;
93 enum branch_track track;
94 struct diff_options diff_options;
95 int conflict_style;
97 int branch_exists;
98 const char *prefix;
99 struct pathspec pathspec;
100 const char *from_treeish;
101 struct tree *source_tree;
104 #define CHECKOUT_OPTS_INIT { .conflict_style = -1, .merge = -1 }
106 struct branch_info {
107 char *name; /* The short name used */
108 char *path; /* The full name of a real branch */
109 struct commit *commit; /* The named commit */
110 char *refname; /* The full name of the ref being checked out. */
111 struct object_id oid; /* The object ID of the commit being checked out. */
113 * if not null the branch is detached because it's already
114 * checked out in this checkout
116 char *checkout;
119 static void branch_info_release(struct branch_info *info)
121 free(info->name);
122 free(info->path);
123 free(info->refname);
124 free(info->checkout);
127 static int post_checkout_hook(struct commit *old_commit, struct commit *new_commit,
128 int changed)
130 return run_hooks_l(the_repository, "post-checkout",
131 oid_to_hex(old_commit ? &old_commit->object.oid : null_oid()),
132 oid_to_hex(new_commit ? &new_commit->object.oid : null_oid()),
133 changed ? "1" : "0", NULL);
134 /* "new_commit" can be NULL when checking out from the index before
135 a commit exists. */
139 static int update_some(const struct object_id *oid, struct strbuf *base,
140 const char *pathname, unsigned mode, void *context UNUSED)
142 int len;
143 struct cache_entry *ce;
144 int pos;
146 if (S_ISDIR(mode))
147 return READ_TREE_RECURSIVE;
149 len = base->len + strlen(pathname);
150 ce = make_empty_cache_entry(the_repository->index, len);
151 oidcpy(&ce->oid, oid);
152 memcpy(ce->name, base->buf, base->len);
153 memcpy(ce->name + base->len, pathname, len - base->len);
154 ce->ce_flags = create_ce_flags(0) | CE_UPDATE;
155 ce->ce_namelen = len;
156 ce->ce_mode = create_ce_mode(mode);
159 * If the entry is the same as the current index, we can leave the old
160 * entry in place. Whether it is UPTODATE or not, checkout_entry will
161 * do the right thing.
163 pos = index_name_pos(the_repository->index, ce->name, ce->ce_namelen);
164 if (pos >= 0) {
165 struct cache_entry *old = the_repository->index->cache[pos];
166 if (ce->ce_mode == old->ce_mode &&
167 !ce_intent_to_add(old) &&
168 oideq(&ce->oid, &old->oid)) {
169 old->ce_flags |= CE_UPDATE;
170 discard_cache_entry(ce);
171 return 0;
175 add_index_entry(the_repository->index, ce,
176 ADD_CACHE_OK_TO_ADD | ADD_CACHE_OK_TO_REPLACE);
177 return 0;
180 static int read_tree_some(struct tree *tree, const struct pathspec *pathspec)
182 read_tree(the_repository, tree,
183 pathspec, update_some, NULL);
185 /* update the index with the given tree's info
186 * for all args, expanding wildcards, and exit
187 * with any non-zero return code.
189 return 0;
192 static int skip_same_name(const struct cache_entry *ce, int pos)
194 while (++pos < the_repository->index->cache_nr &&
195 !strcmp(the_repository->index->cache[pos]->name, ce->name))
196 ; /* skip */
197 return pos;
200 static int check_stage(int stage, const struct cache_entry *ce, int pos,
201 int overlay_mode)
203 while (pos < the_repository->index->cache_nr &&
204 !strcmp(the_repository->index->cache[pos]->name, ce->name)) {
205 if (ce_stage(the_repository->index->cache[pos]) == stage)
206 return 0;
207 pos++;
209 if (!overlay_mode)
210 return 0;
211 if (stage == 2)
212 return error(_("path '%s' does not have our version"), ce->name);
213 else
214 return error(_("path '%s' does not have their version"), ce->name);
217 static int check_stages(unsigned stages, const struct cache_entry *ce, int pos)
219 unsigned seen = 0;
220 const char *name = ce->name;
222 while (pos < the_repository->index->cache_nr) {
223 ce = the_repository->index->cache[pos];
224 if (strcmp(name, ce->name))
225 break;
226 seen |= (1 << ce_stage(ce));
227 pos++;
229 if ((stages & seen) != stages)
230 return error(_("path '%s' does not have all necessary versions"),
231 name);
232 return 0;
235 static int checkout_stage(int stage, const struct cache_entry *ce, int pos,
236 const struct checkout *state, int *nr_checkouts,
237 int overlay_mode)
239 while (pos < the_repository->index->cache_nr &&
240 !strcmp(the_repository->index->cache[pos]->name, ce->name)) {
241 if (ce_stage(the_repository->index->cache[pos]) == stage)
242 return checkout_entry(the_repository->index->cache[pos], state,
243 NULL, nr_checkouts);
244 pos++;
246 if (!overlay_mode) {
247 unlink_entry(ce, NULL);
248 return 0;
250 if (stage == 2)
251 return error(_("path '%s' does not have our version"), ce->name);
252 else
253 return error(_("path '%s' does not have their version"), ce->name);
256 static int checkout_merged(int pos, const struct checkout *state,
257 int *nr_checkouts, struct mem_pool *ce_mem_pool,
258 int conflict_style)
260 struct cache_entry *ce = the_repository->index->cache[pos];
261 const char *path = ce->name;
262 mmfile_t ancestor, ours, theirs;
263 enum ll_merge_result merge_status;
264 int status;
265 struct object_id oid;
266 mmbuffer_t result_buf;
267 struct object_id threeway[3];
268 unsigned mode = 0;
269 struct ll_merge_options ll_opts = LL_MERGE_OPTIONS_INIT;
270 int renormalize = 0;
272 memset(threeway, 0, sizeof(threeway));
273 while (pos < the_repository->index->cache_nr) {
274 int stage;
275 stage = ce_stage(ce);
276 if (!stage || strcmp(path, ce->name))
277 break;
278 oidcpy(&threeway[stage - 1], &ce->oid);
279 if (stage == 2)
280 mode = create_ce_mode(ce->ce_mode);
281 pos++;
282 ce = the_repository->index->cache[pos];
284 if (is_null_oid(&threeway[1]) || is_null_oid(&threeway[2]))
285 return error(_("path '%s' does not have necessary versions"), path);
287 read_mmblob(&ancestor, &threeway[0]);
288 read_mmblob(&ours, &threeway[1]);
289 read_mmblob(&theirs, &threeway[2]);
291 git_config_get_bool("merge.renormalize", &renormalize);
292 ll_opts.renormalize = renormalize;
293 ll_opts.conflict_style = conflict_style;
294 merge_status = ll_merge(&result_buf, path, &ancestor, "base",
295 &ours, "ours", &theirs, "theirs",
296 state->istate, &ll_opts);
297 free(ancestor.ptr);
298 free(ours.ptr);
299 free(theirs.ptr);
300 if (merge_status == LL_MERGE_BINARY_CONFLICT)
301 warning("Cannot merge binary files: %s (%s vs. %s)",
302 path, "ours", "theirs");
303 if (merge_status < 0 || !result_buf.ptr) {
304 free(result_buf.ptr);
305 return error(_("path '%s': cannot merge"), path);
309 * NEEDSWORK:
310 * There is absolutely no reason to write this as a blob object
311 * and create a phony cache entry. This hack is primarily to get
312 * to the write_entry() machinery that massages the contents to
313 * work-tree format and writes out which only allows it for a
314 * cache entry. The code in write_entry() needs to be refactored
315 * to allow us to feed a <buffer, size, mode> instead of a cache
316 * entry. Such a refactoring would help merge_recursive as well
317 * (it also writes the merge result to the object database even
318 * when it may contain conflicts).
320 if (write_object_file(result_buf.ptr, result_buf.size, OBJ_BLOB, &oid))
321 die(_("Unable to add merge result for '%s'"), path);
322 free(result_buf.ptr);
323 ce = make_transient_cache_entry(mode, &oid, path, 2, ce_mem_pool);
324 if (!ce)
325 die(_("make_cache_entry failed for path '%s'"), path);
326 status = checkout_entry(ce, state, NULL, nr_checkouts);
327 return status;
330 static void mark_ce_for_checkout_overlay(struct cache_entry *ce,
331 char *ps_matched,
332 const struct checkout_opts *opts)
334 ce->ce_flags &= ~CE_MATCHED;
335 if (!opts->ignore_skipworktree && ce_skip_worktree(ce))
336 return;
337 if (opts->source_tree && !(ce->ce_flags & CE_UPDATE))
339 * "git checkout tree-ish -- path", but this entry
340 * is in the original index but is not in tree-ish
341 * or does not match the pathspec; it will not be
342 * checked out to the working tree. We will not do
343 * anything to this entry at all.
345 return;
347 * Either this entry came from the tree-ish we are
348 * checking the paths out of, or we are checking out
349 * of the index.
351 * If it comes from the tree-ish, we already know it
352 * matches the pathspec and could just stamp
353 * CE_MATCHED to it from update_some(). But we still
354 * need ps_matched and read_tree (and
355 * eventually tree_entry_interesting) cannot fill
356 * ps_matched yet. Once it can, we can avoid calling
357 * match_pathspec() for _all_ entries when
358 * opts->source_tree != NULL.
360 if (ce_path_match(the_repository->index, ce, &opts->pathspec, ps_matched))
361 ce->ce_flags |= CE_MATCHED;
364 static void mark_ce_for_checkout_no_overlay(struct cache_entry *ce,
365 char *ps_matched,
366 const struct checkout_opts *opts)
368 ce->ce_flags &= ~CE_MATCHED;
369 if (!opts->ignore_skipworktree && ce_skip_worktree(ce))
370 return;
371 if (ce_path_match(the_repository->index, ce, &opts->pathspec, ps_matched)) {
372 ce->ce_flags |= CE_MATCHED;
373 if (opts->source_tree && !(ce->ce_flags & CE_UPDATE))
375 * In overlay mode, but the path is not in
376 * tree-ish, which means we should remove it
377 * from the index and the working tree.
379 ce->ce_flags |= CE_REMOVE | CE_WT_REMOVE;
383 static int checkout_worktree(const struct checkout_opts *opts,
384 const struct branch_info *info)
386 struct checkout state = CHECKOUT_INIT;
387 int nr_checkouts = 0, nr_unmerged = 0;
388 int errs = 0;
389 int pos;
390 int pc_workers, pc_threshold;
391 struct mem_pool ce_mem_pool;
393 state.force = 1;
394 state.refresh_cache = 1;
395 state.istate = the_repository->index;
397 mem_pool_init(&ce_mem_pool, 0);
398 get_parallel_checkout_configs(&pc_workers, &pc_threshold);
399 init_checkout_metadata(&state.meta, info->refname,
400 info->commit ? &info->commit->object.oid : &info->oid,
401 NULL);
403 enable_delayed_checkout(&state);
405 if (pc_workers > 1)
406 init_parallel_checkout();
408 for (pos = 0; pos < the_repository->index->cache_nr; pos++) {
409 struct cache_entry *ce = the_repository->index->cache[pos];
410 if (ce->ce_flags & CE_MATCHED) {
411 if (!ce_stage(ce)) {
412 errs |= checkout_entry(ce, &state,
413 NULL, &nr_checkouts);
414 continue;
416 if (opts->writeout_stage)
417 errs |= checkout_stage(opts->writeout_stage,
418 ce, pos,
419 &state,
420 &nr_checkouts, opts->overlay_mode);
421 else if (opts->merge)
422 errs |= checkout_merged(pos, &state,
423 &nr_unmerged,
424 &ce_mem_pool,
425 opts->conflict_style);
426 pos = skip_same_name(ce, pos) - 1;
429 if (pc_workers > 1)
430 errs |= run_parallel_checkout(&state, pc_workers, pc_threshold,
431 NULL, NULL);
432 mem_pool_discard(&ce_mem_pool, should_validate_cache_entries());
433 remove_marked_cache_entries(the_repository->index, 1);
434 remove_scheduled_dirs();
435 errs |= finish_delayed_checkout(&state, opts->show_progress);
437 if (opts->count_checkout_paths) {
438 if (nr_unmerged)
439 fprintf_ln(stderr, Q_("Recreated %d merge conflict",
440 "Recreated %d merge conflicts",
441 nr_unmerged),
442 nr_unmerged);
443 if (opts->source_tree)
444 fprintf_ln(stderr, Q_("Updated %d path from %s",
445 "Updated %d paths from %s",
446 nr_checkouts),
447 nr_checkouts,
448 repo_find_unique_abbrev(the_repository, &opts->source_tree->object.oid,
449 DEFAULT_ABBREV));
450 else if (!nr_unmerged || nr_checkouts)
451 fprintf_ln(stderr, Q_("Updated %d path from the index",
452 "Updated %d paths from the index",
453 nr_checkouts),
454 nr_checkouts);
457 return errs;
460 static int checkout_paths(const struct checkout_opts *opts,
461 const struct branch_info *new_branch_info)
463 int pos;
464 static char *ps_matched;
465 struct object_id rev;
466 struct commit *head;
467 int errs = 0;
468 struct lock_file lock_file = LOCK_INIT;
469 int checkout_index;
471 trace2_cmd_mode(opts->patch_mode ? "patch" : "path");
473 if (opts->track != BRANCH_TRACK_UNSPECIFIED)
474 die(_("'%s' cannot be used with updating paths"), "--track");
476 if (opts->new_branch_log)
477 die(_("'%s' cannot be used with updating paths"), "-l");
479 if (opts->ignore_unmerged && opts->patch_mode)
480 die(_("'%s' cannot be used with updating paths"),
481 opts->ignore_unmerged_opt);
483 if (opts->force_detach)
484 die(_("'%s' cannot be used with updating paths"), "--detach");
486 if (opts->merge && opts->patch_mode)
487 die(_("options '%s' and '%s' cannot be used together"), "--merge", "--patch");
489 if (opts->ignore_unmerged && opts->merge)
490 die(_("options '%s' and '%s' cannot be used together"),
491 opts->ignore_unmerged_opt, "-m");
493 if (opts->new_branch)
494 die(_("Cannot update paths and switch to branch '%s' at the same time."),
495 opts->new_branch);
497 if (!opts->checkout_worktree && !opts->checkout_index)
498 die(_("neither '%s' or '%s' is specified"),
499 "--staged", "--worktree");
501 if (!opts->checkout_worktree && !opts->from_treeish)
502 die(_("'%s' must be used when '%s' is not specified"),
503 "--worktree", "--source");
506 * Reject --staged option to the restore command when combined with
507 * merge-related options. Use the accept_ref flag to distinguish it
508 * from the checkout command, which does not accept --staged anyway.
510 * `restore --ours|--theirs --worktree --staged` could mean resolving
511 * conflicted paths to one side in both the worktree and the index,
512 * but does not currently.
514 * `restore --merge|--conflict=<style>` already recreates conflicts
515 * in both the worktree and the index, so adding --staged would be
516 * meaningless.
518 if (!opts->accept_ref && opts->checkout_index) {
519 if (opts->writeout_stage)
520 die(_("'%s' or '%s' cannot be used with %s"),
521 "--ours", "--theirs", "--staged");
523 if (opts->merge)
524 die(_("'%s' or '%s' cannot be used with %s"),
525 "--merge", "--conflict", "--staged");
529 * recreating unmerged index entries and writing out data from
530 * unmerged index entries would make no sense when checking out
531 * of a tree-ish.
533 if ((opts->merge || opts->writeout_stage) && opts->source_tree)
534 die(_("'%s', '%s', or '%s' cannot be used when checking out of a tree"),
535 "--merge", "--ours", "--theirs");
537 if (opts->patch_mode) {
538 enum add_p_mode patch_mode;
539 const char *rev = new_branch_info->name;
540 char rev_oid[GIT_MAX_HEXSZ + 1];
543 * Since rev can be in the form of `<a>...<b>` (which is not
544 * recognized by diff-index), we will always replace the name
545 * with the hex of the commit (whether it's in `...` form or
546 * not) for the run_add_interactive() machinery to work
547 * properly. However, there is special logic for the HEAD case
548 * so we mustn't replace that. Also, when we were given a
549 * tree-object, new_branch_info->commit would be NULL, but we
550 * do not have to do any replacement, either.
552 if (rev && new_branch_info->commit && strcmp(rev, "HEAD"))
553 rev = oid_to_hex_r(rev_oid, &new_branch_info->commit->object.oid);
555 if (opts->checkout_index && opts->checkout_worktree)
556 patch_mode = ADD_P_CHECKOUT;
557 else if (opts->checkout_index && !opts->checkout_worktree)
558 patch_mode = ADD_P_RESET;
559 else if (!opts->checkout_index && opts->checkout_worktree)
560 patch_mode = ADD_P_WORKTREE;
561 else
562 BUG("either flag must have been set, worktree=%d, index=%d",
563 opts->checkout_worktree, opts->checkout_index);
564 return !!run_add_p(the_repository, patch_mode, rev,
565 &opts->pathspec);
568 repo_hold_locked_index(the_repository, &lock_file, LOCK_DIE_ON_ERROR);
569 if (repo_read_index_preload(the_repository, &opts->pathspec, 0) < 0)
570 return error(_("index file corrupt"));
572 if (opts->source_tree)
573 read_tree_some(opts->source_tree, &opts->pathspec);
574 if (opts->merge)
575 unmerge_index(the_repository->index, &opts->pathspec, CE_MATCHED);
577 ps_matched = xcalloc(opts->pathspec.nr, 1);
580 * Make sure all pathspecs participated in locating the paths
581 * to be checked out.
583 for (pos = 0; pos < the_repository->index->cache_nr; pos++)
584 if (opts->overlay_mode)
585 mark_ce_for_checkout_overlay(the_repository->index->cache[pos],
586 ps_matched,
587 opts);
588 else
589 mark_ce_for_checkout_no_overlay(the_repository->index->cache[pos],
590 ps_matched,
591 opts);
593 if (report_path_error(ps_matched, &opts->pathspec)) {
594 free(ps_matched);
595 return 1;
597 free(ps_matched);
599 /* Any unmerged paths? */
600 for (pos = 0; pos < the_repository->index->cache_nr; pos++) {
601 const struct cache_entry *ce = the_repository->index->cache[pos];
602 if (ce->ce_flags & CE_MATCHED) {
603 if (!ce_stage(ce))
604 continue;
605 if (opts->ignore_unmerged) {
606 if (!opts->quiet)
607 warning(_("path '%s' is unmerged"), ce->name);
608 } else if (opts->writeout_stage) {
609 errs |= check_stage(opts->writeout_stage, ce, pos, opts->overlay_mode);
610 } else if (opts->merge) {
611 errs |= check_stages((1<<2) | (1<<3), ce, pos);
612 } else {
613 errs = 1;
614 error(_("path '%s' is unmerged"), ce->name);
616 pos = skip_same_name(ce, pos) - 1;
619 if (errs)
620 return 1;
622 /* Now we are committed to check them out */
623 if (opts->checkout_worktree)
624 errs |= checkout_worktree(opts, new_branch_info);
625 else
626 remove_marked_cache_entries(the_repository->index, 1);
629 * Allow updating the index when checking out from the index.
630 * This is to save new stat info.
632 if (opts->checkout_worktree && !opts->checkout_index && !opts->source_tree)
633 checkout_index = 1;
634 else
635 checkout_index = opts->checkout_index;
637 if (checkout_index) {
638 if (write_locked_index(the_repository->index, &lock_file, COMMIT_LOCK))
639 die(_("unable to write new index file"));
640 } else {
642 * NEEDSWORK: if --worktree is not specified, we
643 * should save stat info of checked out files in the
644 * index to avoid the next (potentially costly)
645 * refresh. But it's a bit tricker to do...
647 rollback_lock_file(&lock_file);
650 refs_read_ref_full(get_main_ref_store(the_repository), "HEAD", 0,
651 &rev, NULL);
652 head = lookup_commit_reference_gently(the_repository, &rev, 1);
654 errs |= post_checkout_hook(head, head, 0);
655 return errs;
658 static void show_local_changes(struct object *head,
659 const struct diff_options *opts)
661 struct rev_info rev;
662 /* I think we want full paths, even if we're in a subdirectory. */
663 repo_init_revisions(the_repository, &rev, NULL);
664 rev.diffopt.flags = opts->flags;
665 rev.diffopt.output_format |= DIFF_FORMAT_NAME_STATUS;
666 rev.diffopt.flags.recursive = 1;
667 diff_setup_done(&rev.diffopt);
668 add_pending_object(&rev, head, NULL);
669 run_diff_index(&rev, 0);
670 release_revisions(&rev);
673 static void describe_detached_head(const char *msg, struct commit *commit)
675 struct strbuf sb = STRBUF_INIT;
677 if (!repo_parse_commit(the_repository, commit))
678 pp_commit_easy(CMIT_FMT_ONELINE, commit, &sb);
679 if (print_sha1_ellipsis()) {
680 fprintf(stderr, "%s %s... %s\n", msg,
681 repo_find_unique_abbrev(the_repository, &commit->object.oid, DEFAULT_ABBREV),
682 sb.buf);
683 } else {
684 fprintf(stderr, "%s %s %s\n", msg,
685 repo_find_unique_abbrev(the_repository, &commit->object.oid, DEFAULT_ABBREV),
686 sb.buf);
688 strbuf_release(&sb);
691 static int reset_tree(struct tree *tree, const struct checkout_opts *o,
692 int worktree, int *writeout_error,
693 struct branch_info *info)
695 struct unpack_trees_options opts;
696 struct tree_desc tree_desc;
698 memset(&opts, 0, sizeof(opts));
699 opts.head_idx = -1;
700 opts.update = worktree;
701 opts.skip_unmerged = !worktree;
702 opts.reset = o->force ? UNPACK_RESET_OVERWRITE_UNTRACKED :
703 UNPACK_RESET_PROTECT_UNTRACKED;
704 opts.preserve_ignored = (!o->force && !o->overwrite_ignore);
705 opts.merge = 1;
706 opts.fn = oneway_merge;
707 opts.verbose_update = o->show_progress;
708 opts.src_index = the_repository->index;
709 opts.dst_index = the_repository->index;
710 init_checkout_metadata(&opts.meta, info->refname,
711 info->commit ? &info->commit->object.oid : null_oid(),
712 NULL);
713 if (parse_tree(tree) < 0)
714 return 128;
715 init_tree_desc(&tree_desc, &tree->object.oid, tree->buffer, tree->size);
716 switch (unpack_trees(1, &tree_desc, &opts)) {
717 case -2:
718 *writeout_error = 1;
720 * We return 0 nevertheless, as the index is all right
721 * and more importantly we have made best efforts to
722 * update paths in the work tree, and we cannot revert
723 * them.
725 /* fallthrough */
726 case 0:
727 return 0;
728 default:
729 return 128;
733 static void setup_branch_path(struct branch_info *branch)
735 struct strbuf buf = STRBUF_INIT;
738 * If this is a ref, resolve it; otherwise, look up the OID for our
739 * expression. Failure here is okay.
741 if (!repo_dwim_ref(the_repository, branch->name, strlen(branch->name),
742 &branch->oid, &branch->refname, 0))
743 repo_get_oid_committish(the_repository, branch->name, &branch->oid);
745 strbuf_branchname(&buf, branch->name, INTERPRET_BRANCH_LOCAL);
746 if (strcmp(buf.buf, branch->name)) {
747 free(branch->name);
748 branch->name = xstrdup(buf.buf);
750 strbuf_splice(&buf, 0, 0, "refs/heads/", 11);
751 free(branch->path);
752 branch->path = strbuf_detach(&buf, NULL);
755 static void init_topts(struct unpack_trees_options *topts, int merge,
756 int show_progress, int overwrite_ignore,
757 struct commit *old_commit)
759 memset(topts, 0, sizeof(*topts));
760 topts->head_idx = -1;
761 topts->src_index = the_repository->index;
762 topts->dst_index = the_repository->index;
764 setup_unpack_trees_porcelain(topts, "checkout");
766 topts->initial_checkout = is_index_unborn(the_repository->index);
767 topts->update = 1;
768 topts->merge = 1;
769 topts->quiet = merge && old_commit;
770 topts->verbose_update = show_progress;
771 topts->fn = twoway_merge;
772 topts->preserve_ignored = !overwrite_ignore;
775 static int merge_working_tree(const struct checkout_opts *opts,
776 struct branch_info *old_branch_info,
777 struct branch_info *new_branch_info,
778 int *writeout_error)
780 int ret;
781 struct lock_file lock_file = LOCK_INIT;
782 struct tree *new_tree;
784 repo_hold_locked_index(the_repository, &lock_file, LOCK_DIE_ON_ERROR);
785 if (repo_read_index_preload(the_repository, NULL, 0) < 0)
786 return error(_("index file corrupt"));
788 resolve_undo_clear_index(the_repository->index);
789 if (opts->new_orphan_branch && opts->orphan_from_empty_tree) {
790 if (new_branch_info->commit)
791 BUG("'switch --orphan' should never accept a commit as starting point");
792 new_tree = parse_tree_indirect(the_hash_algo->empty_tree);
793 if (!new_tree)
794 BUG("unable to read empty tree");
795 } else {
796 new_tree = repo_get_commit_tree(the_repository,
797 new_branch_info->commit);
798 if (!new_tree)
799 return error(_("unable to read tree (%s)"),
800 oid_to_hex(&new_branch_info->commit->object.oid));
802 if (opts->discard_changes) {
803 ret = reset_tree(new_tree, opts, 1, writeout_error, new_branch_info);
804 if (ret)
805 return ret;
806 } else {
807 struct tree_desc trees[2];
808 struct tree *tree;
809 struct unpack_trees_options topts;
810 const struct object_id *old_commit_oid;
812 refresh_index(the_repository->index, REFRESH_QUIET, NULL, NULL, NULL);
814 if (unmerged_index(the_repository->index)) {
815 error(_("you need to resolve your current index first"));
816 return 1;
819 /* 2-way merge to the new branch */
820 init_topts(&topts, opts->merge, opts->show_progress,
821 opts->overwrite_ignore, old_branch_info->commit);
822 init_checkout_metadata(&topts.meta, new_branch_info->refname,
823 new_branch_info->commit ?
824 &new_branch_info->commit->object.oid :
825 &new_branch_info->oid, NULL);
827 old_commit_oid = old_branch_info->commit ?
828 &old_branch_info->commit->object.oid :
829 the_hash_algo->empty_tree;
830 tree = parse_tree_indirect(old_commit_oid);
831 if (!tree)
832 die(_("unable to parse commit %s"),
833 oid_to_hex(old_commit_oid));
835 init_tree_desc(&trees[0], &tree->object.oid,
836 tree->buffer, tree->size);
837 if (parse_tree(new_tree) < 0)
838 exit(128);
839 tree = new_tree;
840 init_tree_desc(&trees[1], &tree->object.oid,
841 tree->buffer, tree->size);
843 ret = unpack_trees(2, trees, &topts);
844 clear_unpack_trees_porcelain(&topts);
845 if (ret == -1) {
847 * Unpack couldn't do a trivial merge; either
848 * give up or do a real merge, depending on
849 * whether the merge flag was used.
851 struct tree *work;
852 struct tree *old_tree;
853 struct merge_options o;
854 struct strbuf sb = STRBUF_INIT;
855 struct strbuf old_commit_shortname = STRBUF_INIT;
857 if (!opts->merge)
858 return 1;
861 * Without old_branch_info->commit, the below is the same as
862 * the two-tree unpack we already tried and failed.
864 if (!old_branch_info->commit)
865 return 1;
866 old_tree = repo_get_commit_tree(the_repository,
867 old_branch_info->commit);
869 if (repo_index_has_changes(the_repository, old_tree, &sb))
870 die(_("cannot continue with staged changes in "
871 "the following files:\n%s"), sb.buf);
872 strbuf_release(&sb);
874 /* Do more real merge */
877 * We update the index fully, then write the
878 * tree from the index, then merge the new
879 * branch with the current tree, with the old
880 * branch as the base. Then we reset the index
881 * (but not the working tree) to the new
882 * branch, leaving the working tree as the
883 * merged version, but skipping unmerged
884 * entries in the index.
887 add_files_to_cache(the_repository, NULL, NULL, NULL, 0,
889 init_ui_merge_options(&o, the_repository);
890 o.verbosity = 0;
891 work = write_in_core_index_as_tree(the_repository);
893 ret = reset_tree(new_tree,
894 opts, 1,
895 writeout_error, new_branch_info);
896 if (ret)
897 return ret;
898 o.ancestor = old_branch_info->name;
899 if (!old_branch_info->name) {
900 strbuf_add_unique_abbrev(&old_commit_shortname,
901 &old_branch_info->commit->object.oid,
902 DEFAULT_ABBREV);
903 o.ancestor = old_commit_shortname.buf;
905 o.branch1 = new_branch_info->name;
906 o.branch2 = "local";
907 o.conflict_style = opts->conflict_style;
908 ret = merge_trees(&o,
909 new_tree,
910 work,
911 old_tree);
912 if (ret < 0)
913 exit(128);
914 ret = reset_tree(new_tree,
915 opts, 0,
916 writeout_error, new_branch_info);
917 strbuf_release(&o.obuf);
918 strbuf_release(&old_commit_shortname);
919 if (ret)
920 return ret;
924 if (!cache_tree_fully_valid(the_repository->index->cache_tree))
925 cache_tree_update(the_repository->index, WRITE_TREE_SILENT | WRITE_TREE_REPAIR);
927 if (write_locked_index(the_repository->index, &lock_file, COMMIT_LOCK))
928 die(_("unable to write new index file"));
930 if (!opts->discard_changes && !opts->quiet && new_branch_info->commit)
931 show_local_changes(&new_branch_info->commit->object, &opts->diff_options);
933 return 0;
936 static void report_tracking(struct branch_info *new_branch_info)
938 struct strbuf sb = STRBUF_INIT;
939 struct branch *branch = branch_get(new_branch_info->name);
941 if (!format_tracking_info(branch, &sb, AHEAD_BEHIND_FULL, 1))
942 return;
943 fputs(sb.buf, stdout);
944 strbuf_release(&sb);
947 static void update_refs_for_switch(const struct checkout_opts *opts,
948 struct branch_info *old_branch_info,
949 struct branch_info *new_branch_info)
951 struct strbuf msg = STRBUF_INIT;
952 const char *old_desc, *reflog_msg;
953 if (opts->new_branch) {
954 if (opts->new_orphan_branch) {
955 enum log_refs_config log_all_ref_updates =
956 repo_settings_get_log_all_ref_updates(the_repository);
957 char *refname;
959 refname = mkpathdup("refs/heads/%s", opts->new_orphan_branch);
960 if (opts->new_branch_log &&
961 !should_autocreate_reflog(log_all_ref_updates, refname)) {
962 int ret;
963 struct strbuf err = STRBUF_INIT;
965 ret = refs_create_reflog(get_main_ref_store(the_repository),
966 refname, &err);
967 if (ret) {
968 fprintf(stderr, _("Can not do reflog for '%s': %s\n"),
969 opts->new_orphan_branch, err.buf);
970 strbuf_release(&err);
971 free(refname);
972 return;
974 strbuf_release(&err);
976 free(refname);
978 else
979 create_branch(the_repository,
980 opts->new_branch, new_branch_info->name,
981 opts->new_branch_force ? 1 : 0,
982 opts->new_branch_force ? 1 : 0,
983 opts->new_branch_log,
984 opts->quiet,
985 opts->track,
987 free(new_branch_info->name);
988 free(new_branch_info->refname);
989 new_branch_info->name = xstrdup(opts->new_branch);
990 setup_branch_path(new_branch_info);
993 old_desc = old_branch_info->name;
994 if (!old_desc && old_branch_info->commit)
995 old_desc = oid_to_hex(&old_branch_info->commit->object.oid);
997 reflog_msg = getenv("GIT_REFLOG_ACTION");
998 if (!reflog_msg)
999 strbuf_addf(&msg, "checkout: moving from %s to %s",
1000 old_desc ? old_desc : "(invalid)", new_branch_info->name);
1001 else
1002 strbuf_insertstr(&msg, 0, reflog_msg);
1004 if (!strcmp(new_branch_info->name, "HEAD") && !new_branch_info->path && !opts->force_detach) {
1005 /* Nothing to do. */
1006 } else if (opts->force_detach || !new_branch_info->path) { /* No longer on any branch. */
1007 refs_update_ref(get_main_ref_store(the_repository), msg.buf,
1008 "HEAD", &new_branch_info->commit->object.oid,
1009 NULL,
1010 REF_NO_DEREF, UPDATE_REFS_DIE_ON_ERR);
1011 if (!opts->quiet) {
1012 if (old_branch_info->path &&
1013 advice_enabled(ADVICE_DETACHED_HEAD) && !opts->force_detach)
1014 detach_advice(new_branch_info->name);
1015 describe_detached_head(_("HEAD is now at"), new_branch_info->commit);
1017 } else if (new_branch_info->path) { /* Switch branches. */
1018 if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", new_branch_info->path, msg.buf) < 0)
1019 die(_("unable to update HEAD"));
1020 if (!opts->quiet) {
1021 if (old_branch_info->path && !strcmp(new_branch_info->path, old_branch_info->path)) {
1022 if (opts->new_branch_force)
1023 fprintf(stderr, _("Reset branch '%s'\n"),
1024 new_branch_info->name);
1025 else
1026 fprintf(stderr, _("Already on '%s'\n"),
1027 new_branch_info->name);
1028 } else if (opts->new_branch) {
1029 if (opts->branch_exists)
1030 fprintf(stderr, _("Switched to and reset branch '%s'\n"), new_branch_info->name);
1031 else
1032 fprintf(stderr, _("Switched to a new branch '%s'\n"), new_branch_info->name);
1033 } else {
1034 fprintf(stderr, _("Switched to branch '%s'\n"),
1035 new_branch_info->name);
1038 if (old_branch_info->path && old_branch_info->name) {
1039 if (!refs_ref_exists(get_main_ref_store(the_repository), old_branch_info->path) && refs_reflog_exists(get_main_ref_store(the_repository), old_branch_info->path))
1040 refs_delete_reflog(get_main_ref_store(the_repository),
1041 old_branch_info->path);
1044 remove_branch_state(the_repository, !opts->quiet);
1045 strbuf_release(&msg);
1046 if (!opts->quiet &&
1047 !opts->force_detach &&
1048 (new_branch_info->path || !strcmp(new_branch_info->name, "HEAD")))
1049 report_tracking(new_branch_info);
1052 static int add_pending_uninteresting_ref(const char *refname, const char *referent UNUSED,
1053 const struct object_id *oid,
1054 int flags UNUSED, void *cb_data)
1056 add_pending_oid(cb_data, refname, oid, UNINTERESTING);
1057 return 0;
1060 static void describe_one_orphan(struct strbuf *sb, struct commit *commit)
1062 strbuf_addstr(sb, " ");
1063 strbuf_add_unique_abbrev(sb, &commit->object.oid, DEFAULT_ABBREV);
1064 strbuf_addch(sb, ' ');
1065 if (!repo_parse_commit(the_repository, commit))
1066 pp_commit_easy(CMIT_FMT_ONELINE, commit, sb);
1067 strbuf_addch(sb, '\n');
1070 #define ORPHAN_CUTOFF 4
1071 static void suggest_reattach(struct commit *commit, struct rev_info *revs)
1073 struct commit *c, *last = NULL;
1074 struct strbuf sb = STRBUF_INIT;
1075 int lost = 0;
1076 while ((c = get_revision(revs)) != NULL) {
1077 if (lost < ORPHAN_CUTOFF)
1078 describe_one_orphan(&sb, c);
1079 last = c;
1080 lost++;
1082 if (ORPHAN_CUTOFF < lost) {
1083 int more = lost - ORPHAN_CUTOFF;
1084 if (more == 1)
1085 describe_one_orphan(&sb, last);
1086 else
1087 strbuf_addf(&sb, _(" ... and %d more.\n"), more);
1090 fprintf(stderr,
1092 /* The singular version */
1093 "Warning: you are leaving %d commit behind, "
1094 "not connected to\n"
1095 "any of your branches:\n\n"
1096 "%s\n",
1097 /* The plural version */
1098 "Warning: you are leaving %d commits behind, "
1099 "not connected to\n"
1100 "any of your branches:\n\n"
1101 "%s\n",
1102 /* Give ngettext() the count */
1103 lost),
1104 lost,
1105 sb.buf);
1106 strbuf_release(&sb);
1108 if (advice_enabled(ADVICE_DETACHED_HEAD))
1109 fprintf(stderr,
1111 /* The singular version */
1112 "If you want to keep it by creating a new branch, "
1113 "this may be a good time\nto do so with:\n\n"
1114 " git branch <new-branch-name> %s\n\n",
1115 /* The plural version */
1116 "If you want to keep them by creating a new branch, "
1117 "this may be a good time\nto do so with:\n\n"
1118 " git branch <new-branch-name> %s\n\n",
1119 /* Give ngettext() the count */
1120 lost),
1121 repo_find_unique_abbrev(the_repository, &commit->object.oid, DEFAULT_ABBREV));
1125 * We are about to leave commit that was at the tip of a detached
1126 * HEAD. If it is not reachable from any ref, this is the last chance
1127 * for the user to do so without resorting to reflog.
1129 static void orphaned_commit_warning(struct commit *old_commit, struct commit *new_commit)
1131 struct rev_info revs;
1132 struct object *object = &old_commit->object;
1134 repo_init_revisions(the_repository, &revs, NULL);
1135 setup_revisions(0, NULL, &revs, NULL);
1137 object->flags &= ~UNINTERESTING;
1138 add_pending_object(&revs, object, oid_to_hex(&object->oid));
1140 refs_for_each_ref(get_main_ref_store(the_repository),
1141 add_pending_uninteresting_ref, &revs);
1142 if (new_commit)
1143 add_pending_oid(&revs, "HEAD",
1144 &new_commit->object.oid,
1145 UNINTERESTING);
1147 if (prepare_revision_walk(&revs))
1148 die(_("internal error in revision walk"));
1149 if (!(old_commit->object.flags & UNINTERESTING))
1150 suggest_reattach(old_commit, &revs);
1151 else
1152 describe_detached_head(_("Previous HEAD position was"), old_commit);
1154 /* Clean up objects used, as they will be reused. */
1155 repo_clear_commit_marks(the_repository, ALL_REV_FLAGS);
1156 release_revisions(&revs);
1159 static int switch_branches(const struct checkout_opts *opts,
1160 struct branch_info *new_branch_info)
1162 int ret = 0;
1163 struct branch_info old_branch_info = { 0 };
1164 struct object_id rev;
1165 int flag, writeout_error = 0;
1166 int do_merge = 1;
1168 trace2_cmd_mode("branch");
1170 memset(&old_branch_info, 0, sizeof(old_branch_info));
1171 old_branch_info.path = refs_resolve_refdup(get_main_ref_store(the_repository),
1172 "HEAD", 0, &rev, &flag);
1173 if (old_branch_info.path)
1174 old_branch_info.commit = lookup_commit_reference_gently(the_repository, &rev, 1);
1175 if (!(flag & REF_ISSYMREF))
1176 FREE_AND_NULL(old_branch_info.path);
1178 if (old_branch_info.path) {
1179 const char *const prefix = "refs/heads/";
1180 const char *p;
1181 if (skip_prefix(old_branch_info.path, prefix, &p))
1182 old_branch_info.name = xstrdup(p);
1185 if (opts->new_orphan_branch && opts->orphan_from_empty_tree) {
1186 if (new_branch_info->name)
1187 BUG("'switch --orphan' should never accept a commit as starting point");
1188 new_branch_info->commit = NULL;
1189 new_branch_info->name = xstrdup("(empty)");
1190 do_merge = 1;
1193 if (!new_branch_info->name) {
1194 new_branch_info->name = xstrdup("HEAD");
1195 new_branch_info->commit = old_branch_info.commit;
1196 if (!new_branch_info->commit)
1197 die(_("You are on a branch yet to be born"));
1198 parse_commit_or_die(new_branch_info->commit);
1200 if (opts->only_merge_on_switching_branches)
1201 do_merge = 0;
1204 if (do_merge) {
1205 ret = merge_working_tree(opts, &old_branch_info, new_branch_info, &writeout_error);
1206 if (ret) {
1207 branch_info_release(&old_branch_info);
1208 return ret;
1212 if (!opts->quiet && !old_branch_info.path && old_branch_info.commit && new_branch_info->commit != old_branch_info.commit)
1213 orphaned_commit_warning(old_branch_info.commit, new_branch_info->commit);
1215 update_refs_for_switch(opts, &old_branch_info, new_branch_info);
1217 ret = post_checkout_hook(old_branch_info.commit, new_branch_info->commit, 1);
1218 branch_info_release(&old_branch_info);
1220 return ret || writeout_error;
1223 static int git_checkout_config(const char *var, const char *value,
1224 const struct config_context *ctx, void *cb)
1226 struct checkout_opts *opts = cb;
1228 if (!strcmp(var, "diff.ignoresubmodules")) {
1229 if (!value)
1230 return config_error_nonbool(var);
1231 handle_ignore_submodules_arg(&opts->diff_options, value);
1232 return 0;
1234 if (!strcmp(var, "checkout.guess")) {
1235 opts->dwim_new_local_branch = git_config_bool(var, value);
1236 return 0;
1239 if (starts_with(var, "submodule."))
1240 return git_default_submodule_config(var, value, NULL);
1242 return git_xmerge_config(var, value, ctx, NULL);
1245 static void setup_new_branch_info_and_source_tree(
1246 struct branch_info *new_branch_info,
1247 struct checkout_opts *opts,
1248 struct object_id *rev,
1249 const char *arg)
1251 struct tree **source_tree = &opts->source_tree;
1252 struct object_id branch_rev;
1254 /* treat '@' as a shortcut for 'HEAD' */
1255 new_branch_info->name = !strcmp(arg, "@") ? xstrdup("HEAD") :
1256 xstrdup(arg);
1257 setup_branch_path(new_branch_info);
1259 if (!check_refname_format(new_branch_info->path, 0) &&
1260 !refs_read_ref(get_main_ref_store(the_repository), new_branch_info->path, &branch_rev))
1261 oidcpy(rev, &branch_rev);
1262 else
1263 /* not an existing branch */
1264 FREE_AND_NULL(new_branch_info->path);
1266 new_branch_info->commit = lookup_commit_reference_gently(the_repository, rev, 1);
1267 if (!new_branch_info->commit) {
1268 /* not a commit */
1269 *source_tree = parse_tree_indirect(rev);
1270 if (!*source_tree)
1271 die(_("unable to read tree (%s)"), oid_to_hex(rev));
1272 } else {
1273 parse_commit_or_die(new_branch_info->commit);
1274 *source_tree = repo_get_commit_tree(the_repository,
1275 new_branch_info->commit);
1276 if (!*source_tree)
1277 die(_("unable to read tree (%s)"),
1278 oid_to_hex(&new_branch_info->commit->object.oid));
1282 static char *parse_remote_branch(const char *arg,
1283 struct object_id *rev,
1284 int could_be_checkout_paths)
1286 int num_matches = 0;
1287 char *remote = unique_tracking_name(arg, rev, &num_matches);
1289 if (remote && could_be_checkout_paths) {
1290 die(_("'%s' could be both a local file and a tracking branch.\n"
1291 "Please use -- (and optionally --no-guess) to disambiguate"),
1292 arg);
1295 if (!remote && num_matches > 1) {
1296 if (advice_enabled(ADVICE_CHECKOUT_AMBIGUOUS_REMOTE_BRANCH_NAME)) {
1297 advise(_("If you meant to check out a remote tracking branch on, e.g. 'origin',\n"
1298 "you can do so by fully qualifying the name with the --track option:\n"
1299 "\n"
1300 " git checkout --track origin/<name>\n"
1301 "\n"
1302 "If you'd like to always have checkouts of an ambiguous <name> prefer\n"
1303 "one remote, e.g. the 'origin' remote, consider setting\n"
1304 "checkout.defaultRemote=origin in your config."));
1307 die(_("'%s' matched multiple (%d) remote tracking branches"),
1308 arg, num_matches);
1311 return remote;
1314 static int parse_branchname_arg(int argc, const char **argv,
1315 int dwim_new_local_branch_ok,
1316 struct branch_info *new_branch_info,
1317 struct checkout_opts *opts,
1318 struct object_id *rev)
1320 const char **new_branch = &opts->new_branch;
1321 int argcount = 0;
1322 const char *arg;
1323 char *remote = NULL;
1324 int dash_dash_pos;
1325 int has_dash_dash = 0;
1326 int i;
1329 * case 1: git checkout <ref> -- [<paths>]
1331 * <ref> must be a valid tree, everything after the '--' must be
1332 * a path.
1334 * case 2: git checkout -- [<paths>]
1336 * everything after the '--' must be paths.
1338 * case 3: git checkout <something> [--]
1340 * (a) If <something> is a commit, that is to
1341 * switch to the branch or detach HEAD at it. As a special case,
1342 * if <something> is A...B (missing A or B means HEAD but you can
1343 * omit at most one side), and if there is a unique merge base
1344 * between A and B, A...B names that merge base.
1346 * (b) If <something> is _not_ a commit, either "--" is present
1347 * or <something> is not a path, no -t or -b was given,
1348 * and there is a tracking branch whose name is <something>
1349 * in one and only one remote (or if the branch exists on the
1350 * remote named in checkout.defaultRemote), then this is a
1351 * short-hand to fork local <something> from that
1352 * remote-tracking branch.
1354 * (c) Otherwise, if "--" is present, treat it like case (1).
1356 * (d) Otherwise :
1357 * - if it's a reference, treat it like case (1)
1358 * - else if it's a path, treat it like case (2)
1359 * - else: fail.
1361 * case 4: git checkout <something> <paths>
1363 * The first argument must not be ambiguous.
1364 * - If it's *only* a reference, treat it like case (1).
1365 * - If it's only a path, treat it like case (2).
1366 * - else: fail.
1369 if (!argc)
1370 return 0;
1372 if (!opts->accept_pathspec) {
1373 if (argc > 1)
1374 die(_("only one reference expected"));
1375 has_dash_dash = 1; /* helps disambiguate */
1378 arg = argv[0];
1379 dash_dash_pos = -1;
1380 for (i = 0; i < argc; i++) {
1381 if (opts->accept_pathspec && !strcmp(argv[i], "--")) {
1382 dash_dash_pos = i;
1383 break;
1386 if (dash_dash_pos == 0)
1387 return 1; /* case (2) */
1388 else if (dash_dash_pos == 1)
1389 has_dash_dash = 1; /* case (3) or (1) */
1390 else if (dash_dash_pos >= 2)
1391 die(_("only one reference expected, %d given."), dash_dash_pos);
1392 opts->count_checkout_paths = !opts->quiet && !has_dash_dash;
1394 if (!strcmp(arg, "-"))
1395 arg = "@{-1}";
1397 if (repo_get_oid_mb(the_repository, arg, rev)) {
1399 * Either case (3) or (4), with <something> not being
1400 * a commit, or an attempt to use case (1) with an
1401 * invalid ref.
1403 * It's likely an error, but we need to find out if
1404 * we should auto-create the branch, case (3).(b).
1406 int recover_with_dwim = dwim_new_local_branch_ok;
1408 int could_be_checkout_paths = !has_dash_dash &&
1409 check_filename(opts->prefix, arg);
1411 if (!has_dash_dash && !no_wildcard(arg))
1412 recover_with_dwim = 0;
1415 * Accept "git checkout foo", "git checkout foo --"
1416 * and "git switch foo" as candidates for dwim.
1418 if (!(argc == 1 && !has_dash_dash) &&
1419 !(argc == 2 && has_dash_dash) &&
1420 opts->accept_pathspec)
1421 recover_with_dwim = 0;
1423 if (recover_with_dwim) {
1424 remote = parse_remote_branch(arg, rev,
1425 could_be_checkout_paths);
1426 if (remote) {
1427 *new_branch = arg;
1428 arg = remote;
1429 /* DWIMmed to create local branch, case (3).(b) */
1430 } else {
1431 recover_with_dwim = 0;
1435 if (!recover_with_dwim) {
1436 if (has_dash_dash)
1437 die(_("invalid reference: %s"), arg);
1438 return argcount;
1442 /* we can't end up being in (2) anymore, eat the argument */
1443 argcount++;
1444 argv++;
1445 argc--;
1447 setup_new_branch_info_and_source_tree(new_branch_info, opts, rev, arg);
1449 if (!opts->source_tree) /* case (1): want a tree */
1450 die(_("reference is not a tree: %s"), arg);
1452 if (!has_dash_dash) { /* case (3).(d) -> (1) */
1454 * Do not complain the most common case
1455 * git checkout branch
1456 * even if there happen to be a file called 'branch';
1457 * it would be extremely annoying.
1459 if (argc)
1460 verify_non_filename(opts->prefix, arg);
1461 } else if (opts->accept_pathspec) {
1462 argcount++;
1463 argv++;
1464 argc--;
1467 free(remote);
1468 return argcount;
1471 static int switch_unborn_to_new_branch(const struct checkout_opts *opts)
1473 int status;
1474 struct strbuf branch_ref = STRBUF_INIT;
1476 trace2_cmd_mode("unborn");
1478 if (!opts->new_branch)
1479 die(_("You are on a branch yet to be born"));
1480 strbuf_addf(&branch_ref, "refs/heads/%s", opts->new_branch);
1481 status = refs_update_symref(get_main_ref_store(the_repository),
1482 "HEAD", branch_ref.buf, "checkout -b");
1483 strbuf_release(&branch_ref);
1484 if (!opts->quiet)
1485 fprintf(stderr, _("Switched to a new branch '%s'\n"),
1486 opts->new_branch);
1487 return status;
1490 static void die_expecting_a_branch(const struct branch_info *branch_info)
1492 struct object_id oid;
1493 char *to_free;
1494 int code;
1496 if (repo_dwim_ref(the_repository, branch_info->name,
1497 strlen(branch_info->name), &oid, &to_free, 0) == 1) {
1498 const char *ref = to_free;
1500 if (skip_prefix(ref, "refs/tags/", &ref))
1501 code = die_message(_("a branch is expected, got tag '%s'"), ref);
1502 else if (skip_prefix(ref, "refs/remotes/", &ref))
1503 code = die_message(_("a branch is expected, got remote branch '%s'"), ref);
1504 else
1505 code = die_message(_("a branch is expected, got '%s'"), ref);
1507 else if (branch_info->commit)
1508 code = die_message(_("a branch is expected, got commit '%s'"), branch_info->name);
1509 else
1511 * This case should never happen because we already die() on
1512 * non-commit, but just in case.
1514 code = die_message(_("a branch is expected, got '%s'"), branch_info->name);
1516 if (advice_enabled(ADVICE_SUGGEST_DETACHING_HEAD))
1517 advise(_("If you want to detach HEAD at the commit, try again with the --detach option."));
1519 exit(code);
1522 static void die_if_some_operation_in_progress(void)
1524 struct wt_status_state state;
1526 memset(&state, 0, sizeof(state));
1527 wt_status_get_state(the_repository, &state, 0);
1529 if (state.merge_in_progress)
1530 die(_("cannot switch branch while merging\n"
1531 "Consider \"git merge --quit\" "
1532 "or \"git worktree add\"."));
1533 if (state.am_in_progress)
1534 die(_("cannot switch branch in the middle of an am session\n"
1535 "Consider \"git am --quit\" "
1536 "or \"git worktree add\"."));
1537 if (state.rebase_interactive_in_progress || state.rebase_in_progress)
1538 die(_("cannot switch branch while rebasing\n"
1539 "Consider \"git rebase --quit\" "
1540 "or \"git worktree add\"."));
1541 if (state.cherry_pick_in_progress)
1542 die(_("cannot switch branch while cherry-picking\n"
1543 "Consider \"git cherry-pick --quit\" "
1544 "or \"git worktree add\"."));
1545 if (state.revert_in_progress)
1546 die(_("cannot switch branch while reverting\n"
1547 "Consider \"git revert --quit\" "
1548 "or \"git worktree add\"."));
1549 if (state.bisect_in_progress)
1550 warning(_("you are switching branch while bisecting"));
1552 wt_status_state_free_buffers(&state);
1556 * die if attempting to checkout an existing branch that is in use
1557 * in another worktree, unless ignore-other-wortrees option is given.
1558 * The check is bypassed when the branch is already the current one,
1559 * as it will not make things any worse.
1561 static void die_if_switching_to_a_branch_in_use(struct checkout_opts *opts,
1562 const char *full_ref)
1564 int flags;
1565 char *head_ref;
1567 if (opts->ignore_other_worktrees)
1568 return;
1569 head_ref = refs_resolve_refdup(get_main_ref_store(the_repository),
1570 "HEAD", 0, NULL, &flags);
1571 if (head_ref && (!(flags & REF_ISSYMREF) || strcmp(head_ref, full_ref)))
1572 die_if_checked_out(full_ref, 1);
1573 free(head_ref);
1576 static int checkout_branch(struct checkout_opts *opts,
1577 struct branch_info *new_branch_info)
1579 int noop_switch = (!new_branch_info->name &&
1580 !opts->new_branch &&
1581 !opts->force_detach);
1583 if (opts->pathspec.nr)
1584 die(_("paths cannot be used with switching branches"));
1586 if (opts->patch_mode)
1587 die(_("'%s' cannot be used with switching branches"),
1588 "--patch");
1590 if (opts->overlay_mode != -1)
1591 die(_("'%s' cannot be used with switching branches"),
1592 "--[no]-overlay");
1594 if (opts->writeout_stage) {
1595 const char *msg;
1596 if (noop_switch)
1597 msg = _("'%s' needs the paths to check out");
1598 else
1599 msg = _("'%s' cannot be used with switching branches");
1600 die(msg, "--ours/--theirs");
1603 if (opts->force && opts->merge)
1604 die(_("'%s' cannot be used with '%s'"), "-f", "-m");
1606 if (opts->discard_changes && opts->merge)
1607 die(_("'%s' cannot be used with '%s'"), "--discard-changes", "--merge");
1609 if (opts->force_detach && opts->new_branch)
1610 die(_("'%s' cannot be used with '%s'"),
1611 "--detach", "-b/-B/--orphan");
1613 if (opts->new_orphan_branch) {
1614 if (opts->track != BRANCH_TRACK_UNSPECIFIED)
1615 die(_("'%s' cannot be used with '%s'"), "--orphan", "-t");
1616 if (opts->orphan_from_empty_tree && new_branch_info->name)
1617 die(_("'%s' cannot take <start-point>"), "--orphan");
1618 } else if (opts->force_detach) {
1619 if (opts->track != BRANCH_TRACK_UNSPECIFIED)
1620 die(_("'%s' cannot be used with '%s'"), "--detach", "-t");
1621 } else if (opts->track == BRANCH_TRACK_UNSPECIFIED)
1622 opts->track = git_branch_track;
1624 if (new_branch_info->name && !new_branch_info->commit)
1625 die(_("Cannot switch branch to a non-commit '%s'"),
1626 new_branch_info->name);
1628 if (noop_switch &&
1629 !opts->switch_branch_doing_nothing_is_ok)
1630 die(_("missing branch or commit argument"));
1632 if (!opts->implicit_detach &&
1633 !opts->force_detach &&
1634 !opts->new_branch &&
1635 !opts->new_branch_force &&
1636 new_branch_info->name &&
1637 !new_branch_info->path)
1638 die_expecting_a_branch(new_branch_info);
1640 if (!opts->can_switch_when_in_progress)
1641 die_if_some_operation_in_progress();
1643 /* "git checkout <branch>" */
1644 if (new_branch_info->path && !opts->force_detach && !opts->new_branch)
1645 die_if_switching_to_a_branch_in_use(opts, new_branch_info->path);
1647 /* "git checkout -B <branch>" */
1648 if (opts->new_branch_force) {
1649 char *full_ref = xstrfmt("refs/heads/%s", opts->new_branch);
1650 die_if_switching_to_a_branch_in_use(opts, full_ref);
1651 free(full_ref);
1654 if (!new_branch_info->commit && opts->new_branch) {
1655 struct object_id rev;
1656 int flag;
1658 if (!refs_read_ref_full(get_main_ref_store(the_repository), "HEAD", 0, &rev, &flag) &&
1659 (flag & REF_ISSYMREF) && is_null_oid(&rev))
1660 return switch_unborn_to_new_branch(opts);
1662 return switch_branches(opts, new_branch_info);
1665 static int parse_opt_conflict(const struct option *o, const char *arg, int unset)
1667 struct checkout_opts *opts = o->value;
1669 if (unset) {
1670 opts->conflict_style = -1;
1671 return 0;
1673 opts->conflict_style = parse_conflict_style_name(arg);
1674 if (opts->conflict_style < 0)
1675 return error(_("unknown conflict style '%s'"), arg);
1676 /* --conflict overrides a previous --no-merge */
1677 if (!opts->merge)
1678 opts->merge = -1;
1680 return 0;
1683 static struct option *add_common_options(struct checkout_opts *opts,
1684 struct option *prevopts)
1686 struct option options[] = {
1687 OPT__QUIET(&opts->quiet, N_("suppress progress reporting")),
1688 OPT_CALLBACK_F(0, "recurse-submodules", NULL,
1689 "checkout", "control recursive updating of submodules",
1690 PARSE_OPT_OPTARG, option_parse_recurse_submodules_worktree_updater),
1691 OPT_BOOL(0, "progress", &opts->show_progress, N_("force progress reporting")),
1692 OPT_BOOL('m', "merge", &opts->merge, N_("perform a 3-way merge with the new branch")),
1693 OPT_CALLBACK(0, "conflict", opts, N_("style"),
1694 N_("conflict style (merge, diff3, or zdiff3)"),
1695 parse_opt_conflict),
1696 OPT_END()
1698 struct option *newopts = parse_options_concat(prevopts, options);
1699 free(prevopts);
1700 return newopts;
1703 static struct option *add_common_switch_branch_options(
1704 struct checkout_opts *opts, struct option *prevopts)
1706 struct option options[] = {
1707 OPT_BOOL('d', "detach", &opts->force_detach, N_("detach HEAD at named commit")),
1708 OPT_CALLBACK_F('t', "track", &opts->track, "(direct|inherit)",
1709 N_("set branch tracking configuration"),
1710 PARSE_OPT_OPTARG,
1711 parse_opt_tracking_mode),
1712 OPT__FORCE(&opts->force, N_("force checkout (throw away local modifications)"),
1713 PARSE_OPT_NOCOMPLETE),
1714 OPT_STRING(0, "orphan", &opts->new_orphan_branch, N_("new-branch"), N_("new unborn branch")),
1715 OPT_BOOL_F(0, "overwrite-ignore", &opts->overwrite_ignore,
1716 N_("update ignored files (default)"),
1717 PARSE_OPT_NOCOMPLETE),
1718 OPT_BOOL(0, "ignore-other-worktrees", &opts->ignore_other_worktrees,
1719 N_("do not check if another worktree is using this branch")),
1720 OPT_END()
1722 struct option *newopts = parse_options_concat(prevopts, options);
1723 free(prevopts);
1724 return newopts;
1727 static struct option *add_checkout_path_options(struct checkout_opts *opts,
1728 struct option *prevopts)
1730 struct option options[] = {
1731 OPT_SET_INT_F('2', "ours", &opts->writeout_stage,
1732 N_("checkout our version for unmerged files"),
1733 2, PARSE_OPT_NONEG),
1734 OPT_SET_INT_F('3', "theirs", &opts->writeout_stage,
1735 N_("checkout their version for unmerged files"),
1736 3, PARSE_OPT_NONEG),
1737 OPT_BOOL('p', "patch", &opts->patch_mode, N_("select hunks interactively")),
1738 OPT_BOOL(0, "ignore-skip-worktree-bits", &opts->ignore_skipworktree,
1739 N_("do not limit pathspecs to sparse entries only")),
1740 OPT_PATHSPEC_FROM_FILE(&opts->pathspec_from_file),
1741 OPT_PATHSPEC_FILE_NUL(&opts->pathspec_file_nul),
1742 OPT_END()
1744 struct option *newopts = parse_options_concat(prevopts, options);
1745 free(prevopts);
1746 return newopts;
1749 /* create-branch option (either b or c) */
1750 static char cb_option = 'b';
1752 static int checkout_main(int argc, const char **argv, const char *prefix,
1753 struct checkout_opts *opts, struct option *options,
1754 const char * const usagestr[])
1756 int parseopt_flags = 0;
1757 struct branch_info new_branch_info = { 0 };
1758 int ret;
1760 opts->overwrite_ignore = 1;
1761 opts->prefix = prefix;
1762 opts->show_progress = -1;
1764 git_config(git_checkout_config, opts);
1765 if (the_repository->gitdir) {
1766 prepare_repo_settings(the_repository);
1767 the_repository->settings.command_requires_full_index = 0;
1770 opts->track = BRANCH_TRACK_UNSPECIFIED;
1772 if (!opts->accept_pathspec && !opts->accept_ref)
1773 BUG("make up your mind, you need to take _something_");
1774 if (opts->accept_pathspec && opts->accept_ref)
1775 parseopt_flags = PARSE_OPT_KEEP_DASHDASH;
1777 argc = parse_options(argc, argv, prefix, options,
1778 usagestr, parseopt_flags);
1780 if (opts->show_progress < 0) {
1781 if (opts->quiet)
1782 opts->show_progress = 0;
1783 else
1784 opts->show_progress = isatty(2);
1787 /* --conflicts implies --merge */
1788 if (opts->merge == -1)
1789 opts->merge = opts->conflict_style >= 0;
1791 if (opts->force) {
1792 opts->discard_changes = 1;
1793 opts->ignore_unmerged_opt = "--force";
1794 opts->ignore_unmerged = 1;
1797 if ((!!opts->new_branch + !!opts->new_branch_force + !!opts->new_orphan_branch) > 1)
1798 die(_("options '-%c', '-%c', and '%s' cannot be used together"),
1799 cb_option, toupper(cb_option), "--orphan");
1801 if (opts->overlay_mode == 1 && opts->patch_mode)
1802 die(_("options '%s' and '%s' cannot be used together"), "-p", "--overlay");
1804 if (opts->checkout_index >= 0 || opts->checkout_worktree >= 0) {
1805 if (opts->checkout_index < 0)
1806 opts->checkout_index = 0;
1807 if (opts->checkout_worktree < 0)
1808 opts->checkout_worktree = 0;
1809 } else {
1810 if (opts->checkout_index < 0)
1811 opts->checkout_index = -opts->checkout_index - 1;
1812 if (opts->checkout_worktree < 0)
1813 opts->checkout_worktree = -opts->checkout_worktree - 1;
1815 if (opts->checkout_index < 0 || opts->checkout_worktree < 0)
1816 BUG("these flags should be non-negative by now");
1818 * convenient shortcut: "git restore --staged [--worktree]" equals
1819 * "git restore --staged [--worktree] --source HEAD"
1821 if (!opts->from_treeish && opts->checkout_index)
1822 opts->from_treeish = "HEAD";
1825 * From here on, new_branch will contain the branch to be checked out,
1826 * and new_branch_force and new_orphan_branch will tell us which one of
1827 * -b/-B/-c/-C/--orphan is being used.
1829 if (opts->new_branch_force)
1830 opts->new_branch = opts->new_branch_force;
1832 if (opts->new_orphan_branch)
1833 opts->new_branch = opts->new_orphan_branch;
1835 /* --track without -c/-C/-b/-B/--orphan should DWIM */
1836 if (opts->track != BRANCH_TRACK_UNSPECIFIED && !opts->new_branch) {
1837 const char *argv0 = argv[0];
1838 if (!argc || !strcmp(argv0, "--"))
1839 die(_("--track needs a branch name"));
1840 skip_prefix(argv0, "refs/", &argv0);
1841 skip_prefix(argv0, "remotes/", &argv0);
1842 argv0 = strchr(argv0, '/');
1843 if (!argv0 || !argv0[1])
1844 die(_("missing branch name; try -%c"), cb_option);
1845 opts->new_branch = argv0 + 1;
1849 * Extract branch name from command line arguments, so
1850 * all that is left is pathspecs.
1852 * Handle
1854 * 1) git checkout <tree> -- [<paths>]
1855 * 2) git checkout -- [<paths>]
1856 * 3) git checkout <something> [<paths>]
1858 * including "last branch" syntax and DWIM-ery for names of
1859 * remote branches, erroring out for invalid or ambiguous cases.
1861 if (argc && opts->accept_ref) {
1862 struct object_id rev;
1863 int dwim_ok =
1864 !opts->patch_mode &&
1865 opts->dwim_new_local_branch &&
1866 opts->track == BRANCH_TRACK_UNSPECIFIED &&
1867 !opts->new_branch;
1868 int n = parse_branchname_arg(argc, argv, dwim_ok,
1869 &new_branch_info, opts, &rev);
1870 argv += n;
1871 argc -= n;
1872 } else if (!opts->accept_ref && opts->from_treeish) {
1873 struct object_id rev;
1875 if (repo_get_oid_mb(the_repository, opts->from_treeish, &rev))
1876 die(_("could not resolve %s"), opts->from_treeish);
1878 setup_new_branch_info_and_source_tree(&new_branch_info,
1879 opts, &rev,
1880 opts->from_treeish);
1882 if (!opts->source_tree)
1883 die(_("reference is not a tree: %s"), opts->from_treeish);
1886 if (argc) {
1887 parse_pathspec(&opts->pathspec, 0,
1888 opts->patch_mode ? PATHSPEC_PREFIX_ORIGIN : 0,
1889 prefix, argv);
1891 if (!opts->pathspec.nr)
1892 die(_("invalid path specification"));
1895 * Try to give more helpful suggestion.
1896 * new_branch && argc > 1 will be caught later.
1898 if (opts->new_branch && argc == 1 && !new_branch_info.commit)
1899 die(_("'%s' is not a commit and a branch '%s' cannot be created from it"),
1900 argv[0], opts->new_branch);
1902 if (opts->force_detach)
1903 die(_("git checkout: --detach does not take a path argument '%s'"),
1904 argv[0]);
1907 if (opts->pathspec_from_file) {
1908 if (opts->pathspec.nr)
1909 die(_("'%s' and pathspec arguments cannot be used together"), "--pathspec-from-file");
1911 if (opts->force_detach)
1912 die(_("options '%s' and '%s' cannot be used together"), "--pathspec-from-file", "--detach");
1914 if (opts->patch_mode)
1915 die(_("options '%s' and '%s' cannot be used together"), "--pathspec-from-file", "--patch");
1917 parse_pathspec_file(&opts->pathspec, 0,
1919 prefix, opts->pathspec_from_file, opts->pathspec_file_nul);
1920 } else if (opts->pathspec_file_nul) {
1921 die(_("the option '%s' requires '%s'"), "--pathspec-file-nul", "--pathspec-from-file");
1924 opts->pathspec.recursive = 1;
1926 if (opts->pathspec.nr) {
1927 if (1 < !!opts->writeout_stage + !!opts->force + !!opts->merge)
1928 die(_("git checkout: --ours/--theirs, --force and --merge are incompatible when\n"
1929 "checking out of the index."));
1930 } else {
1931 if (opts->accept_pathspec && !opts->empty_pathspec_ok &&
1932 !opts->patch_mode) /* patch mode is special */
1933 die(_("you must specify path(s) to restore"));
1936 if (opts->new_branch) {
1937 struct strbuf buf = STRBUF_INIT;
1939 if (opts->new_branch_force)
1940 opts->branch_exists = validate_branchname(opts->new_branch, &buf);
1941 else
1942 opts->branch_exists =
1943 validate_new_branchname(opts->new_branch, &buf, 0);
1944 strbuf_release(&buf);
1947 if (opts->patch_mode || opts->pathspec.nr)
1948 ret = checkout_paths(opts, &new_branch_info);
1949 else
1950 ret = checkout_branch(opts, &new_branch_info);
1952 branch_info_release(&new_branch_info);
1953 clear_pathspec(&opts->pathspec);
1954 free(opts->pathspec_from_file);
1955 free(options);
1957 return ret;
1960 int cmd_checkout(int argc,
1961 const char **argv,
1962 const char *prefix,
1963 struct repository *repo UNUSED)
1965 struct checkout_opts opts = CHECKOUT_OPTS_INIT;
1966 struct option *options;
1967 struct option checkout_options[] = {
1968 OPT_STRING('b', NULL, &opts.new_branch, N_("branch"),
1969 N_("create and checkout a new branch")),
1970 OPT_STRING('B', NULL, &opts.new_branch_force, N_("branch"),
1971 N_("create/reset and checkout a branch")),
1972 OPT_BOOL('l', NULL, &opts.new_branch_log, N_("create reflog for new branch")),
1973 OPT_BOOL(0, "guess", &opts.dwim_new_local_branch,
1974 N_("second guess 'git checkout <no-such-branch>' (default)")),
1975 OPT_BOOL(0, "overlay", &opts.overlay_mode, N_("use overlay mode (default)")),
1976 OPT_END()
1979 opts.dwim_new_local_branch = 1;
1980 opts.switch_branch_doing_nothing_is_ok = 1;
1981 opts.only_merge_on_switching_branches = 0;
1982 opts.accept_ref = 1;
1983 opts.accept_pathspec = 1;
1984 opts.implicit_detach = 1;
1985 opts.can_switch_when_in_progress = 1;
1986 opts.orphan_from_empty_tree = 0;
1987 opts.empty_pathspec_ok = 1;
1988 opts.overlay_mode = -1;
1989 opts.checkout_index = -2; /* default on */
1990 opts.checkout_worktree = -2; /* default on */
1992 if (argc == 3 && !strcmp(argv[1], "-b")) {
1994 * User ran 'git checkout -b <branch>' and expects
1995 * the same behavior as 'git switch -c <branch>'.
1997 opts.switch_branch_doing_nothing_is_ok = 0;
1998 opts.only_merge_on_switching_branches = 1;
2001 options = parse_options_dup(checkout_options);
2002 options = add_common_options(&opts, options);
2003 options = add_common_switch_branch_options(&opts, options);
2004 options = add_checkout_path_options(&opts, options);
2006 return checkout_main(argc, argv, prefix, &opts, options,
2007 checkout_usage);
2010 int cmd_switch(int argc,
2011 const char **argv,
2012 const char *prefix,
2013 struct repository *repo UNUSED)
2015 struct checkout_opts opts = CHECKOUT_OPTS_INIT;
2016 struct option *options = NULL;
2017 struct option switch_options[] = {
2018 OPT_STRING('c', "create", &opts.new_branch, N_("branch"),
2019 N_("create and switch to a new branch")),
2020 OPT_STRING('C', "force-create", &opts.new_branch_force, N_("branch"),
2021 N_("create/reset and switch to a branch")),
2022 OPT_BOOL(0, "guess", &opts.dwim_new_local_branch,
2023 N_("second guess 'git switch <no-such-branch>'")),
2024 OPT_BOOL(0, "discard-changes", &opts.discard_changes,
2025 N_("throw away local modifications")),
2026 OPT_END()
2029 opts.dwim_new_local_branch = 1;
2030 opts.accept_ref = 1;
2031 opts.accept_pathspec = 0;
2032 opts.switch_branch_doing_nothing_is_ok = 0;
2033 opts.only_merge_on_switching_branches = 1;
2034 opts.implicit_detach = 0;
2035 opts.can_switch_when_in_progress = 0;
2036 opts.orphan_from_empty_tree = 1;
2037 opts.overlay_mode = -1;
2039 options = parse_options_dup(switch_options);
2040 options = add_common_options(&opts, options);
2041 options = add_common_switch_branch_options(&opts, options);
2043 cb_option = 'c';
2045 return checkout_main(argc, argv, prefix, &opts, options,
2046 switch_branch_usage);
2049 int cmd_restore(int argc,
2050 const char **argv,
2051 const char *prefix,
2052 struct repository *repo UNUSED)
2054 struct checkout_opts opts = CHECKOUT_OPTS_INIT;
2055 struct option *options;
2056 struct option restore_options[] = {
2057 OPT_STRING('s', "source", &opts.from_treeish, "<tree-ish>",
2058 N_("which tree-ish to checkout from")),
2059 OPT_BOOL('S', "staged", &opts.checkout_index,
2060 N_("restore the index")),
2061 OPT_BOOL('W', "worktree", &opts.checkout_worktree,
2062 N_("restore the working tree (default)")),
2063 OPT_BOOL(0, "ignore-unmerged", &opts.ignore_unmerged,
2064 N_("ignore unmerged entries")),
2065 OPT_BOOL(0, "overlay", &opts.overlay_mode, N_("use overlay mode")),
2066 OPT_END()
2069 opts.accept_ref = 0;
2070 opts.accept_pathspec = 1;
2071 opts.empty_pathspec_ok = 0;
2072 opts.overlay_mode = 0;
2073 opts.checkout_index = -1; /* default off */
2074 opts.checkout_worktree = -2; /* default on */
2075 opts.ignore_unmerged_opt = "--ignore-unmerged";
2077 options = parse_options_dup(restore_options);
2078 options = add_common_options(&opts, options);
2079 options = add_checkout_path_options(&opts, options);
2081 return checkout_main(argc, argv, prefix, &opts, options,
2082 restore_usage);