compat/terminal: mark parameter of git_terminal_prompt() UNUSED
[git.git] / builtin / checkout.c
blob3cf44b4683a9ba48abaaa32ef20bc127920865bd
1 #include "builtin.h"
2 #include "advice.h"
3 #include "branch.h"
4 #include "cache-tree.h"
5 #include "checkout.h"
6 #include "commit.h"
7 #include "config.h"
8 #include "diff.h"
9 #include "dir.h"
10 #include "environment.h"
11 #include "gettext.h"
12 #include "hex.h"
13 #include "hook.h"
14 #include "merge-ll.h"
15 #include "lockfile.h"
16 #include "mem-pool.h"
17 #include "merge-recursive.h"
18 #include "object-name.h"
19 #include "object-store-ll.h"
20 #include "parse-options.h"
21 #include "path.h"
22 #include "preload-index.h"
23 #include "read-cache.h"
24 #include "refs.h"
25 #include "remote.h"
26 #include "resolve-undo.h"
27 #include "revision.h"
28 #include "setup.h"
29 #include "submodule.h"
30 #include "symlinks.h"
31 #include "trace2.h"
32 #include "tree.h"
33 #include "tree-walk.h"
34 #include "unpack-trees.h"
35 #include "wt-status.h"
36 #include "xdiff-interface.h"
37 #include "entry.h"
38 #include "parallel-checkout.h"
39 #include "add-interactive.h"
41 static const char * const checkout_usage[] = {
42 N_("git checkout [<options>] <branch>"),
43 N_("git checkout [<options>] [<branch>] -- <file>..."),
44 NULL,
47 static const char * const switch_branch_usage[] = {
48 N_("git switch [<options>] [<branch>]"),
49 NULL,
52 static const char * const restore_usage[] = {
53 N_("git restore [<options>] [--source=<branch>] <file>..."),
54 NULL,
57 struct checkout_opts {
58 int patch_mode;
59 int quiet;
60 int merge;
61 int force;
62 int force_detach;
63 int implicit_detach;
64 int writeout_stage;
65 int overwrite_ignore;
66 int ignore_skipworktree;
67 int ignore_other_worktrees;
68 int show_progress;
69 int count_checkout_paths;
70 int overlay_mode;
71 int dwim_new_local_branch;
72 int discard_changes;
73 int accept_ref;
74 int accept_pathspec;
75 int switch_branch_doing_nothing_is_ok;
76 int only_merge_on_switching_branches;
77 int can_switch_when_in_progress;
78 int orphan_from_empty_tree;
79 int empty_pathspec_ok;
80 int checkout_index;
81 int checkout_worktree;
82 const char *ignore_unmerged_opt;
83 int ignore_unmerged;
84 int pathspec_file_nul;
85 char *pathspec_from_file;
87 const char *new_branch;
88 const char *new_branch_force;
89 const char *new_orphan_branch;
90 int new_branch_log;
91 enum branch_track track;
92 struct diff_options diff_options;
93 int conflict_style;
95 int branch_exists;
96 const char *prefix;
97 struct pathspec pathspec;
98 const char *from_treeish;
99 struct tree *source_tree;
102 #define CHECKOUT_OPTS_INIT { .conflict_style = -1, .merge = -1 }
104 struct branch_info {
105 char *name; /* The short name used */
106 char *path; /* The full name of a real branch */
107 struct commit *commit; /* The named commit */
108 char *refname; /* The full name of the ref being checked out. */
109 struct object_id oid; /* The object ID of the commit being checked out. */
111 * if not null the branch is detached because it's already
112 * checked out in this checkout
114 char *checkout;
117 static void branch_info_release(struct branch_info *info)
119 free(info->name);
120 free(info->path);
121 free(info->refname);
122 free(info->checkout);
125 static int post_checkout_hook(struct commit *old_commit, struct commit *new_commit,
126 int changed)
128 return run_hooks_l("post-checkout",
129 oid_to_hex(old_commit ? &old_commit->object.oid : null_oid()),
130 oid_to_hex(new_commit ? &new_commit->object.oid : null_oid()),
131 changed ? "1" : "0", NULL);
132 /* "new_commit" can be NULL when checking out from the index before
133 a commit exists. */
137 static int update_some(const struct object_id *oid, struct strbuf *base,
138 const char *pathname, unsigned mode, void *context UNUSED)
140 int len;
141 struct cache_entry *ce;
142 int pos;
144 if (S_ISDIR(mode))
145 return READ_TREE_RECURSIVE;
147 len = base->len + strlen(pathname);
148 ce = make_empty_cache_entry(the_repository->index, len);
149 oidcpy(&ce->oid, oid);
150 memcpy(ce->name, base->buf, base->len);
151 memcpy(ce->name + base->len, pathname, len - base->len);
152 ce->ce_flags = create_ce_flags(0) | CE_UPDATE;
153 ce->ce_namelen = len;
154 ce->ce_mode = create_ce_mode(mode);
157 * If the entry is the same as the current index, we can leave the old
158 * entry in place. Whether it is UPTODATE or not, checkout_entry will
159 * do the right thing.
161 pos = index_name_pos(the_repository->index, ce->name, ce->ce_namelen);
162 if (pos >= 0) {
163 struct cache_entry *old = the_repository->index->cache[pos];
164 if (ce->ce_mode == old->ce_mode &&
165 !ce_intent_to_add(old) &&
166 oideq(&ce->oid, &old->oid)) {
167 old->ce_flags |= CE_UPDATE;
168 discard_cache_entry(ce);
169 return 0;
173 add_index_entry(the_repository->index, ce,
174 ADD_CACHE_OK_TO_ADD | ADD_CACHE_OK_TO_REPLACE);
175 return 0;
178 static int read_tree_some(struct tree *tree, const struct pathspec *pathspec)
180 read_tree(the_repository, tree,
181 pathspec, update_some, NULL);
183 /* update the index with the given tree's info
184 * for all args, expanding wildcards, and exit
185 * with any non-zero return code.
187 return 0;
190 static int skip_same_name(const struct cache_entry *ce, int pos)
192 while (++pos < the_repository->index->cache_nr &&
193 !strcmp(the_repository->index->cache[pos]->name, ce->name))
194 ; /* skip */
195 return pos;
198 static int check_stage(int stage, const struct cache_entry *ce, int pos,
199 int overlay_mode)
201 while (pos < the_repository->index->cache_nr &&
202 !strcmp(the_repository->index->cache[pos]->name, ce->name)) {
203 if (ce_stage(the_repository->index->cache[pos]) == stage)
204 return 0;
205 pos++;
207 if (!overlay_mode)
208 return 0;
209 if (stage == 2)
210 return error(_("path '%s' does not have our version"), ce->name);
211 else
212 return error(_("path '%s' does not have their version"), ce->name);
215 static int check_stages(unsigned stages, const struct cache_entry *ce, int pos)
217 unsigned seen = 0;
218 const char *name = ce->name;
220 while (pos < the_repository->index->cache_nr) {
221 ce = the_repository->index->cache[pos];
222 if (strcmp(name, ce->name))
223 break;
224 seen |= (1 << ce_stage(ce));
225 pos++;
227 if ((stages & seen) != stages)
228 return error(_("path '%s' does not have all necessary versions"),
229 name);
230 return 0;
233 static int checkout_stage(int stage, const struct cache_entry *ce, int pos,
234 const struct checkout *state, int *nr_checkouts,
235 int overlay_mode)
237 while (pos < the_repository->index->cache_nr &&
238 !strcmp(the_repository->index->cache[pos]->name, ce->name)) {
239 if (ce_stage(the_repository->index->cache[pos]) == stage)
240 return checkout_entry(the_repository->index->cache[pos], state,
241 NULL, nr_checkouts);
242 pos++;
244 if (!overlay_mode) {
245 unlink_entry(ce, NULL);
246 return 0;
248 if (stage == 2)
249 return error(_("path '%s' does not have our version"), ce->name);
250 else
251 return error(_("path '%s' does not have their version"), ce->name);
254 static int checkout_merged(int pos, const struct checkout *state,
255 int *nr_checkouts, struct mem_pool *ce_mem_pool,
256 int conflict_style)
258 struct cache_entry *ce = the_repository->index->cache[pos];
259 const char *path = ce->name;
260 mmfile_t ancestor, ours, theirs;
261 enum ll_merge_result merge_status;
262 int status;
263 struct object_id oid;
264 mmbuffer_t result_buf;
265 struct object_id threeway[3];
266 unsigned mode = 0;
267 struct ll_merge_options ll_opts = LL_MERGE_OPTIONS_INIT;
268 int renormalize = 0;
270 memset(threeway, 0, sizeof(threeway));
271 while (pos < the_repository->index->cache_nr) {
272 int stage;
273 stage = ce_stage(ce);
274 if (!stage || strcmp(path, ce->name))
275 break;
276 oidcpy(&threeway[stage - 1], &ce->oid);
277 if (stage == 2)
278 mode = create_ce_mode(ce->ce_mode);
279 pos++;
280 ce = the_repository->index->cache[pos];
282 if (is_null_oid(&threeway[1]) || is_null_oid(&threeway[2]))
283 return error(_("path '%s' does not have necessary versions"), path);
285 read_mmblob(&ancestor, &threeway[0]);
286 read_mmblob(&ours, &threeway[1]);
287 read_mmblob(&theirs, &threeway[2]);
289 git_config_get_bool("merge.renormalize", &renormalize);
290 ll_opts.renormalize = renormalize;
291 ll_opts.conflict_style = conflict_style;
292 merge_status = ll_merge(&result_buf, path, &ancestor, "base",
293 &ours, "ours", &theirs, "theirs",
294 state->istate, &ll_opts);
295 free(ancestor.ptr);
296 free(ours.ptr);
297 free(theirs.ptr);
298 if (merge_status == LL_MERGE_BINARY_CONFLICT)
299 warning("Cannot merge binary files: %s (%s vs. %s)",
300 path, "ours", "theirs");
301 if (merge_status < 0 || !result_buf.ptr) {
302 free(result_buf.ptr);
303 return error(_("path '%s': cannot merge"), path);
307 * NEEDSWORK:
308 * There is absolutely no reason to write this as a blob object
309 * and create a phony cache entry. This hack is primarily to get
310 * to the write_entry() machinery that massages the contents to
311 * work-tree format and writes out which only allows it for a
312 * cache entry. The code in write_entry() needs to be refactored
313 * to allow us to feed a <buffer, size, mode> instead of a cache
314 * entry. Such a refactoring would help merge_recursive as well
315 * (it also writes the merge result to the object database even
316 * when it may contain conflicts).
318 if (write_object_file(result_buf.ptr, result_buf.size, OBJ_BLOB, &oid))
319 die(_("Unable to add merge result for '%s'"), path);
320 free(result_buf.ptr);
321 ce = make_transient_cache_entry(mode, &oid, path, 2, ce_mem_pool);
322 if (!ce)
323 die(_("make_cache_entry failed for path '%s'"), path);
324 status = checkout_entry(ce, state, NULL, nr_checkouts);
325 return status;
328 static void mark_ce_for_checkout_overlay(struct cache_entry *ce,
329 char *ps_matched,
330 const struct checkout_opts *opts)
332 ce->ce_flags &= ~CE_MATCHED;
333 if (!opts->ignore_skipworktree && ce_skip_worktree(ce))
334 return;
335 if (opts->source_tree && !(ce->ce_flags & CE_UPDATE))
337 * "git checkout tree-ish -- path", but this entry
338 * is in the original index but is not in tree-ish
339 * or does not match the pathspec; it will not be
340 * checked out to the working tree. We will not do
341 * anything to this entry at all.
343 return;
345 * Either this entry came from the tree-ish we are
346 * checking the paths out of, or we are checking out
347 * of the index.
349 * If it comes from the tree-ish, we already know it
350 * matches the pathspec and could just stamp
351 * CE_MATCHED to it from update_some(). But we still
352 * need ps_matched and read_tree (and
353 * eventually tree_entry_interesting) cannot fill
354 * ps_matched yet. Once it can, we can avoid calling
355 * match_pathspec() for _all_ entries when
356 * opts->source_tree != NULL.
358 if (ce_path_match(the_repository->index, ce, &opts->pathspec, ps_matched))
359 ce->ce_flags |= CE_MATCHED;
362 static void mark_ce_for_checkout_no_overlay(struct cache_entry *ce,
363 char *ps_matched,
364 const struct checkout_opts *opts)
366 ce->ce_flags &= ~CE_MATCHED;
367 if (!opts->ignore_skipworktree && ce_skip_worktree(ce))
368 return;
369 if (ce_path_match(the_repository->index, ce, &opts->pathspec, ps_matched)) {
370 ce->ce_flags |= CE_MATCHED;
371 if (opts->source_tree && !(ce->ce_flags & CE_UPDATE))
373 * In overlay mode, but the path is not in
374 * tree-ish, which means we should remove it
375 * from the index and the working tree.
377 ce->ce_flags |= CE_REMOVE | CE_WT_REMOVE;
381 static int checkout_worktree(const struct checkout_opts *opts,
382 const struct branch_info *info)
384 struct checkout state = CHECKOUT_INIT;
385 int nr_checkouts = 0, nr_unmerged = 0;
386 int errs = 0;
387 int pos;
388 int pc_workers, pc_threshold;
389 struct mem_pool ce_mem_pool;
391 state.force = 1;
392 state.refresh_cache = 1;
393 state.istate = the_repository->index;
395 mem_pool_init(&ce_mem_pool, 0);
396 get_parallel_checkout_configs(&pc_workers, &pc_threshold);
397 init_checkout_metadata(&state.meta, info->refname,
398 info->commit ? &info->commit->object.oid : &info->oid,
399 NULL);
401 enable_delayed_checkout(&state);
403 if (pc_workers > 1)
404 init_parallel_checkout();
406 for (pos = 0; pos < the_repository->index->cache_nr; pos++) {
407 struct cache_entry *ce = the_repository->index->cache[pos];
408 if (ce->ce_flags & CE_MATCHED) {
409 if (!ce_stage(ce)) {
410 errs |= checkout_entry(ce, &state,
411 NULL, &nr_checkouts);
412 continue;
414 if (opts->writeout_stage)
415 errs |= checkout_stage(opts->writeout_stage,
416 ce, pos,
417 &state,
418 &nr_checkouts, opts->overlay_mode);
419 else if (opts->merge)
420 errs |= checkout_merged(pos, &state,
421 &nr_unmerged,
422 &ce_mem_pool,
423 opts->conflict_style);
424 pos = skip_same_name(ce, pos) - 1;
427 if (pc_workers > 1)
428 errs |= run_parallel_checkout(&state, pc_workers, pc_threshold,
429 NULL, NULL);
430 mem_pool_discard(&ce_mem_pool, should_validate_cache_entries());
431 remove_marked_cache_entries(the_repository->index, 1);
432 remove_scheduled_dirs();
433 errs |= finish_delayed_checkout(&state, opts->show_progress);
435 if (opts->count_checkout_paths) {
436 if (nr_unmerged)
437 fprintf_ln(stderr, Q_("Recreated %d merge conflict",
438 "Recreated %d merge conflicts",
439 nr_unmerged),
440 nr_unmerged);
441 if (opts->source_tree)
442 fprintf_ln(stderr, Q_("Updated %d path from %s",
443 "Updated %d paths from %s",
444 nr_checkouts),
445 nr_checkouts,
446 repo_find_unique_abbrev(the_repository, &opts->source_tree->object.oid,
447 DEFAULT_ABBREV));
448 else if (!nr_unmerged || nr_checkouts)
449 fprintf_ln(stderr, Q_("Updated %d path from the index",
450 "Updated %d paths from the index",
451 nr_checkouts),
452 nr_checkouts);
455 return errs;
458 static int checkout_paths(const struct checkout_opts *opts,
459 const struct branch_info *new_branch_info)
461 int pos;
462 static char *ps_matched;
463 struct object_id rev;
464 struct commit *head;
465 int errs = 0;
466 struct lock_file lock_file = LOCK_INIT;
467 int checkout_index;
469 trace2_cmd_mode(opts->patch_mode ? "patch" : "path");
471 if (opts->track != BRANCH_TRACK_UNSPECIFIED)
472 die(_("'%s' cannot be used with updating paths"), "--track");
474 if (opts->new_branch_log)
475 die(_("'%s' cannot be used with updating paths"), "-l");
477 if (opts->ignore_unmerged && opts->patch_mode)
478 die(_("'%s' cannot be used with updating paths"),
479 opts->ignore_unmerged_opt);
481 if (opts->force_detach)
482 die(_("'%s' cannot be used with updating paths"), "--detach");
484 if (opts->merge && opts->patch_mode)
485 die(_("options '%s' and '%s' cannot be used together"), "--merge", "--patch");
487 if (opts->ignore_unmerged && opts->merge)
488 die(_("options '%s' and '%s' cannot be used together"),
489 opts->ignore_unmerged_opt, "-m");
491 if (opts->new_branch)
492 die(_("Cannot update paths and switch to branch '%s' at the same time."),
493 opts->new_branch);
495 if (!opts->checkout_worktree && !opts->checkout_index)
496 die(_("neither '%s' or '%s' is specified"),
497 "--staged", "--worktree");
499 if (!opts->checkout_worktree && !opts->from_treeish)
500 die(_("'%s' must be used when '%s' is not specified"),
501 "--worktree", "--source");
504 * Reject --staged option to the restore command when combined with
505 * merge-related options. Use the accept_ref flag to distinguish it
506 * from the checkout command, which does not accept --staged anyway.
508 * `restore --ours|--theirs --worktree --staged` could mean resolving
509 * conflicted paths to one side in both the worktree and the index,
510 * but does not currently.
512 * `restore --merge|--conflict=<style>` already recreates conflicts
513 * in both the worktree and the index, so adding --staged would be
514 * meaningless.
516 if (!opts->accept_ref && opts->checkout_index) {
517 if (opts->writeout_stage)
518 die(_("'%s' or '%s' cannot be used with %s"),
519 "--ours", "--theirs", "--staged");
521 if (opts->merge)
522 die(_("'%s' or '%s' cannot be used with %s"),
523 "--merge", "--conflict", "--staged");
527 * recreating unmerged index entries and writing out data from
528 * unmerged index entries would make no sense when checking out
529 * of a tree-ish.
531 if ((opts->merge || opts->writeout_stage) && opts->source_tree)
532 die(_("'%s', '%s', or '%s' cannot be used when checking out of a tree"),
533 "--merge", "--ours", "--theirs");
535 if (opts->patch_mode) {
536 enum add_p_mode patch_mode;
537 const char *rev = new_branch_info->name;
538 char rev_oid[GIT_MAX_HEXSZ + 1];
541 * Since rev can be in the form of `<a>...<b>` (which is not
542 * recognized by diff-index), we will always replace the name
543 * with the hex of the commit (whether it's in `...` form or
544 * not) for the run_add_interactive() machinery to work
545 * properly. However, there is special logic for the HEAD case
546 * so we mustn't replace that. Also, when we were given a
547 * tree-object, new_branch_info->commit would be NULL, but we
548 * do not have to do any replacement, either.
550 if (rev && new_branch_info->commit && strcmp(rev, "HEAD"))
551 rev = oid_to_hex_r(rev_oid, &new_branch_info->commit->object.oid);
553 if (opts->checkout_index && opts->checkout_worktree)
554 patch_mode = ADD_P_CHECKOUT;
555 else if (opts->checkout_index && !opts->checkout_worktree)
556 patch_mode = ADD_P_RESET;
557 else if (!opts->checkout_index && opts->checkout_worktree)
558 patch_mode = ADD_P_WORKTREE;
559 else
560 BUG("either flag must have been set, worktree=%d, index=%d",
561 opts->checkout_worktree, opts->checkout_index);
562 return !!run_add_p(the_repository, patch_mode, rev,
563 &opts->pathspec);
566 repo_hold_locked_index(the_repository, &lock_file, LOCK_DIE_ON_ERROR);
567 if (repo_read_index_preload(the_repository, &opts->pathspec, 0) < 0)
568 return error(_("index file corrupt"));
570 if (opts->source_tree)
571 read_tree_some(opts->source_tree, &opts->pathspec);
572 if (opts->merge)
573 unmerge_index(the_repository->index, &opts->pathspec, CE_MATCHED);
575 ps_matched = xcalloc(opts->pathspec.nr, 1);
578 * Make sure all pathspecs participated in locating the paths
579 * to be checked out.
581 for (pos = 0; pos < the_repository->index->cache_nr; pos++)
582 if (opts->overlay_mode)
583 mark_ce_for_checkout_overlay(the_repository->index->cache[pos],
584 ps_matched,
585 opts);
586 else
587 mark_ce_for_checkout_no_overlay(the_repository->index->cache[pos],
588 ps_matched,
589 opts);
591 if (report_path_error(ps_matched, &opts->pathspec)) {
592 free(ps_matched);
593 return 1;
595 free(ps_matched);
597 /* Any unmerged paths? */
598 for (pos = 0; pos < the_repository->index->cache_nr; pos++) {
599 const struct cache_entry *ce = the_repository->index->cache[pos];
600 if (ce->ce_flags & CE_MATCHED) {
601 if (!ce_stage(ce))
602 continue;
603 if (opts->ignore_unmerged) {
604 if (!opts->quiet)
605 warning(_("path '%s' is unmerged"), ce->name);
606 } else if (opts->writeout_stage) {
607 errs |= check_stage(opts->writeout_stage, ce, pos, opts->overlay_mode);
608 } else if (opts->merge) {
609 errs |= check_stages((1<<2) | (1<<3), ce, pos);
610 } else {
611 errs = 1;
612 error(_("path '%s' is unmerged"), ce->name);
614 pos = skip_same_name(ce, pos) - 1;
617 if (errs)
618 return 1;
620 /* Now we are committed to check them out */
621 if (opts->checkout_worktree)
622 errs |= checkout_worktree(opts, new_branch_info);
623 else
624 remove_marked_cache_entries(the_repository->index, 1);
627 * Allow updating the index when checking out from the index.
628 * This is to save new stat info.
630 if (opts->checkout_worktree && !opts->checkout_index && !opts->source_tree)
631 checkout_index = 1;
632 else
633 checkout_index = opts->checkout_index;
635 if (checkout_index) {
636 if (write_locked_index(the_repository->index, &lock_file, COMMIT_LOCK))
637 die(_("unable to write new index file"));
638 } else {
640 * NEEDSWORK: if --worktree is not specified, we
641 * should save stat info of checked out files in the
642 * index to avoid the next (potentially costly)
643 * refresh. But it's a bit tricker to do...
645 rollback_lock_file(&lock_file);
648 refs_read_ref_full(get_main_ref_store(the_repository), "HEAD", 0,
649 &rev, NULL);
650 head = lookup_commit_reference_gently(the_repository, &rev, 1);
652 errs |= post_checkout_hook(head, head, 0);
653 return errs;
656 static void show_local_changes(struct object *head,
657 const struct diff_options *opts)
659 struct rev_info rev;
660 /* I think we want full paths, even if we're in a subdirectory. */
661 repo_init_revisions(the_repository, &rev, NULL);
662 rev.diffopt.flags = opts->flags;
663 rev.diffopt.output_format |= DIFF_FORMAT_NAME_STATUS;
664 rev.diffopt.flags.recursive = 1;
665 diff_setup_done(&rev.diffopt);
666 add_pending_object(&rev, head, NULL);
667 run_diff_index(&rev, 0);
668 release_revisions(&rev);
671 static void describe_detached_head(const char *msg, struct commit *commit)
673 struct strbuf sb = STRBUF_INIT;
675 if (!repo_parse_commit(the_repository, commit))
676 pp_commit_easy(CMIT_FMT_ONELINE, commit, &sb);
677 if (print_sha1_ellipsis()) {
678 fprintf(stderr, "%s %s... %s\n", msg,
679 repo_find_unique_abbrev(the_repository, &commit->object.oid, DEFAULT_ABBREV),
680 sb.buf);
681 } else {
682 fprintf(stderr, "%s %s %s\n", msg,
683 repo_find_unique_abbrev(the_repository, &commit->object.oid, DEFAULT_ABBREV),
684 sb.buf);
686 strbuf_release(&sb);
689 static int reset_tree(struct tree *tree, const struct checkout_opts *o,
690 int worktree, int *writeout_error,
691 struct branch_info *info)
693 struct unpack_trees_options opts;
694 struct tree_desc tree_desc;
696 memset(&opts, 0, sizeof(opts));
697 opts.head_idx = -1;
698 opts.update = worktree;
699 opts.skip_unmerged = !worktree;
700 opts.reset = o->force ? UNPACK_RESET_OVERWRITE_UNTRACKED :
701 UNPACK_RESET_PROTECT_UNTRACKED;
702 opts.preserve_ignored = (!o->force && !o->overwrite_ignore);
703 opts.merge = 1;
704 opts.fn = oneway_merge;
705 opts.verbose_update = o->show_progress;
706 opts.src_index = the_repository->index;
707 opts.dst_index = the_repository->index;
708 init_checkout_metadata(&opts.meta, info->refname,
709 info->commit ? &info->commit->object.oid : null_oid(),
710 NULL);
711 if (parse_tree(tree) < 0)
712 return 128;
713 init_tree_desc(&tree_desc, &tree->object.oid, tree->buffer, tree->size);
714 switch (unpack_trees(1, &tree_desc, &opts)) {
715 case -2:
716 *writeout_error = 1;
718 * We return 0 nevertheless, as the index is all right
719 * and more importantly we have made best efforts to
720 * update paths in the work tree, and we cannot revert
721 * them.
723 /* fallthrough */
724 case 0:
725 return 0;
726 default:
727 return 128;
731 static void setup_branch_path(struct branch_info *branch)
733 struct strbuf buf = STRBUF_INIT;
736 * If this is a ref, resolve it; otherwise, look up the OID for our
737 * expression. Failure here is okay.
739 if (!repo_dwim_ref(the_repository, branch->name, strlen(branch->name),
740 &branch->oid, &branch->refname, 0))
741 repo_get_oid_committish(the_repository, branch->name, &branch->oid);
743 strbuf_branchname(&buf, branch->name, INTERPRET_BRANCH_LOCAL);
744 if (strcmp(buf.buf, branch->name)) {
745 free(branch->name);
746 branch->name = xstrdup(buf.buf);
748 strbuf_splice(&buf, 0, 0, "refs/heads/", 11);
749 free(branch->path);
750 branch->path = strbuf_detach(&buf, NULL);
753 static void init_topts(struct unpack_trees_options *topts, int merge,
754 int show_progress, int overwrite_ignore,
755 struct commit *old_commit)
757 memset(topts, 0, sizeof(*topts));
758 topts->head_idx = -1;
759 topts->src_index = the_repository->index;
760 topts->dst_index = the_repository->index;
762 setup_unpack_trees_porcelain(topts, "checkout");
764 topts->initial_checkout = is_index_unborn(the_repository->index);
765 topts->update = 1;
766 topts->merge = 1;
767 topts->quiet = merge && old_commit;
768 topts->verbose_update = show_progress;
769 topts->fn = twoway_merge;
770 topts->preserve_ignored = !overwrite_ignore;
773 static int merge_working_tree(const struct checkout_opts *opts,
774 struct branch_info *old_branch_info,
775 struct branch_info *new_branch_info,
776 int *writeout_error)
778 int ret;
779 struct lock_file lock_file = LOCK_INIT;
780 struct tree *new_tree;
782 repo_hold_locked_index(the_repository, &lock_file, LOCK_DIE_ON_ERROR);
783 if (repo_read_index_preload(the_repository, NULL, 0) < 0)
784 return error(_("index file corrupt"));
786 resolve_undo_clear_index(the_repository->index);
787 if (opts->new_orphan_branch && opts->orphan_from_empty_tree) {
788 if (new_branch_info->commit)
789 BUG("'switch --orphan' should never accept a commit as starting point");
790 new_tree = parse_tree_indirect(the_hash_algo->empty_tree);
791 if (!new_tree)
792 BUG("unable to read empty tree");
793 } else {
794 new_tree = repo_get_commit_tree(the_repository,
795 new_branch_info->commit);
796 if (!new_tree)
797 return error(_("unable to read tree (%s)"),
798 oid_to_hex(&new_branch_info->commit->object.oid));
800 if (opts->discard_changes) {
801 ret = reset_tree(new_tree, opts, 1, writeout_error, new_branch_info);
802 if (ret)
803 return ret;
804 } else {
805 struct tree_desc trees[2];
806 struct tree *tree;
807 struct unpack_trees_options topts;
808 const struct object_id *old_commit_oid;
810 refresh_index(the_repository->index, REFRESH_QUIET, NULL, NULL, NULL);
812 if (unmerged_index(the_repository->index)) {
813 error(_("you need to resolve your current index first"));
814 return 1;
817 /* 2-way merge to the new branch */
818 init_topts(&topts, opts->merge, opts->show_progress,
819 opts->overwrite_ignore, old_branch_info->commit);
820 init_checkout_metadata(&topts.meta, new_branch_info->refname,
821 new_branch_info->commit ?
822 &new_branch_info->commit->object.oid :
823 &new_branch_info->oid, NULL);
825 old_commit_oid = old_branch_info->commit ?
826 &old_branch_info->commit->object.oid :
827 the_hash_algo->empty_tree;
828 tree = parse_tree_indirect(old_commit_oid);
829 if (!tree)
830 die(_("unable to parse commit %s"),
831 oid_to_hex(old_commit_oid));
833 init_tree_desc(&trees[0], &tree->object.oid,
834 tree->buffer, tree->size);
835 if (parse_tree(new_tree) < 0)
836 exit(128);
837 tree = new_tree;
838 init_tree_desc(&trees[1], &tree->object.oid,
839 tree->buffer, tree->size);
841 ret = unpack_trees(2, trees, &topts);
842 clear_unpack_trees_porcelain(&topts);
843 if (ret == -1) {
845 * Unpack couldn't do a trivial merge; either
846 * give up or do a real merge, depending on
847 * whether the merge flag was used.
849 struct tree *work;
850 struct tree *old_tree;
851 struct merge_options o;
852 struct strbuf sb = STRBUF_INIT;
853 struct strbuf old_commit_shortname = STRBUF_INIT;
855 if (!opts->merge)
856 return 1;
859 * Without old_branch_info->commit, the below is the same as
860 * the two-tree unpack we already tried and failed.
862 if (!old_branch_info->commit)
863 return 1;
864 old_tree = repo_get_commit_tree(the_repository,
865 old_branch_info->commit);
867 if (repo_index_has_changes(the_repository, old_tree, &sb))
868 die(_("cannot continue with staged changes in "
869 "the following files:\n%s"), sb.buf);
870 strbuf_release(&sb);
872 /* Do more real merge */
875 * We update the index fully, then write the
876 * tree from the index, then merge the new
877 * branch with the current tree, with the old
878 * branch as the base. Then we reset the index
879 * (but not the working tree) to the new
880 * branch, leaving the working tree as the
881 * merged version, but skipping unmerged
882 * entries in the index.
885 add_files_to_cache(the_repository, NULL, NULL, NULL, 0,
887 init_merge_options(&o, the_repository);
888 o.verbosity = 0;
889 work = write_in_core_index_as_tree(the_repository);
891 ret = reset_tree(new_tree,
892 opts, 1,
893 writeout_error, new_branch_info);
894 if (ret)
895 return ret;
896 o.ancestor = old_branch_info->name;
897 if (!old_branch_info->name) {
898 strbuf_add_unique_abbrev(&old_commit_shortname,
899 &old_branch_info->commit->object.oid,
900 DEFAULT_ABBREV);
901 o.ancestor = old_commit_shortname.buf;
903 o.branch1 = new_branch_info->name;
904 o.branch2 = "local";
905 o.conflict_style = opts->conflict_style;
906 ret = merge_trees(&o,
907 new_tree,
908 work,
909 old_tree);
910 if (ret < 0)
911 exit(128);
912 ret = reset_tree(new_tree,
913 opts, 0,
914 writeout_error, new_branch_info);
915 strbuf_release(&o.obuf);
916 strbuf_release(&old_commit_shortname);
917 if (ret)
918 return ret;
922 if (!cache_tree_fully_valid(the_repository->index->cache_tree))
923 cache_tree_update(the_repository->index, WRITE_TREE_SILENT | WRITE_TREE_REPAIR);
925 if (write_locked_index(the_repository->index, &lock_file, COMMIT_LOCK))
926 die(_("unable to write new index file"));
928 if (!opts->discard_changes && !opts->quiet && new_branch_info->commit)
929 show_local_changes(&new_branch_info->commit->object, &opts->diff_options);
931 return 0;
934 static void report_tracking(struct branch_info *new_branch_info)
936 struct strbuf sb = STRBUF_INIT;
937 struct branch *branch = branch_get(new_branch_info->name);
939 if (!format_tracking_info(branch, &sb, AHEAD_BEHIND_FULL, 1))
940 return;
941 fputs(sb.buf, stdout);
942 strbuf_release(&sb);
945 static void update_refs_for_switch(const struct checkout_opts *opts,
946 struct branch_info *old_branch_info,
947 struct branch_info *new_branch_info)
949 struct strbuf msg = STRBUF_INIT;
950 const char *old_desc, *reflog_msg;
951 if (opts->new_branch) {
952 if (opts->new_orphan_branch) {
953 char *refname;
955 refname = mkpathdup("refs/heads/%s", opts->new_orphan_branch);
956 if (opts->new_branch_log &&
957 !should_autocreate_reflog(refname)) {
958 int ret;
959 struct strbuf err = STRBUF_INIT;
961 ret = refs_create_reflog(get_main_ref_store(the_repository),
962 refname, &err);
963 if (ret) {
964 fprintf(stderr, _("Can not do reflog for '%s': %s\n"),
965 opts->new_orphan_branch, err.buf);
966 strbuf_release(&err);
967 free(refname);
968 return;
970 strbuf_release(&err);
972 free(refname);
974 else
975 create_branch(the_repository,
976 opts->new_branch, new_branch_info->name,
977 opts->new_branch_force ? 1 : 0,
978 opts->new_branch_force ? 1 : 0,
979 opts->new_branch_log,
980 opts->quiet,
981 opts->track,
983 free(new_branch_info->name);
984 free(new_branch_info->refname);
985 new_branch_info->name = xstrdup(opts->new_branch);
986 setup_branch_path(new_branch_info);
989 old_desc = old_branch_info->name;
990 if (!old_desc && old_branch_info->commit)
991 old_desc = oid_to_hex(&old_branch_info->commit->object.oid);
993 reflog_msg = getenv("GIT_REFLOG_ACTION");
994 if (!reflog_msg)
995 strbuf_addf(&msg, "checkout: moving from %s to %s",
996 old_desc ? old_desc : "(invalid)", new_branch_info->name);
997 else
998 strbuf_insertstr(&msg, 0, reflog_msg);
1000 if (!strcmp(new_branch_info->name, "HEAD") && !new_branch_info->path && !opts->force_detach) {
1001 /* Nothing to do. */
1002 } else if (opts->force_detach || !new_branch_info->path) { /* No longer on any branch. */
1003 refs_update_ref(get_main_ref_store(the_repository), msg.buf,
1004 "HEAD", &new_branch_info->commit->object.oid,
1005 NULL,
1006 REF_NO_DEREF, UPDATE_REFS_DIE_ON_ERR);
1007 if (!opts->quiet) {
1008 if (old_branch_info->path &&
1009 advice_enabled(ADVICE_DETACHED_HEAD) && !opts->force_detach)
1010 detach_advice(new_branch_info->name);
1011 describe_detached_head(_("HEAD is now at"), new_branch_info->commit);
1013 } else if (new_branch_info->path) { /* Switch branches. */
1014 if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", new_branch_info->path, msg.buf) < 0)
1015 die(_("unable to update HEAD"));
1016 if (!opts->quiet) {
1017 if (old_branch_info->path && !strcmp(new_branch_info->path, old_branch_info->path)) {
1018 if (opts->new_branch_force)
1019 fprintf(stderr, _("Reset branch '%s'\n"),
1020 new_branch_info->name);
1021 else
1022 fprintf(stderr, _("Already on '%s'\n"),
1023 new_branch_info->name);
1024 } else if (opts->new_branch) {
1025 if (opts->branch_exists)
1026 fprintf(stderr, _("Switched to and reset branch '%s'\n"), new_branch_info->name);
1027 else
1028 fprintf(stderr, _("Switched to a new branch '%s'\n"), new_branch_info->name);
1029 } else {
1030 fprintf(stderr, _("Switched to branch '%s'\n"),
1031 new_branch_info->name);
1034 if (old_branch_info->path && old_branch_info->name) {
1035 if (!refs_ref_exists(get_main_ref_store(the_repository), old_branch_info->path) && refs_reflog_exists(get_main_ref_store(the_repository), old_branch_info->path))
1036 refs_delete_reflog(get_main_ref_store(the_repository),
1037 old_branch_info->path);
1040 remove_branch_state(the_repository, !opts->quiet);
1041 strbuf_release(&msg);
1042 if (!opts->quiet &&
1043 !opts->force_detach &&
1044 (new_branch_info->path || !strcmp(new_branch_info->name, "HEAD")))
1045 report_tracking(new_branch_info);
1048 static int add_pending_uninteresting_ref(const char *refname,
1049 const struct object_id *oid,
1050 int flags UNUSED, void *cb_data)
1052 add_pending_oid(cb_data, refname, oid, UNINTERESTING);
1053 return 0;
1056 static void describe_one_orphan(struct strbuf *sb, struct commit *commit)
1058 strbuf_addstr(sb, " ");
1059 strbuf_add_unique_abbrev(sb, &commit->object.oid, DEFAULT_ABBREV);
1060 strbuf_addch(sb, ' ');
1061 if (!repo_parse_commit(the_repository, commit))
1062 pp_commit_easy(CMIT_FMT_ONELINE, commit, sb);
1063 strbuf_addch(sb, '\n');
1066 #define ORPHAN_CUTOFF 4
1067 static void suggest_reattach(struct commit *commit, struct rev_info *revs)
1069 struct commit *c, *last = NULL;
1070 struct strbuf sb = STRBUF_INIT;
1071 int lost = 0;
1072 while ((c = get_revision(revs)) != NULL) {
1073 if (lost < ORPHAN_CUTOFF)
1074 describe_one_orphan(&sb, c);
1075 last = c;
1076 lost++;
1078 if (ORPHAN_CUTOFF < lost) {
1079 int more = lost - ORPHAN_CUTOFF;
1080 if (more == 1)
1081 describe_one_orphan(&sb, last);
1082 else
1083 strbuf_addf(&sb, _(" ... and %d more.\n"), more);
1086 fprintf(stderr,
1088 /* The singular version */
1089 "Warning: you are leaving %d commit behind, "
1090 "not connected to\n"
1091 "any of your branches:\n\n"
1092 "%s\n",
1093 /* The plural version */
1094 "Warning: you are leaving %d commits behind, "
1095 "not connected to\n"
1096 "any of your branches:\n\n"
1097 "%s\n",
1098 /* Give ngettext() the count */
1099 lost),
1100 lost,
1101 sb.buf);
1102 strbuf_release(&sb);
1104 if (advice_enabled(ADVICE_DETACHED_HEAD))
1105 fprintf(stderr,
1107 /* The singular version */
1108 "If you want to keep it by creating a new branch, "
1109 "this may be a good time\nto do so with:\n\n"
1110 " git branch <new-branch-name> %s\n\n",
1111 /* The plural version */
1112 "If you want to keep them by creating a new branch, "
1113 "this may be a good time\nto do so with:\n\n"
1114 " git branch <new-branch-name> %s\n\n",
1115 /* Give ngettext() the count */
1116 lost),
1117 repo_find_unique_abbrev(the_repository, &commit->object.oid, DEFAULT_ABBREV));
1121 * We are about to leave commit that was at the tip of a detached
1122 * HEAD. If it is not reachable from any ref, this is the last chance
1123 * for the user to do so without resorting to reflog.
1125 static void orphaned_commit_warning(struct commit *old_commit, struct commit *new_commit)
1127 struct rev_info revs;
1128 struct object *object = &old_commit->object;
1130 repo_init_revisions(the_repository, &revs, NULL);
1131 setup_revisions(0, NULL, &revs, NULL);
1133 object->flags &= ~UNINTERESTING;
1134 add_pending_object(&revs, object, oid_to_hex(&object->oid));
1136 refs_for_each_ref(get_main_ref_store(the_repository),
1137 add_pending_uninteresting_ref, &revs);
1138 if (new_commit)
1139 add_pending_oid(&revs, "HEAD",
1140 &new_commit->object.oid,
1141 UNINTERESTING);
1143 if (prepare_revision_walk(&revs))
1144 die(_("internal error in revision walk"));
1145 if (!(old_commit->object.flags & UNINTERESTING))
1146 suggest_reattach(old_commit, &revs);
1147 else
1148 describe_detached_head(_("Previous HEAD position was"), old_commit);
1150 /* Clean up objects used, as they will be reused. */
1151 repo_clear_commit_marks(the_repository, ALL_REV_FLAGS);
1152 release_revisions(&revs);
1155 static int switch_branches(const struct checkout_opts *opts,
1156 struct branch_info *new_branch_info)
1158 int ret = 0;
1159 struct branch_info old_branch_info = { 0 };
1160 struct object_id rev;
1161 int flag, writeout_error = 0;
1162 int do_merge = 1;
1164 trace2_cmd_mode("branch");
1166 memset(&old_branch_info, 0, sizeof(old_branch_info));
1167 old_branch_info.path = refs_resolve_refdup(get_main_ref_store(the_repository),
1168 "HEAD", 0, &rev, &flag);
1169 if (old_branch_info.path)
1170 old_branch_info.commit = lookup_commit_reference_gently(the_repository, &rev, 1);
1171 if (!(flag & REF_ISSYMREF))
1172 FREE_AND_NULL(old_branch_info.path);
1174 if (old_branch_info.path) {
1175 const char *const prefix = "refs/heads/";
1176 const char *p;
1177 if (skip_prefix(old_branch_info.path, prefix, &p))
1178 old_branch_info.name = xstrdup(p);
1181 if (opts->new_orphan_branch && opts->orphan_from_empty_tree) {
1182 if (new_branch_info->name)
1183 BUG("'switch --orphan' should never accept a commit as starting point");
1184 new_branch_info->commit = NULL;
1185 new_branch_info->name = xstrdup("(empty)");
1186 do_merge = 1;
1189 if (!new_branch_info->name) {
1190 new_branch_info->name = xstrdup("HEAD");
1191 new_branch_info->commit = old_branch_info.commit;
1192 if (!new_branch_info->commit)
1193 die(_("You are on a branch yet to be born"));
1194 parse_commit_or_die(new_branch_info->commit);
1196 if (opts->only_merge_on_switching_branches)
1197 do_merge = 0;
1200 if (do_merge) {
1201 ret = merge_working_tree(opts, &old_branch_info, new_branch_info, &writeout_error);
1202 if (ret) {
1203 branch_info_release(&old_branch_info);
1204 return ret;
1208 if (!opts->quiet && !old_branch_info.path && old_branch_info.commit && new_branch_info->commit != old_branch_info.commit)
1209 orphaned_commit_warning(old_branch_info.commit, new_branch_info->commit);
1211 update_refs_for_switch(opts, &old_branch_info, new_branch_info);
1213 ret = post_checkout_hook(old_branch_info.commit, new_branch_info->commit, 1);
1214 branch_info_release(&old_branch_info);
1216 return ret || writeout_error;
1219 static int git_checkout_config(const char *var, const char *value,
1220 const struct config_context *ctx, void *cb)
1222 struct checkout_opts *opts = cb;
1224 if (!strcmp(var, "diff.ignoresubmodules")) {
1225 if (!value)
1226 return config_error_nonbool(var);
1227 handle_ignore_submodules_arg(&opts->diff_options, value);
1228 return 0;
1230 if (!strcmp(var, "checkout.guess")) {
1231 opts->dwim_new_local_branch = git_config_bool(var, value);
1232 return 0;
1235 if (starts_with(var, "submodule."))
1236 return git_default_submodule_config(var, value, NULL);
1238 return git_xmerge_config(var, value, ctx, NULL);
1241 static void setup_new_branch_info_and_source_tree(
1242 struct branch_info *new_branch_info,
1243 struct checkout_opts *opts,
1244 struct object_id *rev,
1245 const char *arg)
1247 struct tree **source_tree = &opts->source_tree;
1248 struct object_id branch_rev;
1250 /* treat '@' as a shortcut for 'HEAD' */
1251 new_branch_info->name = !strcmp(arg, "@") ? xstrdup("HEAD") :
1252 xstrdup(arg);
1253 setup_branch_path(new_branch_info);
1255 if (!check_refname_format(new_branch_info->path, 0) &&
1256 !refs_read_ref(get_main_ref_store(the_repository), new_branch_info->path, &branch_rev))
1257 oidcpy(rev, &branch_rev);
1258 else
1259 /* not an existing branch */
1260 FREE_AND_NULL(new_branch_info->path);
1262 new_branch_info->commit = lookup_commit_reference_gently(the_repository, rev, 1);
1263 if (!new_branch_info->commit) {
1264 /* not a commit */
1265 *source_tree = parse_tree_indirect(rev);
1266 if (!*source_tree)
1267 die(_("unable to read tree (%s)"), oid_to_hex(rev));
1268 } else {
1269 parse_commit_or_die(new_branch_info->commit);
1270 *source_tree = repo_get_commit_tree(the_repository,
1271 new_branch_info->commit);
1272 if (!*source_tree)
1273 die(_("unable to read tree (%s)"),
1274 oid_to_hex(&new_branch_info->commit->object.oid));
1278 static char *parse_remote_branch(const char *arg,
1279 struct object_id *rev,
1280 int could_be_checkout_paths)
1282 int num_matches = 0;
1283 char *remote = unique_tracking_name(arg, rev, &num_matches);
1285 if (remote && could_be_checkout_paths) {
1286 die(_("'%s' could be both a local file and a tracking branch.\n"
1287 "Please use -- (and optionally --no-guess) to disambiguate"),
1288 arg);
1291 if (!remote && num_matches > 1) {
1292 if (advice_enabled(ADVICE_CHECKOUT_AMBIGUOUS_REMOTE_BRANCH_NAME)) {
1293 advise(_("If you meant to check out a remote tracking branch on, e.g. 'origin',\n"
1294 "you can do so by fully qualifying the name with the --track option:\n"
1295 "\n"
1296 " git checkout --track origin/<name>\n"
1297 "\n"
1298 "If you'd like to always have checkouts of an ambiguous <name> prefer\n"
1299 "one remote, e.g. the 'origin' remote, consider setting\n"
1300 "checkout.defaultRemote=origin in your config."));
1303 die(_("'%s' matched multiple (%d) remote tracking branches"),
1304 arg, num_matches);
1307 return remote;
1310 static int parse_branchname_arg(int argc, const char **argv,
1311 int dwim_new_local_branch_ok,
1312 struct branch_info *new_branch_info,
1313 struct checkout_opts *opts,
1314 struct object_id *rev)
1316 const char **new_branch = &opts->new_branch;
1317 int argcount = 0;
1318 const char *arg;
1319 char *remote = NULL;
1320 int dash_dash_pos;
1321 int has_dash_dash = 0;
1322 int i;
1325 * case 1: git checkout <ref> -- [<paths>]
1327 * <ref> must be a valid tree, everything after the '--' must be
1328 * a path.
1330 * case 2: git checkout -- [<paths>]
1332 * everything after the '--' must be paths.
1334 * case 3: git checkout <something> [--]
1336 * (a) If <something> is a commit, that is to
1337 * switch to the branch or detach HEAD at it. As a special case,
1338 * if <something> is A...B (missing A or B means HEAD but you can
1339 * omit at most one side), and if there is a unique merge base
1340 * between A and B, A...B names that merge base.
1342 * (b) If <something> is _not_ a commit, either "--" is present
1343 * or <something> is not a path, no -t or -b was given,
1344 * and there is a tracking branch whose name is <something>
1345 * in one and only one remote (or if the branch exists on the
1346 * remote named in checkout.defaultRemote), then this is a
1347 * short-hand to fork local <something> from that
1348 * remote-tracking branch.
1350 * (c) Otherwise, if "--" is present, treat it like case (1).
1352 * (d) Otherwise :
1353 * - if it's a reference, treat it like case (1)
1354 * - else if it's a path, treat it like case (2)
1355 * - else: fail.
1357 * case 4: git checkout <something> <paths>
1359 * The first argument must not be ambiguous.
1360 * - If it's *only* a reference, treat it like case (1).
1361 * - If it's only a path, treat it like case (2).
1362 * - else: fail.
1365 if (!argc)
1366 return 0;
1368 if (!opts->accept_pathspec) {
1369 if (argc > 1)
1370 die(_("only one reference expected"));
1371 has_dash_dash = 1; /* helps disambiguate */
1374 arg = argv[0];
1375 dash_dash_pos = -1;
1376 for (i = 0; i < argc; i++) {
1377 if (opts->accept_pathspec && !strcmp(argv[i], "--")) {
1378 dash_dash_pos = i;
1379 break;
1382 if (dash_dash_pos == 0)
1383 return 1; /* case (2) */
1384 else if (dash_dash_pos == 1)
1385 has_dash_dash = 1; /* case (3) or (1) */
1386 else if (dash_dash_pos >= 2)
1387 die(_("only one reference expected, %d given."), dash_dash_pos);
1388 opts->count_checkout_paths = !opts->quiet && !has_dash_dash;
1390 if (!strcmp(arg, "-"))
1391 arg = "@{-1}";
1393 if (repo_get_oid_mb(the_repository, arg, rev)) {
1395 * Either case (3) or (4), with <something> not being
1396 * a commit, or an attempt to use case (1) with an
1397 * invalid ref.
1399 * It's likely an error, but we need to find out if
1400 * we should auto-create the branch, case (3).(b).
1402 int recover_with_dwim = dwim_new_local_branch_ok;
1404 int could_be_checkout_paths = !has_dash_dash &&
1405 check_filename(opts->prefix, arg);
1407 if (!has_dash_dash && !no_wildcard(arg))
1408 recover_with_dwim = 0;
1411 * Accept "git checkout foo", "git checkout foo --"
1412 * and "git switch foo" as candidates for dwim.
1414 if (!(argc == 1 && !has_dash_dash) &&
1415 !(argc == 2 && has_dash_dash) &&
1416 opts->accept_pathspec)
1417 recover_with_dwim = 0;
1419 if (recover_with_dwim) {
1420 remote = parse_remote_branch(arg, rev,
1421 could_be_checkout_paths);
1422 if (remote) {
1423 *new_branch = arg;
1424 arg = remote;
1425 /* DWIMmed to create local branch, case (3).(b) */
1426 } else {
1427 recover_with_dwim = 0;
1431 if (!recover_with_dwim) {
1432 if (has_dash_dash)
1433 die(_("invalid reference: %s"), arg);
1434 return argcount;
1438 /* we can't end up being in (2) anymore, eat the argument */
1439 argcount++;
1440 argv++;
1441 argc--;
1443 setup_new_branch_info_and_source_tree(new_branch_info, opts, rev, arg);
1445 if (!opts->source_tree) /* case (1): want a tree */
1446 die(_("reference is not a tree: %s"), arg);
1448 if (!has_dash_dash) { /* case (3).(d) -> (1) */
1450 * Do not complain the most common case
1451 * git checkout branch
1452 * even if there happen to be a file called 'branch';
1453 * it would be extremely annoying.
1455 if (argc)
1456 verify_non_filename(opts->prefix, arg);
1457 } else if (opts->accept_pathspec) {
1458 argcount++;
1459 argv++;
1460 argc--;
1463 free(remote);
1464 return argcount;
1467 static int switch_unborn_to_new_branch(const struct checkout_opts *opts)
1469 int status;
1470 struct strbuf branch_ref = STRBUF_INIT;
1472 trace2_cmd_mode("unborn");
1474 if (!opts->new_branch)
1475 die(_("You are on a branch yet to be born"));
1476 strbuf_addf(&branch_ref, "refs/heads/%s", opts->new_branch);
1477 status = refs_update_symref(get_main_ref_store(the_repository),
1478 "HEAD", branch_ref.buf, "checkout -b");
1479 strbuf_release(&branch_ref);
1480 if (!opts->quiet)
1481 fprintf(stderr, _("Switched to a new branch '%s'\n"),
1482 opts->new_branch);
1483 return status;
1486 static void die_expecting_a_branch(const struct branch_info *branch_info)
1488 struct object_id oid;
1489 char *to_free;
1490 int code;
1492 if (repo_dwim_ref(the_repository, branch_info->name,
1493 strlen(branch_info->name), &oid, &to_free, 0) == 1) {
1494 const char *ref = to_free;
1496 if (skip_prefix(ref, "refs/tags/", &ref))
1497 code = die_message(_("a branch is expected, got tag '%s'"), ref);
1498 else if (skip_prefix(ref, "refs/remotes/", &ref))
1499 code = die_message(_("a branch is expected, got remote branch '%s'"), ref);
1500 else
1501 code = die_message(_("a branch is expected, got '%s'"), ref);
1503 else if (branch_info->commit)
1504 code = die_message(_("a branch is expected, got commit '%s'"), branch_info->name);
1505 else
1507 * This case should never happen because we already die() on
1508 * non-commit, but just in case.
1510 code = die_message(_("a branch is expected, got '%s'"), branch_info->name);
1512 if (advice_enabled(ADVICE_SUGGEST_DETACHING_HEAD))
1513 advise(_("If you want to detach HEAD at the commit, try again with the --detach option."));
1515 exit(code);
1518 static void die_if_some_operation_in_progress(void)
1520 struct wt_status_state state;
1522 memset(&state, 0, sizeof(state));
1523 wt_status_get_state(the_repository, &state, 0);
1525 if (state.merge_in_progress)
1526 die(_("cannot switch branch while merging\n"
1527 "Consider \"git merge --quit\" "
1528 "or \"git worktree add\"."));
1529 if (state.am_in_progress)
1530 die(_("cannot switch branch in the middle of an am session\n"
1531 "Consider \"git am --quit\" "
1532 "or \"git worktree add\"."));
1533 if (state.rebase_interactive_in_progress || state.rebase_in_progress)
1534 die(_("cannot switch branch while rebasing\n"
1535 "Consider \"git rebase --quit\" "
1536 "or \"git worktree add\"."));
1537 if (state.cherry_pick_in_progress)
1538 die(_("cannot switch branch while cherry-picking\n"
1539 "Consider \"git cherry-pick --quit\" "
1540 "or \"git worktree add\"."));
1541 if (state.revert_in_progress)
1542 die(_("cannot switch branch while reverting\n"
1543 "Consider \"git revert --quit\" "
1544 "or \"git worktree add\"."));
1545 if (state.bisect_in_progress)
1546 warning(_("you are switching branch while bisecting"));
1548 wt_status_state_free_buffers(&state);
1552 * die if attempting to checkout an existing branch that is in use
1553 * in another worktree, unless ignore-other-wortrees option is given.
1554 * The check is bypassed when the branch is already the current one,
1555 * as it will not make things any worse.
1557 static void die_if_switching_to_a_branch_in_use(struct checkout_opts *opts,
1558 const char *full_ref)
1560 int flags;
1561 char *head_ref;
1563 if (opts->ignore_other_worktrees)
1564 return;
1565 head_ref = refs_resolve_refdup(get_main_ref_store(the_repository),
1566 "HEAD", 0, NULL, &flags);
1567 if (head_ref && (!(flags & REF_ISSYMREF) || strcmp(head_ref, full_ref)))
1568 die_if_checked_out(full_ref, 1);
1569 free(head_ref);
1572 static int checkout_branch(struct checkout_opts *opts,
1573 struct branch_info *new_branch_info)
1575 if (opts->pathspec.nr)
1576 die(_("paths cannot be used with switching branches"));
1578 if (opts->patch_mode)
1579 die(_("'%s' cannot be used with switching branches"),
1580 "--patch");
1582 if (opts->overlay_mode != -1)
1583 die(_("'%s' cannot be used with switching branches"),
1584 "--[no]-overlay");
1586 if (opts->writeout_stage)
1587 die(_("'%s' cannot be used with switching branches"),
1588 "--ours/--theirs");
1590 if (opts->force && opts->merge)
1591 die(_("'%s' cannot be used with '%s'"), "-f", "-m");
1593 if (opts->discard_changes && opts->merge)
1594 die(_("'%s' cannot be used with '%s'"), "--discard-changes", "--merge");
1596 if (opts->force_detach && opts->new_branch)
1597 die(_("'%s' cannot be used with '%s'"),
1598 "--detach", "-b/-B/--orphan");
1600 if (opts->new_orphan_branch) {
1601 if (opts->track != BRANCH_TRACK_UNSPECIFIED)
1602 die(_("'%s' cannot be used with '%s'"), "--orphan", "-t");
1603 if (opts->orphan_from_empty_tree && new_branch_info->name)
1604 die(_("'%s' cannot take <start-point>"), "--orphan");
1605 } else if (opts->force_detach) {
1606 if (opts->track != BRANCH_TRACK_UNSPECIFIED)
1607 die(_("'%s' cannot be used with '%s'"), "--detach", "-t");
1608 } else if (opts->track == BRANCH_TRACK_UNSPECIFIED)
1609 opts->track = git_branch_track;
1611 if (new_branch_info->name && !new_branch_info->commit)
1612 die(_("Cannot switch branch to a non-commit '%s'"),
1613 new_branch_info->name);
1615 if (!opts->switch_branch_doing_nothing_is_ok &&
1616 !new_branch_info->name &&
1617 !opts->new_branch &&
1618 !opts->force_detach)
1619 die(_("missing branch or commit argument"));
1621 if (!opts->implicit_detach &&
1622 !opts->force_detach &&
1623 !opts->new_branch &&
1624 !opts->new_branch_force &&
1625 new_branch_info->name &&
1626 !new_branch_info->path)
1627 die_expecting_a_branch(new_branch_info);
1629 if (!opts->can_switch_when_in_progress)
1630 die_if_some_operation_in_progress();
1632 /* "git checkout <branch>" */
1633 if (new_branch_info->path && !opts->force_detach && !opts->new_branch)
1634 die_if_switching_to_a_branch_in_use(opts, new_branch_info->path);
1636 /* "git checkout -B <branch>" */
1637 if (opts->new_branch_force) {
1638 char *full_ref = xstrfmt("refs/heads/%s", opts->new_branch);
1639 die_if_switching_to_a_branch_in_use(opts, full_ref);
1640 free(full_ref);
1643 if (!new_branch_info->commit && opts->new_branch) {
1644 struct object_id rev;
1645 int flag;
1647 if (!refs_read_ref_full(get_main_ref_store(the_repository), "HEAD", 0, &rev, &flag) &&
1648 (flag & REF_ISSYMREF) && is_null_oid(&rev))
1649 return switch_unborn_to_new_branch(opts);
1651 return switch_branches(opts, new_branch_info);
1654 static int parse_opt_conflict(const struct option *o, const char *arg, int unset)
1656 struct checkout_opts *opts = o->value;
1658 if (unset) {
1659 opts->conflict_style = -1;
1660 return 0;
1662 opts->conflict_style = parse_conflict_style_name(arg);
1663 if (opts->conflict_style < 0)
1664 return error(_("unknown conflict style '%s'"), arg);
1665 /* --conflict overrides a previous --no-merge */
1666 if (!opts->merge)
1667 opts->merge = -1;
1669 return 0;
1672 static struct option *add_common_options(struct checkout_opts *opts,
1673 struct option *prevopts)
1675 struct option options[] = {
1676 OPT__QUIET(&opts->quiet, N_("suppress progress reporting")),
1677 OPT_CALLBACK_F(0, "recurse-submodules", NULL,
1678 "checkout", "control recursive updating of submodules",
1679 PARSE_OPT_OPTARG, option_parse_recurse_submodules_worktree_updater),
1680 OPT_BOOL(0, "progress", &opts->show_progress, N_("force progress reporting")),
1681 OPT_BOOL('m', "merge", &opts->merge, N_("perform a 3-way merge with the new branch")),
1682 OPT_CALLBACK(0, "conflict", opts, N_("style"),
1683 N_("conflict style (merge, diff3, or zdiff3)"),
1684 parse_opt_conflict),
1685 OPT_END()
1687 struct option *newopts = parse_options_concat(prevopts, options);
1688 free(prevopts);
1689 return newopts;
1692 static struct option *add_common_switch_branch_options(
1693 struct checkout_opts *opts, struct option *prevopts)
1695 struct option options[] = {
1696 OPT_BOOL('d', "detach", &opts->force_detach, N_("detach HEAD at named commit")),
1697 OPT_CALLBACK_F('t', "track", &opts->track, "(direct|inherit)",
1698 N_("set branch tracking configuration"),
1699 PARSE_OPT_OPTARG,
1700 parse_opt_tracking_mode),
1701 OPT__FORCE(&opts->force, N_("force checkout (throw away local modifications)"),
1702 PARSE_OPT_NOCOMPLETE),
1703 OPT_STRING(0, "orphan", &opts->new_orphan_branch, N_("new-branch"), N_("new unborn branch")),
1704 OPT_BOOL_F(0, "overwrite-ignore", &opts->overwrite_ignore,
1705 N_("update ignored files (default)"),
1706 PARSE_OPT_NOCOMPLETE),
1707 OPT_BOOL(0, "ignore-other-worktrees", &opts->ignore_other_worktrees,
1708 N_("do not check if another worktree is holding the given ref")),
1709 OPT_END()
1711 struct option *newopts = parse_options_concat(prevopts, options);
1712 free(prevopts);
1713 return newopts;
1716 static struct option *add_checkout_path_options(struct checkout_opts *opts,
1717 struct option *prevopts)
1719 struct option options[] = {
1720 OPT_SET_INT_F('2', "ours", &opts->writeout_stage,
1721 N_("checkout our version for unmerged files"),
1722 2, PARSE_OPT_NONEG),
1723 OPT_SET_INT_F('3', "theirs", &opts->writeout_stage,
1724 N_("checkout their version for unmerged files"),
1725 3, PARSE_OPT_NONEG),
1726 OPT_BOOL('p', "patch", &opts->patch_mode, N_("select hunks interactively")),
1727 OPT_BOOL(0, "ignore-skip-worktree-bits", &opts->ignore_skipworktree,
1728 N_("do not limit pathspecs to sparse entries only")),
1729 OPT_PATHSPEC_FROM_FILE(&opts->pathspec_from_file),
1730 OPT_PATHSPEC_FILE_NUL(&opts->pathspec_file_nul),
1731 OPT_END()
1733 struct option *newopts = parse_options_concat(prevopts, options);
1734 free(prevopts);
1735 return newopts;
1738 /* create-branch option (either b or c) */
1739 static char cb_option = 'b';
1741 static int checkout_main(int argc, const char **argv, const char *prefix,
1742 struct checkout_opts *opts, struct option *options,
1743 const char * const usagestr[])
1745 int parseopt_flags = 0;
1746 struct branch_info new_branch_info = { 0 };
1747 int ret;
1749 opts->overwrite_ignore = 1;
1750 opts->prefix = prefix;
1751 opts->show_progress = -1;
1753 git_config(git_checkout_config, opts);
1754 if (the_repository->gitdir) {
1755 prepare_repo_settings(the_repository);
1756 the_repository->settings.command_requires_full_index = 0;
1759 opts->track = BRANCH_TRACK_UNSPECIFIED;
1761 if (!opts->accept_pathspec && !opts->accept_ref)
1762 BUG("make up your mind, you need to take _something_");
1763 if (opts->accept_pathspec && opts->accept_ref)
1764 parseopt_flags = PARSE_OPT_KEEP_DASHDASH;
1766 argc = parse_options(argc, argv, prefix, options,
1767 usagestr, parseopt_flags);
1769 if (opts->show_progress < 0) {
1770 if (opts->quiet)
1771 opts->show_progress = 0;
1772 else
1773 opts->show_progress = isatty(2);
1776 /* --conflicts implies --merge */
1777 if (opts->merge == -1)
1778 opts->merge = opts->conflict_style >= 0;
1780 if (opts->force) {
1781 opts->discard_changes = 1;
1782 opts->ignore_unmerged_opt = "--force";
1783 opts->ignore_unmerged = 1;
1786 if ((!!opts->new_branch + !!opts->new_branch_force + !!opts->new_orphan_branch) > 1)
1787 die(_("options '-%c', '-%c', and '%s' cannot be used together"),
1788 cb_option, toupper(cb_option), "--orphan");
1790 if (opts->overlay_mode == 1 && opts->patch_mode)
1791 die(_("options '%s' and '%s' cannot be used together"), "-p", "--overlay");
1793 if (opts->checkout_index >= 0 || opts->checkout_worktree >= 0) {
1794 if (opts->checkout_index < 0)
1795 opts->checkout_index = 0;
1796 if (opts->checkout_worktree < 0)
1797 opts->checkout_worktree = 0;
1798 } else {
1799 if (opts->checkout_index < 0)
1800 opts->checkout_index = -opts->checkout_index - 1;
1801 if (opts->checkout_worktree < 0)
1802 opts->checkout_worktree = -opts->checkout_worktree - 1;
1804 if (opts->checkout_index < 0 || opts->checkout_worktree < 0)
1805 BUG("these flags should be non-negative by now");
1807 * convenient shortcut: "git restore --staged [--worktree]" equals
1808 * "git restore --staged [--worktree] --source HEAD"
1810 if (!opts->from_treeish && opts->checkout_index)
1811 opts->from_treeish = "HEAD";
1814 * From here on, new_branch will contain the branch to be checked out,
1815 * and new_branch_force and new_orphan_branch will tell us which one of
1816 * -b/-B/-c/-C/--orphan is being used.
1818 if (opts->new_branch_force)
1819 opts->new_branch = opts->new_branch_force;
1821 if (opts->new_orphan_branch)
1822 opts->new_branch = opts->new_orphan_branch;
1824 /* --track without -c/-C/-b/-B/--orphan should DWIM */
1825 if (opts->track != BRANCH_TRACK_UNSPECIFIED && !opts->new_branch) {
1826 const char *argv0 = argv[0];
1827 if (!argc || !strcmp(argv0, "--"))
1828 die(_("--track needs a branch name"));
1829 skip_prefix(argv0, "refs/", &argv0);
1830 skip_prefix(argv0, "remotes/", &argv0);
1831 argv0 = strchr(argv0, '/');
1832 if (!argv0 || !argv0[1])
1833 die(_("missing branch name; try -%c"), cb_option);
1834 opts->new_branch = argv0 + 1;
1838 * Extract branch name from command line arguments, so
1839 * all that is left is pathspecs.
1841 * Handle
1843 * 1) git checkout <tree> -- [<paths>]
1844 * 2) git checkout -- [<paths>]
1845 * 3) git checkout <something> [<paths>]
1847 * including "last branch" syntax and DWIM-ery for names of
1848 * remote branches, erroring out for invalid or ambiguous cases.
1850 if (argc && opts->accept_ref) {
1851 struct object_id rev;
1852 int dwim_ok =
1853 !opts->patch_mode &&
1854 opts->dwim_new_local_branch &&
1855 opts->track == BRANCH_TRACK_UNSPECIFIED &&
1856 !opts->new_branch;
1857 int n = parse_branchname_arg(argc, argv, dwim_ok,
1858 &new_branch_info, opts, &rev);
1859 argv += n;
1860 argc -= n;
1861 } else if (!opts->accept_ref && opts->from_treeish) {
1862 struct object_id rev;
1864 if (repo_get_oid_mb(the_repository, opts->from_treeish, &rev))
1865 die(_("could not resolve %s"), opts->from_treeish);
1867 setup_new_branch_info_and_source_tree(&new_branch_info,
1868 opts, &rev,
1869 opts->from_treeish);
1871 if (!opts->source_tree)
1872 die(_("reference is not a tree: %s"), opts->from_treeish);
1875 if (argc) {
1876 parse_pathspec(&opts->pathspec, 0,
1877 opts->patch_mode ? PATHSPEC_PREFIX_ORIGIN : 0,
1878 prefix, argv);
1880 if (!opts->pathspec.nr)
1881 die(_("invalid path specification"));
1884 * Try to give more helpful suggestion.
1885 * new_branch && argc > 1 will be caught later.
1887 if (opts->new_branch && argc == 1 && !new_branch_info.commit)
1888 die(_("'%s' is not a commit and a branch '%s' cannot be created from it"),
1889 argv[0], opts->new_branch);
1891 if (opts->force_detach)
1892 die(_("git checkout: --detach does not take a path argument '%s'"),
1893 argv[0]);
1896 if (opts->pathspec_from_file) {
1897 if (opts->pathspec.nr)
1898 die(_("'%s' and pathspec arguments cannot be used together"), "--pathspec-from-file");
1900 if (opts->force_detach)
1901 die(_("options '%s' and '%s' cannot be used together"), "--pathspec-from-file", "--detach");
1903 if (opts->patch_mode)
1904 die(_("options '%s' and '%s' cannot be used together"), "--pathspec-from-file", "--patch");
1906 parse_pathspec_file(&opts->pathspec, 0,
1908 prefix, opts->pathspec_from_file, opts->pathspec_file_nul);
1909 } else if (opts->pathspec_file_nul) {
1910 die(_("the option '%s' requires '%s'"), "--pathspec-file-nul", "--pathspec-from-file");
1913 opts->pathspec.recursive = 1;
1915 if (opts->pathspec.nr) {
1916 if (1 < !!opts->writeout_stage + !!opts->force + !!opts->merge)
1917 die(_("git checkout: --ours/--theirs, --force and --merge are incompatible when\n"
1918 "checking out of the index."));
1919 } else {
1920 if (opts->accept_pathspec && !opts->empty_pathspec_ok &&
1921 !opts->patch_mode) /* patch mode is special */
1922 die(_("you must specify path(s) to restore"));
1925 if (opts->new_branch) {
1926 struct strbuf buf = STRBUF_INIT;
1928 if (opts->new_branch_force)
1929 opts->branch_exists = validate_branchname(opts->new_branch, &buf);
1930 else
1931 opts->branch_exists =
1932 validate_new_branchname(opts->new_branch, &buf, 0);
1933 strbuf_release(&buf);
1936 if (opts->patch_mode || opts->pathspec.nr)
1937 ret = checkout_paths(opts, &new_branch_info);
1938 else
1939 ret = checkout_branch(opts, &new_branch_info);
1941 branch_info_release(&new_branch_info);
1942 clear_pathspec(&opts->pathspec);
1943 free(opts->pathspec_from_file);
1944 free(options);
1946 return ret;
1949 int cmd_checkout(int argc, const char **argv, const char *prefix)
1951 struct checkout_opts opts = CHECKOUT_OPTS_INIT;
1952 struct option *options;
1953 struct option checkout_options[] = {
1954 OPT_STRING('b', NULL, &opts.new_branch, N_("branch"),
1955 N_("create and checkout a new branch")),
1956 OPT_STRING('B', NULL, &opts.new_branch_force, N_("branch"),
1957 N_("create/reset and checkout a branch")),
1958 OPT_BOOL('l', NULL, &opts.new_branch_log, N_("create reflog for new branch")),
1959 OPT_BOOL(0, "guess", &opts.dwim_new_local_branch,
1960 N_("second guess 'git checkout <no-such-branch>' (default)")),
1961 OPT_BOOL(0, "overlay", &opts.overlay_mode, N_("use overlay mode (default)")),
1962 OPT_END()
1965 opts.dwim_new_local_branch = 1;
1966 opts.switch_branch_doing_nothing_is_ok = 1;
1967 opts.only_merge_on_switching_branches = 0;
1968 opts.accept_ref = 1;
1969 opts.accept_pathspec = 1;
1970 opts.implicit_detach = 1;
1971 opts.can_switch_when_in_progress = 1;
1972 opts.orphan_from_empty_tree = 0;
1973 opts.empty_pathspec_ok = 1;
1974 opts.overlay_mode = -1;
1975 opts.checkout_index = -2; /* default on */
1976 opts.checkout_worktree = -2; /* default on */
1978 if (argc == 3 && !strcmp(argv[1], "-b")) {
1980 * User ran 'git checkout -b <branch>' and expects
1981 * the same behavior as 'git switch -c <branch>'.
1983 opts.switch_branch_doing_nothing_is_ok = 0;
1984 opts.only_merge_on_switching_branches = 1;
1987 options = parse_options_dup(checkout_options);
1988 options = add_common_options(&opts, options);
1989 options = add_common_switch_branch_options(&opts, options);
1990 options = add_checkout_path_options(&opts, options);
1992 return checkout_main(argc, argv, prefix, &opts, options,
1993 checkout_usage);
1996 int cmd_switch(int argc, const char **argv, const char *prefix)
1998 struct checkout_opts opts = CHECKOUT_OPTS_INIT;
1999 struct option *options = NULL;
2000 struct option switch_options[] = {
2001 OPT_STRING('c', "create", &opts.new_branch, N_("branch"),
2002 N_("create and switch to a new branch")),
2003 OPT_STRING('C', "force-create", &opts.new_branch_force, N_("branch"),
2004 N_("create/reset and switch to a branch")),
2005 OPT_BOOL(0, "guess", &opts.dwim_new_local_branch,
2006 N_("second guess 'git switch <no-such-branch>'")),
2007 OPT_BOOL(0, "discard-changes", &opts.discard_changes,
2008 N_("throw away local modifications")),
2009 OPT_END()
2012 opts.dwim_new_local_branch = 1;
2013 opts.accept_ref = 1;
2014 opts.accept_pathspec = 0;
2015 opts.switch_branch_doing_nothing_is_ok = 0;
2016 opts.only_merge_on_switching_branches = 1;
2017 opts.implicit_detach = 0;
2018 opts.can_switch_when_in_progress = 0;
2019 opts.orphan_from_empty_tree = 1;
2020 opts.overlay_mode = -1;
2022 options = parse_options_dup(switch_options);
2023 options = add_common_options(&opts, options);
2024 options = add_common_switch_branch_options(&opts, options);
2026 cb_option = 'c';
2028 return checkout_main(argc, argv, prefix, &opts, options,
2029 switch_branch_usage);
2032 int cmd_restore(int argc, const char **argv, const char *prefix)
2034 struct checkout_opts opts = CHECKOUT_OPTS_INIT;
2035 struct option *options;
2036 struct option restore_options[] = {
2037 OPT_STRING('s', "source", &opts.from_treeish, "<tree-ish>",
2038 N_("which tree-ish to checkout from")),
2039 OPT_BOOL('S', "staged", &opts.checkout_index,
2040 N_("restore the index")),
2041 OPT_BOOL('W', "worktree", &opts.checkout_worktree,
2042 N_("restore the working tree (default)")),
2043 OPT_BOOL(0, "ignore-unmerged", &opts.ignore_unmerged,
2044 N_("ignore unmerged entries")),
2045 OPT_BOOL(0, "overlay", &opts.overlay_mode, N_("use overlay mode")),
2046 OPT_END()
2049 opts.accept_ref = 0;
2050 opts.accept_pathspec = 1;
2051 opts.empty_pathspec_ok = 0;
2052 opts.overlay_mode = 0;
2053 opts.checkout_index = -1; /* default off */
2054 opts.checkout_worktree = -2; /* default on */
2055 opts.ignore_unmerged_opt = "--ignore-unmerged";
2057 options = parse_options_dup(restore_options);
2058 options = add_common_options(&opts, options);
2059 options = add_checkout_path_options(&opts, options);
2061 return checkout_main(argc, argv, prefix, &opts, options,
2062 restore_usage);