]> git.ipfire.org Git - thirdparty/git.git/blob - builtin/checkout.c
Merge branch 'pw/rebase-i-parse-fix'
[thirdparty/git.git] / builtin / checkout.c
1 #define USE_THE_INDEX_VARIABLE
2 #include "builtin.h"
3 #include "advice.h"
4 #include "blob.h"
5 #include "branch.h"
6 #include "cache-tree.h"
7 #include "checkout.h"
8 #include "commit.h"
9 #include "config.h"
10 #include "diff.h"
11 #include "dir.h"
12 #include "hook.h"
13 #include "ll-merge.h"
14 #include "lockfile.h"
15 #include "merge-recursive.h"
16 #include "object-store.h"
17 #include "parse-options.h"
18 #include "refs.h"
19 #include "remote.h"
20 #include "resolve-undo.h"
21 #include "revision.h"
22 #include "run-command.h"
23 #include "submodule.h"
24 #include "submodule-config.h"
25 #include "tree.h"
26 #include "tree-walk.h"
27 #include "unpack-trees.h"
28 #include "wt-status.h"
29 #include "xdiff-interface.h"
30 #include "entry.h"
31 #include "parallel-checkout.h"
32 #include "add-interactive.h"
33
34 static const char * const checkout_usage[] = {
35 N_("git checkout [<options>] <branch>"),
36 N_("git checkout [<options>] [<branch>] -- <file>..."),
37 NULL,
38 };
39
40 static const char * const switch_branch_usage[] = {
41 N_("git switch [<options>] [<branch>]"),
42 NULL,
43 };
44
45 static const char * const restore_usage[] = {
46 N_("git restore [<options>] [--source=<branch>] <file>..."),
47 NULL,
48 };
49
50 struct checkout_opts {
51 int patch_mode;
52 int quiet;
53 int merge;
54 int force;
55 int force_detach;
56 int implicit_detach;
57 int writeout_stage;
58 int overwrite_ignore;
59 int ignore_skipworktree;
60 int ignore_other_worktrees;
61 int show_progress;
62 int count_checkout_paths;
63 int overlay_mode;
64 int dwim_new_local_branch;
65 int discard_changes;
66 int accept_ref;
67 int accept_pathspec;
68 int switch_branch_doing_nothing_is_ok;
69 int only_merge_on_switching_branches;
70 int can_switch_when_in_progress;
71 int orphan_from_empty_tree;
72 int empty_pathspec_ok;
73 int checkout_index;
74 int checkout_worktree;
75 const char *ignore_unmerged_opt;
76 int ignore_unmerged;
77 int pathspec_file_nul;
78 const char *pathspec_from_file;
79
80 const char *new_branch;
81 const char *new_branch_force;
82 const char *new_orphan_branch;
83 int new_branch_log;
84 enum branch_track track;
85 struct diff_options diff_options;
86 char *conflict_style;
87
88 int branch_exists;
89 const char *prefix;
90 struct pathspec pathspec;
91 const char *from_treeish;
92 struct tree *source_tree;
93 };
94
95 struct branch_info {
96 char *name; /* The short name used */
97 char *path; /* The full name of a real branch */
98 struct commit *commit; /* The named commit */
99 char *refname; /* The full name of the ref being checked out. */
100 struct object_id oid; /* The object ID of the commit being checked out. */
101 /*
102 * if not null the branch is detached because it's already
103 * checked out in this checkout
104 */
105 char *checkout;
106 };
107
108 static void branch_info_release(struct branch_info *info)
109 {
110 free(info->name);
111 free(info->path);
112 free(info->refname);
113 free(info->checkout);
114 }
115
116 static int post_checkout_hook(struct commit *old_commit, struct commit *new_commit,
117 int changed)
118 {
119 return run_hooks_l("post-checkout",
120 oid_to_hex(old_commit ? &old_commit->object.oid : null_oid()),
121 oid_to_hex(new_commit ? &new_commit->object.oid : null_oid()),
122 changed ? "1" : "0", NULL);
123 /* "new_commit" can be NULL when checking out from the index before
124 a commit exists. */
125
126 }
127
128 static int update_some(const struct object_id *oid, struct strbuf *base,
129 const char *pathname, unsigned mode, void *context UNUSED)
130 {
131 int len;
132 struct cache_entry *ce;
133 int pos;
134
135 if (S_ISDIR(mode))
136 return READ_TREE_RECURSIVE;
137
138 len = base->len + strlen(pathname);
139 ce = make_empty_cache_entry(&the_index, len);
140 oidcpy(&ce->oid, oid);
141 memcpy(ce->name, base->buf, base->len);
142 memcpy(ce->name + base->len, pathname, len - base->len);
143 ce->ce_flags = create_ce_flags(0) | CE_UPDATE;
144 ce->ce_namelen = len;
145 ce->ce_mode = create_ce_mode(mode);
146
147 /*
148 * If the entry is the same as the current index, we can leave the old
149 * entry in place. Whether it is UPTODATE or not, checkout_entry will
150 * do the right thing.
151 */
152 pos = index_name_pos(&the_index, ce->name, ce->ce_namelen);
153 if (pos >= 0) {
154 struct cache_entry *old = the_index.cache[pos];
155 if (ce->ce_mode == old->ce_mode &&
156 !ce_intent_to_add(old) &&
157 oideq(&ce->oid, &old->oid)) {
158 old->ce_flags |= CE_UPDATE;
159 discard_cache_entry(ce);
160 return 0;
161 }
162 }
163
164 add_index_entry(&the_index, ce,
165 ADD_CACHE_OK_TO_ADD | ADD_CACHE_OK_TO_REPLACE);
166 return 0;
167 }
168
169 static int read_tree_some(struct tree *tree, const struct pathspec *pathspec)
170 {
171 read_tree(the_repository, tree,
172 pathspec, update_some, NULL);
173
174 /* update the index with the given tree's info
175 * for all args, expanding wildcards, and exit
176 * with any non-zero return code.
177 */
178 return 0;
179 }
180
181 static int skip_same_name(const struct cache_entry *ce, int pos)
182 {
183 while (++pos < the_index.cache_nr &&
184 !strcmp(the_index.cache[pos]->name, ce->name))
185 ; /* skip */
186 return pos;
187 }
188
189 static int check_stage(int stage, const struct cache_entry *ce, int pos,
190 int overlay_mode)
191 {
192 while (pos < the_index.cache_nr &&
193 !strcmp(the_index.cache[pos]->name, ce->name)) {
194 if (ce_stage(the_index.cache[pos]) == stage)
195 return 0;
196 pos++;
197 }
198 if (!overlay_mode)
199 return 0;
200 if (stage == 2)
201 return error(_("path '%s' does not have our version"), ce->name);
202 else
203 return error(_("path '%s' does not have their version"), ce->name);
204 }
205
206 static int check_stages(unsigned stages, const struct cache_entry *ce, int pos)
207 {
208 unsigned seen = 0;
209 const char *name = ce->name;
210
211 while (pos < the_index.cache_nr) {
212 ce = the_index.cache[pos];
213 if (strcmp(name, ce->name))
214 break;
215 seen |= (1 << ce_stage(ce));
216 pos++;
217 }
218 if ((stages & seen) != stages)
219 return error(_("path '%s' does not have all necessary versions"),
220 name);
221 return 0;
222 }
223
224 static int checkout_stage(int stage, const struct cache_entry *ce, int pos,
225 const struct checkout *state, int *nr_checkouts,
226 int overlay_mode)
227 {
228 while (pos < the_index.cache_nr &&
229 !strcmp(the_index.cache[pos]->name, ce->name)) {
230 if (ce_stage(the_index.cache[pos]) == stage)
231 return checkout_entry(the_index.cache[pos], state,
232 NULL, nr_checkouts);
233 pos++;
234 }
235 if (!overlay_mode) {
236 unlink_entry(ce, NULL);
237 return 0;
238 }
239 if (stage == 2)
240 return error(_("path '%s' does not have our version"), ce->name);
241 else
242 return error(_("path '%s' does not have their version"), ce->name);
243 }
244
245 static int checkout_merged(int pos, const struct checkout *state,
246 int *nr_checkouts, struct mem_pool *ce_mem_pool)
247 {
248 struct cache_entry *ce = the_index.cache[pos];
249 const char *path = ce->name;
250 mmfile_t ancestor, ours, theirs;
251 enum ll_merge_result merge_status;
252 int status;
253 struct object_id oid;
254 mmbuffer_t result_buf;
255 struct object_id threeway[3];
256 unsigned mode = 0;
257 struct ll_merge_options ll_opts;
258 int renormalize = 0;
259
260 memset(threeway, 0, sizeof(threeway));
261 while (pos < the_index.cache_nr) {
262 int stage;
263 stage = ce_stage(ce);
264 if (!stage || strcmp(path, ce->name))
265 break;
266 oidcpy(&threeway[stage - 1], &ce->oid);
267 if (stage == 2)
268 mode = create_ce_mode(ce->ce_mode);
269 pos++;
270 ce = the_index.cache[pos];
271 }
272 if (is_null_oid(&threeway[1]) || is_null_oid(&threeway[2]))
273 return error(_("path '%s' does not have necessary versions"), path);
274
275 read_mmblob(&ancestor, &threeway[0]);
276 read_mmblob(&ours, &threeway[1]);
277 read_mmblob(&theirs, &threeway[2]);
278
279 memset(&ll_opts, 0, sizeof(ll_opts));
280 git_config_get_bool("merge.renormalize", &renormalize);
281 ll_opts.renormalize = renormalize;
282 merge_status = ll_merge(&result_buf, path, &ancestor, "base",
283 &ours, "ours", &theirs, "theirs",
284 state->istate, &ll_opts);
285 free(ancestor.ptr);
286 free(ours.ptr);
287 free(theirs.ptr);
288 if (merge_status == LL_MERGE_BINARY_CONFLICT)
289 warning("Cannot merge binary files: %s (%s vs. %s)",
290 path, "ours", "theirs");
291 if (merge_status < 0 || !result_buf.ptr) {
292 free(result_buf.ptr);
293 return error(_("path '%s': cannot merge"), path);
294 }
295
296 /*
297 * NEEDSWORK:
298 * There is absolutely no reason to write this as a blob object
299 * and create a phony cache entry. This hack is primarily to get
300 * to the write_entry() machinery that massages the contents to
301 * work-tree format and writes out which only allows it for a
302 * cache entry. The code in write_entry() needs to be refactored
303 * to allow us to feed a <buffer, size, mode> instead of a cache
304 * entry. Such a refactoring would help merge_recursive as well
305 * (it also writes the merge result to the object database even
306 * when it may contain conflicts).
307 */
308 if (write_object_file(result_buf.ptr, result_buf.size, OBJ_BLOB, &oid))
309 die(_("Unable to add merge result for '%s'"), path);
310 free(result_buf.ptr);
311 ce = make_transient_cache_entry(mode, &oid, path, 2, ce_mem_pool);
312 if (!ce)
313 die(_("make_cache_entry failed for path '%s'"), path);
314 status = checkout_entry(ce, state, NULL, nr_checkouts);
315 return status;
316 }
317
318 static void mark_ce_for_checkout_overlay(struct cache_entry *ce,
319 char *ps_matched,
320 const struct checkout_opts *opts)
321 {
322 ce->ce_flags &= ~CE_MATCHED;
323 if (!opts->ignore_skipworktree && ce_skip_worktree(ce))
324 return;
325 if (opts->source_tree && !(ce->ce_flags & CE_UPDATE))
326 /*
327 * "git checkout tree-ish -- path", but this entry
328 * is in the original index but is not in tree-ish
329 * or does not match the pathspec; it will not be
330 * checked out to the working tree. We will not do
331 * anything to this entry at all.
332 */
333 return;
334 /*
335 * Either this entry came from the tree-ish we are
336 * checking the paths out of, or we are checking out
337 * of the index.
338 *
339 * If it comes from the tree-ish, we already know it
340 * matches the pathspec and could just stamp
341 * CE_MATCHED to it from update_some(). But we still
342 * need ps_matched and read_tree (and
343 * eventually tree_entry_interesting) cannot fill
344 * ps_matched yet. Once it can, we can avoid calling
345 * match_pathspec() for _all_ entries when
346 * opts->source_tree != NULL.
347 */
348 if (ce_path_match(&the_index, ce, &opts->pathspec, ps_matched))
349 ce->ce_flags |= CE_MATCHED;
350 }
351
352 static void mark_ce_for_checkout_no_overlay(struct cache_entry *ce,
353 char *ps_matched,
354 const struct checkout_opts *opts)
355 {
356 ce->ce_flags &= ~CE_MATCHED;
357 if (!opts->ignore_skipworktree && ce_skip_worktree(ce))
358 return;
359 if (ce_path_match(&the_index, ce, &opts->pathspec, ps_matched)) {
360 ce->ce_flags |= CE_MATCHED;
361 if (opts->source_tree && !(ce->ce_flags & CE_UPDATE))
362 /*
363 * In overlay mode, but the path is not in
364 * tree-ish, which means we should remove it
365 * from the index and the working tree.
366 */
367 ce->ce_flags |= CE_REMOVE | CE_WT_REMOVE;
368 }
369 }
370
371 static int checkout_worktree(const struct checkout_opts *opts,
372 const struct branch_info *info)
373 {
374 struct checkout state = CHECKOUT_INIT;
375 int nr_checkouts = 0, nr_unmerged = 0;
376 int errs = 0;
377 int pos;
378 int pc_workers, pc_threshold;
379 struct mem_pool ce_mem_pool;
380
381 state.force = 1;
382 state.refresh_cache = 1;
383 state.istate = &the_index;
384
385 mem_pool_init(&ce_mem_pool, 0);
386 get_parallel_checkout_configs(&pc_workers, &pc_threshold);
387 init_checkout_metadata(&state.meta, info->refname,
388 info->commit ? &info->commit->object.oid : &info->oid,
389 NULL);
390
391 enable_delayed_checkout(&state);
392
393 if (pc_workers > 1)
394 init_parallel_checkout();
395
396 for (pos = 0; pos < the_index.cache_nr; pos++) {
397 struct cache_entry *ce = the_index.cache[pos];
398 if (ce->ce_flags & CE_MATCHED) {
399 if (!ce_stage(ce)) {
400 errs |= checkout_entry(ce, &state,
401 NULL, &nr_checkouts);
402 continue;
403 }
404 if (opts->writeout_stage)
405 errs |= checkout_stage(opts->writeout_stage,
406 ce, pos,
407 &state,
408 &nr_checkouts, opts->overlay_mode);
409 else if (opts->merge)
410 errs |= checkout_merged(pos, &state,
411 &nr_unmerged,
412 &ce_mem_pool);
413 pos = skip_same_name(ce, pos) - 1;
414 }
415 }
416 if (pc_workers > 1)
417 errs |= run_parallel_checkout(&state, pc_workers, pc_threshold,
418 NULL, NULL);
419 mem_pool_discard(&ce_mem_pool, should_validate_cache_entries());
420 remove_marked_cache_entries(&the_index, 1);
421 remove_scheduled_dirs();
422 errs |= finish_delayed_checkout(&state, opts->show_progress);
423
424 if (opts->count_checkout_paths) {
425 if (nr_unmerged)
426 fprintf_ln(stderr, Q_("Recreated %d merge conflict",
427 "Recreated %d merge conflicts",
428 nr_unmerged),
429 nr_unmerged);
430 if (opts->source_tree)
431 fprintf_ln(stderr, Q_("Updated %d path from %s",
432 "Updated %d paths from %s",
433 nr_checkouts),
434 nr_checkouts,
435 find_unique_abbrev(&opts->source_tree->object.oid,
436 DEFAULT_ABBREV));
437 else if (!nr_unmerged || nr_checkouts)
438 fprintf_ln(stderr, Q_("Updated %d path from the index",
439 "Updated %d paths from the index",
440 nr_checkouts),
441 nr_checkouts);
442 }
443
444 return errs;
445 }
446
447 static int checkout_paths(const struct checkout_opts *opts,
448 const struct branch_info *new_branch_info)
449 {
450 int pos;
451 static char *ps_matched;
452 struct object_id rev;
453 struct commit *head;
454 int errs = 0;
455 struct lock_file lock_file = LOCK_INIT;
456 int checkout_index;
457
458 trace2_cmd_mode(opts->patch_mode ? "patch" : "path");
459
460 if (opts->track != BRANCH_TRACK_UNSPECIFIED)
461 die(_("'%s' cannot be used with updating paths"), "--track");
462
463 if (opts->new_branch_log)
464 die(_("'%s' cannot be used with updating paths"), "-l");
465
466 if (opts->ignore_unmerged && opts->patch_mode)
467 die(_("'%s' cannot be used with updating paths"),
468 opts->ignore_unmerged_opt);
469
470 if (opts->force_detach)
471 die(_("'%s' cannot be used with updating paths"), "--detach");
472
473 if (opts->merge && opts->patch_mode)
474 die(_("options '%s' and '%s' cannot be used together"), "--merge", "--patch");
475
476 if (opts->ignore_unmerged && opts->merge)
477 die(_("options '%s' and '%s' cannot be used together"),
478 opts->ignore_unmerged_opt, "-m");
479
480 if (opts->new_branch)
481 die(_("Cannot update paths and switch to branch '%s' at the same time."),
482 opts->new_branch);
483
484 if (!opts->checkout_worktree && !opts->checkout_index)
485 die(_("neither '%s' or '%s' is specified"),
486 "--staged", "--worktree");
487
488 if (!opts->checkout_worktree && !opts->from_treeish)
489 die(_("'%s' must be used when '%s' is not specified"),
490 "--worktree", "--source");
491
492 if (opts->checkout_index && !opts->checkout_worktree &&
493 opts->writeout_stage)
494 die(_("'%s' or '%s' cannot be used with %s"),
495 "--ours", "--theirs", "--staged");
496
497 if (opts->checkout_index && !opts->checkout_worktree &&
498 opts->merge)
499 die(_("'%s' or '%s' cannot be used with %s"),
500 "--merge", "--conflict", "--staged");
501
502 if (opts->patch_mode) {
503 enum add_p_mode patch_mode;
504 const char *rev = new_branch_info->name;
505 char rev_oid[GIT_MAX_HEXSZ + 1];
506
507 /*
508 * Since rev can be in the form of `<a>...<b>` (which is not
509 * recognized by diff-index), we will always replace the name
510 * with the hex of the commit (whether it's in `...` form or
511 * not) for the run_add_interactive() machinery to work
512 * properly. However, there is special logic for the HEAD case
513 * so we mustn't replace that. Also, when we were given a
514 * tree-object, new_branch_info->commit would be NULL, but we
515 * do not have to do any replacement, either.
516 */
517 if (rev && new_branch_info->commit && strcmp(rev, "HEAD"))
518 rev = oid_to_hex_r(rev_oid, &new_branch_info->commit->object.oid);
519
520 if (opts->checkout_index && opts->checkout_worktree)
521 patch_mode = ADD_P_CHECKOUT;
522 else if (opts->checkout_index && !opts->checkout_worktree)
523 patch_mode = ADD_P_RESET;
524 else if (!opts->checkout_index && opts->checkout_worktree)
525 patch_mode = ADD_P_WORKTREE;
526 else
527 BUG("either flag must have been set, worktree=%d, index=%d",
528 opts->checkout_worktree, opts->checkout_index);
529 return !!run_add_p(the_repository, patch_mode, rev,
530 &opts->pathspec);
531 }
532
533 repo_hold_locked_index(the_repository, &lock_file, LOCK_DIE_ON_ERROR);
534 if (repo_read_index_preload(the_repository, &opts->pathspec, 0) < 0)
535 return error(_("index file corrupt"));
536
537 if (opts->source_tree)
538 read_tree_some(opts->source_tree, &opts->pathspec);
539
540 ps_matched = xcalloc(opts->pathspec.nr, 1);
541
542 /*
543 * Make sure all pathspecs participated in locating the paths
544 * to be checked out.
545 */
546 for (pos = 0; pos < the_index.cache_nr; pos++)
547 if (opts->overlay_mode)
548 mark_ce_for_checkout_overlay(the_index.cache[pos],
549 ps_matched,
550 opts);
551 else
552 mark_ce_for_checkout_no_overlay(the_index.cache[pos],
553 ps_matched,
554 opts);
555
556 if (report_path_error(ps_matched, &opts->pathspec)) {
557 free(ps_matched);
558 return 1;
559 }
560 free(ps_matched);
561
562 /* "checkout -m path" to recreate conflicted state */
563 if (opts->merge)
564 unmerge_marked_index(&the_index);
565
566 /* Any unmerged paths? */
567 for (pos = 0; pos < the_index.cache_nr; pos++) {
568 const struct cache_entry *ce = the_index.cache[pos];
569 if (ce->ce_flags & CE_MATCHED) {
570 if (!ce_stage(ce))
571 continue;
572 if (opts->ignore_unmerged) {
573 if (!opts->quiet)
574 warning(_("path '%s' is unmerged"), ce->name);
575 } else if (opts->writeout_stage) {
576 errs |= check_stage(opts->writeout_stage, ce, pos, opts->overlay_mode);
577 } else if (opts->merge) {
578 errs |= check_stages((1<<2) | (1<<3), ce, pos);
579 } else {
580 errs = 1;
581 error(_("path '%s' is unmerged"), ce->name);
582 }
583 pos = skip_same_name(ce, pos) - 1;
584 }
585 }
586 if (errs)
587 return 1;
588
589 /* Now we are committed to check them out */
590 if (opts->checkout_worktree)
591 errs |= checkout_worktree(opts, new_branch_info);
592 else
593 remove_marked_cache_entries(&the_index, 1);
594
595 /*
596 * Allow updating the index when checking out from the index.
597 * This is to save new stat info.
598 */
599 if (opts->checkout_worktree && !opts->checkout_index && !opts->source_tree)
600 checkout_index = 1;
601 else
602 checkout_index = opts->checkout_index;
603
604 if (checkout_index) {
605 if (write_locked_index(&the_index, &lock_file, COMMIT_LOCK))
606 die(_("unable to write new index file"));
607 } else {
608 /*
609 * NEEDSWORK: if --worktree is not specified, we
610 * should save stat info of checked out files in the
611 * index to avoid the next (potentially costly)
612 * refresh. But it's a bit tricker to do...
613 */
614 rollback_lock_file(&lock_file);
615 }
616
617 read_ref_full("HEAD", 0, &rev, NULL);
618 head = lookup_commit_reference_gently(the_repository, &rev, 1);
619
620 errs |= post_checkout_hook(head, head, 0);
621 return errs;
622 }
623
624 static void show_local_changes(struct object *head,
625 const struct diff_options *opts)
626 {
627 struct rev_info rev;
628 /* I think we want full paths, even if we're in a subdirectory. */
629 repo_init_revisions(the_repository, &rev, NULL);
630 rev.diffopt.flags = opts->flags;
631 rev.diffopt.output_format |= DIFF_FORMAT_NAME_STATUS;
632 rev.diffopt.flags.recursive = 1;
633 diff_setup_done(&rev.diffopt);
634 add_pending_object(&rev, head, NULL);
635 run_diff_index(&rev, 0);
636 release_revisions(&rev);
637 }
638
639 static void describe_detached_head(const char *msg, struct commit *commit)
640 {
641 struct strbuf sb = STRBUF_INIT;
642
643 if (!parse_commit(commit))
644 pp_commit_easy(CMIT_FMT_ONELINE, commit, &sb);
645 if (print_sha1_ellipsis()) {
646 fprintf(stderr, "%s %s... %s\n", msg,
647 find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV), sb.buf);
648 } else {
649 fprintf(stderr, "%s %s %s\n", msg,
650 find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV), sb.buf);
651 }
652 strbuf_release(&sb);
653 }
654
655 static int reset_tree(struct tree *tree, const struct checkout_opts *o,
656 int worktree, int *writeout_error,
657 struct branch_info *info)
658 {
659 struct unpack_trees_options opts;
660 struct tree_desc tree_desc;
661
662 memset(&opts, 0, sizeof(opts));
663 opts.head_idx = -1;
664 opts.update = worktree;
665 opts.skip_unmerged = !worktree;
666 opts.reset = o->force ? UNPACK_RESET_OVERWRITE_UNTRACKED :
667 UNPACK_RESET_PROTECT_UNTRACKED;
668 opts.preserve_ignored = (!o->force && !o->overwrite_ignore);
669 opts.merge = 1;
670 opts.fn = oneway_merge;
671 opts.verbose_update = o->show_progress;
672 opts.src_index = &the_index;
673 opts.dst_index = &the_index;
674 init_checkout_metadata(&opts.meta, info->refname,
675 info->commit ? &info->commit->object.oid : null_oid(),
676 NULL);
677 parse_tree(tree);
678 init_tree_desc(&tree_desc, tree->buffer, tree->size);
679 switch (unpack_trees(1, &tree_desc, &opts)) {
680 case -2:
681 *writeout_error = 1;
682 /*
683 * We return 0 nevertheless, as the index is all right
684 * and more importantly we have made best efforts to
685 * update paths in the work tree, and we cannot revert
686 * them.
687 */
688 /* fallthrough */
689 case 0:
690 return 0;
691 default:
692 return 128;
693 }
694 }
695
696 static void setup_branch_path(struct branch_info *branch)
697 {
698 struct strbuf buf = STRBUF_INIT;
699
700 /*
701 * If this is a ref, resolve it; otherwise, look up the OID for our
702 * expression. Failure here is okay.
703 */
704 if (!dwim_ref(branch->name, strlen(branch->name), &branch->oid, &branch->refname, 0))
705 repo_get_oid_committish(the_repository, branch->name, &branch->oid);
706
707 strbuf_branchname(&buf, branch->name, INTERPRET_BRANCH_LOCAL);
708 if (strcmp(buf.buf, branch->name)) {
709 free(branch->name);
710 branch->name = xstrdup(buf.buf);
711 }
712 strbuf_splice(&buf, 0, 0, "refs/heads/", 11);
713 free(branch->path);
714 branch->path = strbuf_detach(&buf, NULL);
715 }
716
717 static void init_topts(struct unpack_trees_options *topts, int merge,
718 int show_progress, int overwrite_ignore,
719 struct commit *old_commit)
720 {
721 memset(topts, 0, sizeof(*topts));
722 topts->head_idx = -1;
723 topts->src_index = &the_index;
724 topts->dst_index = &the_index;
725
726 setup_unpack_trees_porcelain(topts, "checkout");
727
728 topts->initial_checkout = is_index_unborn(&the_index);
729 topts->update = 1;
730 topts->merge = 1;
731 topts->quiet = merge && old_commit;
732 topts->verbose_update = show_progress;
733 topts->fn = twoway_merge;
734 topts->preserve_ignored = !overwrite_ignore;
735 }
736
737 static int merge_working_tree(const struct checkout_opts *opts,
738 struct branch_info *old_branch_info,
739 struct branch_info *new_branch_info,
740 int *writeout_error)
741 {
742 int ret;
743 struct lock_file lock_file = LOCK_INIT;
744 struct tree *new_tree;
745
746 repo_hold_locked_index(the_repository, &lock_file, LOCK_DIE_ON_ERROR);
747 if (repo_read_index_preload(the_repository, NULL, 0) < 0)
748 return error(_("index file corrupt"));
749
750 resolve_undo_clear_index(&the_index);
751 if (opts->new_orphan_branch && opts->orphan_from_empty_tree) {
752 if (new_branch_info->commit)
753 BUG("'switch --orphan' should never accept a commit as starting point");
754 new_tree = parse_tree_indirect(the_hash_algo->empty_tree);
755 } else
756 new_tree = get_commit_tree(new_branch_info->commit);
757 if (opts->discard_changes) {
758 ret = reset_tree(new_tree, opts, 1, writeout_error, new_branch_info);
759 if (ret)
760 return ret;
761 } else {
762 struct tree_desc trees[2];
763 struct tree *tree;
764 struct unpack_trees_options topts;
765 const struct object_id *old_commit_oid;
766
767 refresh_index(&the_index, REFRESH_QUIET, NULL, NULL, NULL);
768
769 if (unmerged_index(&the_index)) {
770 error(_("you need to resolve your current index first"));
771 return 1;
772 }
773
774 /* 2-way merge to the new branch */
775 init_topts(&topts, opts->merge, opts->show_progress,
776 opts->overwrite_ignore, old_branch_info->commit);
777 init_checkout_metadata(&topts.meta, new_branch_info->refname,
778 new_branch_info->commit ?
779 &new_branch_info->commit->object.oid :
780 &new_branch_info->oid, NULL);
781
782 old_commit_oid = old_branch_info->commit ?
783 &old_branch_info->commit->object.oid :
784 the_hash_algo->empty_tree;
785 tree = parse_tree_indirect(old_commit_oid);
786 if (!tree)
787 die(_("unable to parse commit %s"),
788 oid_to_hex(old_commit_oid));
789
790 init_tree_desc(&trees[0], tree->buffer, tree->size);
791 parse_tree(new_tree);
792 tree = new_tree;
793 init_tree_desc(&trees[1], tree->buffer, tree->size);
794
795 ret = unpack_trees(2, trees, &topts);
796 clear_unpack_trees_porcelain(&topts);
797 if (ret == -1) {
798 /*
799 * Unpack couldn't do a trivial merge; either
800 * give up or do a real merge, depending on
801 * whether the merge flag was used.
802 */
803 struct tree *work;
804 struct tree *old_tree;
805 struct merge_options o;
806 struct strbuf sb = STRBUF_INIT;
807 struct strbuf old_commit_shortname = STRBUF_INIT;
808
809 if (!opts->merge)
810 return 1;
811
812 /*
813 * Without old_branch_info->commit, the below is the same as
814 * the two-tree unpack we already tried and failed.
815 */
816 if (!old_branch_info->commit)
817 return 1;
818 old_tree = get_commit_tree(old_branch_info->commit);
819
820 if (repo_index_has_changes(the_repository, old_tree, &sb))
821 die(_("cannot continue with staged changes in "
822 "the following files:\n%s"), sb.buf);
823 strbuf_release(&sb);
824
825 /* Do more real merge */
826
827 /*
828 * We update the index fully, then write the
829 * tree from the index, then merge the new
830 * branch with the current tree, with the old
831 * branch as the base. Then we reset the index
832 * (but not the working tree) to the new
833 * branch, leaving the working tree as the
834 * merged version, but skipping unmerged
835 * entries in the index.
836 */
837
838 add_files_to_cache(NULL, NULL, 0);
839 init_merge_options(&o, the_repository);
840 o.verbosity = 0;
841 work = write_in_core_index_as_tree(the_repository);
842
843 ret = reset_tree(new_tree,
844 opts, 1,
845 writeout_error, new_branch_info);
846 if (ret)
847 return ret;
848 o.ancestor = old_branch_info->name;
849 if (!old_branch_info->name) {
850 strbuf_add_unique_abbrev(&old_commit_shortname,
851 &old_branch_info->commit->object.oid,
852 DEFAULT_ABBREV);
853 o.ancestor = old_commit_shortname.buf;
854 }
855 o.branch1 = new_branch_info->name;
856 o.branch2 = "local";
857 ret = merge_trees(&o,
858 new_tree,
859 work,
860 old_tree);
861 if (ret < 0)
862 exit(128);
863 ret = reset_tree(new_tree,
864 opts, 0,
865 writeout_error, new_branch_info);
866 strbuf_release(&o.obuf);
867 strbuf_release(&old_commit_shortname);
868 if (ret)
869 return ret;
870 }
871 }
872
873 if (!cache_tree_fully_valid(the_index.cache_tree))
874 cache_tree_update(&the_index, WRITE_TREE_SILENT | WRITE_TREE_REPAIR);
875
876 if (write_locked_index(&the_index, &lock_file, COMMIT_LOCK))
877 die(_("unable to write new index file"));
878
879 if (!opts->discard_changes && !opts->quiet && new_branch_info->commit)
880 show_local_changes(&new_branch_info->commit->object, &opts->diff_options);
881
882 return 0;
883 }
884
885 static void report_tracking(struct branch_info *new_branch_info)
886 {
887 struct strbuf sb = STRBUF_INIT;
888 struct branch *branch = branch_get(new_branch_info->name);
889
890 if (!format_tracking_info(branch, &sb, AHEAD_BEHIND_FULL))
891 return;
892 fputs(sb.buf, stdout);
893 strbuf_release(&sb);
894 }
895
896 static void update_refs_for_switch(const struct checkout_opts *opts,
897 struct branch_info *old_branch_info,
898 struct branch_info *new_branch_info)
899 {
900 struct strbuf msg = STRBUF_INIT;
901 const char *old_desc, *reflog_msg;
902 if (opts->new_branch) {
903 if (opts->new_orphan_branch) {
904 char *refname;
905
906 refname = mkpathdup("refs/heads/%s", opts->new_orphan_branch);
907 if (opts->new_branch_log &&
908 !should_autocreate_reflog(refname)) {
909 int ret;
910 struct strbuf err = STRBUF_INIT;
911
912 ret = safe_create_reflog(refname, &err);
913 if (ret) {
914 fprintf(stderr, _("Can not do reflog for '%s': %s\n"),
915 opts->new_orphan_branch, err.buf);
916 strbuf_release(&err);
917 free(refname);
918 return;
919 }
920 strbuf_release(&err);
921 }
922 free(refname);
923 }
924 else
925 create_branch(the_repository,
926 opts->new_branch, new_branch_info->name,
927 opts->new_branch_force ? 1 : 0,
928 opts->new_branch_force ? 1 : 0,
929 opts->new_branch_log,
930 opts->quiet,
931 opts->track,
932 0);
933 free(new_branch_info->name);
934 free(new_branch_info->refname);
935 new_branch_info->name = xstrdup(opts->new_branch);
936 setup_branch_path(new_branch_info);
937 }
938
939 old_desc = old_branch_info->name;
940 if (!old_desc && old_branch_info->commit)
941 old_desc = oid_to_hex(&old_branch_info->commit->object.oid);
942
943 reflog_msg = getenv("GIT_REFLOG_ACTION");
944 if (!reflog_msg)
945 strbuf_addf(&msg, "checkout: moving from %s to %s",
946 old_desc ? old_desc : "(invalid)", new_branch_info->name);
947 else
948 strbuf_insertstr(&msg, 0, reflog_msg);
949
950 if (!strcmp(new_branch_info->name, "HEAD") && !new_branch_info->path && !opts->force_detach) {
951 /* Nothing to do. */
952 } else if (opts->force_detach || !new_branch_info->path) { /* No longer on any branch. */
953 update_ref(msg.buf, "HEAD", &new_branch_info->commit->object.oid, NULL,
954 REF_NO_DEREF, UPDATE_REFS_DIE_ON_ERR);
955 if (!opts->quiet) {
956 if (old_branch_info->path &&
957 advice_enabled(ADVICE_DETACHED_HEAD) && !opts->force_detach)
958 detach_advice(new_branch_info->name);
959 describe_detached_head(_("HEAD is now at"), new_branch_info->commit);
960 }
961 } else if (new_branch_info->path) { /* Switch branches. */
962 if (create_symref("HEAD", new_branch_info->path, msg.buf) < 0)
963 die(_("unable to update HEAD"));
964 if (!opts->quiet) {
965 if (old_branch_info->path && !strcmp(new_branch_info->path, old_branch_info->path)) {
966 if (opts->new_branch_force)
967 fprintf(stderr, _("Reset branch '%s'\n"),
968 new_branch_info->name);
969 else
970 fprintf(stderr, _("Already on '%s'\n"),
971 new_branch_info->name);
972 } else if (opts->new_branch) {
973 if (opts->branch_exists)
974 fprintf(stderr, _("Switched to and reset branch '%s'\n"), new_branch_info->name);
975 else
976 fprintf(stderr, _("Switched to a new branch '%s'\n"), new_branch_info->name);
977 } else {
978 fprintf(stderr, _("Switched to branch '%s'\n"),
979 new_branch_info->name);
980 }
981 }
982 if (old_branch_info->path && old_branch_info->name) {
983 if (!ref_exists(old_branch_info->path) && reflog_exists(old_branch_info->path))
984 delete_reflog(old_branch_info->path);
985 }
986 }
987 remove_branch_state(the_repository, !opts->quiet);
988 strbuf_release(&msg);
989 if (!opts->quiet &&
990 (new_branch_info->path || (!opts->force_detach && !strcmp(new_branch_info->name, "HEAD"))))
991 report_tracking(new_branch_info);
992 }
993
994 static int add_pending_uninteresting_ref(const char *refname,
995 const struct object_id *oid,
996 int flags UNUSED, void *cb_data)
997 {
998 add_pending_oid(cb_data, refname, oid, UNINTERESTING);
999 return 0;
1000 }
1001
1002 static void describe_one_orphan(struct strbuf *sb, struct commit *commit)
1003 {
1004 strbuf_addstr(sb, " ");
1005 strbuf_add_unique_abbrev(sb, &commit->object.oid, DEFAULT_ABBREV);
1006 strbuf_addch(sb, ' ');
1007 if (!parse_commit(commit))
1008 pp_commit_easy(CMIT_FMT_ONELINE, commit, sb);
1009 strbuf_addch(sb, '\n');
1010 }
1011
1012 #define ORPHAN_CUTOFF 4
1013 static void suggest_reattach(struct commit *commit, struct rev_info *revs)
1014 {
1015 struct commit *c, *last = NULL;
1016 struct strbuf sb = STRBUF_INIT;
1017 int lost = 0;
1018 while ((c = get_revision(revs)) != NULL) {
1019 if (lost < ORPHAN_CUTOFF)
1020 describe_one_orphan(&sb, c);
1021 last = c;
1022 lost++;
1023 }
1024 if (ORPHAN_CUTOFF < lost) {
1025 int more = lost - ORPHAN_CUTOFF;
1026 if (more == 1)
1027 describe_one_orphan(&sb, last);
1028 else
1029 strbuf_addf(&sb, _(" ... and %d more.\n"), more);
1030 }
1031
1032 fprintf(stderr,
1033 Q_(
1034 /* The singular version */
1035 "Warning: you are leaving %d commit behind, "
1036 "not connected to\n"
1037 "any of your branches:\n\n"
1038 "%s\n",
1039 /* The plural version */
1040 "Warning: you are leaving %d commits behind, "
1041 "not connected to\n"
1042 "any of your branches:\n\n"
1043 "%s\n",
1044 /* Give ngettext() the count */
1045 lost),
1046 lost,
1047 sb.buf);
1048 strbuf_release(&sb);
1049
1050 if (advice_enabled(ADVICE_DETACHED_HEAD))
1051 fprintf(stderr,
1052 Q_(
1053 /* The singular version */
1054 "If you want to keep it by creating a new branch, "
1055 "this may be a good time\nto do so with:\n\n"
1056 " git branch <new-branch-name> %s\n\n",
1057 /* The plural version */
1058 "If you want to keep them by creating a new branch, "
1059 "this may be a good time\nto do so with:\n\n"
1060 " git branch <new-branch-name> %s\n\n",
1061 /* Give ngettext() the count */
1062 lost),
1063 find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV));
1064 }
1065
1066 /*
1067 * We are about to leave commit that was at the tip of a detached
1068 * HEAD. If it is not reachable from any ref, this is the last chance
1069 * for the user to do so without resorting to reflog.
1070 */
1071 static void orphaned_commit_warning(struct commit *old_commit, struct commit *new_commit)
1072 {
1073 struct rev_info revs;
1074 struct object *object = &old_commit->object;
1075
1076 repo_init_revisions(the_repository, &revs, NULL);
1077 setup_revisions(0, NULL, &revs, NULL);
1078
1079 object->flags &= ~UNINTERESTING;
1080 add_pending_object(&revs, object, oid_to_hex(&object->oid));
1081
1082 for_each_ref(add_pending_uninteresting_ref, &revs);
1083 if (new_commit)
1084 add_pending_oid(&revs, "HEAD",
1085 &new_commit->object.oid,
1086 UNINTERESTING);
1087
1088 if (prepare_revision_walk(&revs))
1089 die(_("internal error in revision walk"));
1090 if (!(old_commit->object.flags & UNINTERESTING))
1091 suggest_reattach(old_commit, &revs);
1092 else
1093 describe_detached_head(_("Previous HEAD position was"), old_commit);
1094
1095 /* Clean up objects used, as they will be reused. */
1096 repo_clear_commit_marks(the_repository, ALL_REV_FLAGS);
1097 release_revisions(&revs);
1098 }
1099
1100 static int switch_branches(const struct checkout_opts *opts,
1101 struct branch_info *new_branch_info)
1102 {
1103 int ret = 0;
1104 struct branch_info old_branch_info = { 0 };
1105 struct object_id rev;
1106 int flag, writeout_error = 0;
1107 int do_merge = 1;
1108
1109 trace2_cmd_mode("branch");
1110
1111 memset(&old_branch_info, 0, sizeof(old_branch_info));
1112 old_branch_info.path = resolve_refdup("HEAD", 0, &rev, &flag);
1113 if (old_branch_info.path)
1114 old_branch_info.commit = lookup_commit_reference_gently(the_repository, &rev, 1);
1115 if (!(flag & REF_ISSYMREF))
1116 FREE_AND_NULL(old_branch_info.path);
1117
1118 if (old_branch_info.path) {
1119 const char *const prefix = "refs/heads/";
1120 const char *p;
1121 if (skip_prefix(old_branch_info.path, prefix, &p))
1122 old_branch_info.name = xstrdup(p);
1123 }
1124
1125 if (opts->new_orphan_branch && opts->orphan_from_empty_tree) {
1126 if (new_branch_info->name)
1127 BUG("'switch --orphan' should never accept a commit as starting point");
1128 new_branch_info->commit = NULL;
1129 new_branch_info->name = xstrdup("(empty)");
1130 do_merge = 1;
1131 }
1132
1133 if (!new_branch_info->name) {
1134 new_branch_info->name = xstrdup("HEAD");
1135 new_branch_info->commit = old_branch_info.commit;
1136 if (!new_branch_info->commit)
1137 die(_("You are on a branch yet to be born"));
1138 parse_commit_or_die(new_branch_info->commit);
1139
1140 if (opts->only_merge_on_switching_branches)
1141 do_merge = 0;
1142 }
1143
1144 if (do_merge) {
1145 ret = merge_working_tree(opts, &old_branch_info, new_branch_info, &writeout_error);
1146 if (ret) {
1147 branch_info_release(&old_branch_info);
1148 return ret;
1149 }
1150 }
1151
1152 if (!opts->quiet && !old_branch_info.path && old_branch_info.commit && new_branch_info->commit != old_branch_info.commit)
1153 orphaned_commit_warning(old_branch_info.commit, new_branch_info->commit);
1154
1155 update_refs_for_switch(opts, &old_branch_info, new_branch_info);
1156
1157 ret = post_checkout_hook(old_branch_info.commit, new_branch_info->commit, 1);
1158 branch_info_release(&old_branch_info);
1159
1160 return ret || writeout_error;
1161 }
1162
1163 static int git_checkout_config(const char *var, const char *value, void *cb)
1164 {
1165 struct checkout_opts *opts = cb;
1166
1167 if (!strcmp(var, "diff.ignoresubmodules")) {
1168 handle_ignore_submodules_arg(&opts->diff_options, value);
1169 return 0;
1170 }
1171 if (!strcmp(var, "checkout.guess")) {
1172 opts->dwim_new_local_branch = git_config_bool(var, value);
1173 return 0;
1174 }
1175
1176 if (starts_with(var, "submodule."))
1177 return git_default_submodule_config(var, value, NULL);
1178
1179 return git_xmerge_config(var, value, NULL);
1180 }
1181
1182 static void setup_new_branch_info_and_source_tree(
1183 struct branch_info *new_branch_info,
1184 struct checkout_opts *opts,
1185 struct object_id *rev,
1186 const char *arg)
1187 {
1188 struct tree **source_tree = &opts->source_tree;
1189 struct object_id branch_rev;
1190
1191 new_branch_info->name = xstrdup(arg);
1192 setup_branch_path(new_branch_info);
1193
1194 if (!check_refname_format(new_branch_info->path, 0) &&
1195 !read_ref(new_branch_info->path, &branch_rev))
1196 oidcpy(rev, &branch_rev);
1197 else
1198 /* not an existing branch */
1199 FREE_AND_NULL(new_branch_info->path);
1200
1201 new_branch_info->commit = lookup_commit_reference_gently(the_repository, rev, 1);
1202 if (!new_branch_info->commit) {
1203 /* not a commit */
1204 *source_tree = parse_tree_indirect(rev);
1205 } else {
1206 parse_commit_or_die(new_branch_info->commit);
1207 *source_tree = get_commit_tree(new_branch_info->commit);
1208 }
1209 }
1210
1211 static const char *parse_remote_branch(const char *arg,
1212 struct object_id *rev,
1213 int could_be_checkout_paths)
1214 {
1215 int num_matches = 0;
1216 const char *remote = unique_tracking_name(arg, rev, &num_matches);
1217
1218 if (remote && could_be_checkout_paths) {
1219 die(_("'%s' could be both a local file and a tracking branch.\n"
1220 "Please use -- (and optionally --no-guess) to disambiguate"),
1221 arg);
1222 }
1223
1224 if (!remote && num_matches > 1) {
1225 if (advice_enabled(ADVICE_CHECKOUT_AMBIGUOUS_REMOTE_BRANCH_NAME)) {
1226 advise(_("If you meant to check out a remote tracking branch on, e.g. 'origin',\n"
1227 "you can do so by fully qualifying the name with the --track option:\n"
1228 "\n"
1229 " git checkout --track origin/<name>\n"
1230 "\n"
1231 "If you'd like to always have checkouts of an ambiguous <name> prefer\n"
1232 "one remote, e.g. the 'origin' remote, consider setting\n"
1233 "checkout.defaultRemote=origin in your config."));
1234 }
1235
1236 die(_("'%s' matched multiple (%d) remote tracking branches"),
1237 arg, num_matches);
1238 }
1239
1240 return remote;
1241 }
1242
1243 static int parse_branchname_arg(int argc, const char **argv,
1244 int dwim_new_local_branch_ok,
1245 struct branch_info *new_branch_info,
1246 struct checkout_opts *opts,
1247 struct object_id *rev)
1248 {
1249 const char **new_branch = &opts->new_branch;
1250 int argcount = 0;
1251 const char *arg;
1252 int dash_dash_pos;
1253 int has_dash_dash = 0;
1254 int i;
1255
1256 /*
1257 * case 1: git checkout <ref> -- [<paths>]
1258 *
1259 * <ref> must be a valid tree, everything after the '--' must be
1260 * a path.
1261 *
1262 * case 2: git checkout -- [<paths>]
1263 *
1264 * everything after the '--' must be paths.
1265 *
1266 * case 3: git checkout <something> [--]
1267 *
1268 * (a) If <something> is a commit, that is to
1269 * switch to the branch or detach HEAD at it. As a special case,
1270 * if <something> is A...B (missing A or B means HEAD but you can
1271 * omit at most one side), and if there is a unique merge base
1272 * between A and B, A...B names that merge base.
1273 *
1274 * (b) If <something> is _not_ a commit, either "--" is present
1275 * or <something> is not a path, no -t or -b was given,
1276 * and there is a tracking branch whose name is <something>
1277 * in one and only one remote (or if the branch exists on the
1278 * remote named in checkout.defaultRemote), then this is a
1279 * short-hand to fork local <something> from that
1280 * remote-tracking branch.
1281 *
1282 * (c) Otherwise, if "--" is present, treat it like case (1).
1283 *
1284 * (d) Otherwise :
1285 * - if it's a reference, treat it like case (1)
1286 * - else if it's a path, treat it like case (2)
1287 * - else: fail.
1288 *
1289 * case 4: git checkout <something> <paths>
1290 *
1291 * The first argument must not be ambiguous.
1292 * - If it's *only* a reference, treat it like case (1).
1293 * - If it's only a path, treat it like case (2).
1294 * - else: fail.
1295 *
1296 */
1297 if (!argc)
1298 return 0;
1299
1300 if (!opts->accept_pathspec) {
1301 if (argc > 1)
1302 die(_("only one reference expected"));
1303 has_dash_dash = 1; /* helps disambiguate */
1304 }
1305
1306 arg = argv[0];
1307 dash_dash_pos = -1;
1308 for (i = 0; i < argc; i++) {
1309 if (opts->accept_pathspec && !strcmp(argv[i], "--")) {
1310 dash_dash_pos = i;
1311 break;
1312 }
1313 }
1314 if (dash_dash_pos == 0)
1315 return 1; /* case (2) */
1316 else if (dash_dash_pos == 1)
1317 has_dash_dash = 1; /* case (3) or (1) */
1318 else if (dash_dash_pos >= 2)
1319 die(_("only one reference expected, %d given."), dash_dash_pos);
1320 opts->count_checkout_paths = !opts->quiet && !has_dash_dash;
1321
1322 if (!strcmp(arg, "-"))
1323 arg = "@{-1}";
1324
1325 if (get_oid_mb(arg, rev)) {
1326 /*
1327 * Either case (3) or (4), with <something> not being
1328 * a commit, or an attempt to use case (1) with an
1329 * invalid ref.
1330 *
1331 * It's likely an error, but we need to find out if
1332 * we should auto-create the branch, case (3).(b).
1333 */
1334 int recover_with_dwim = dwim_new_local_branch_ok;
1335
1336 int could_be_checkout_paths = !has_dash_dash &&
1337 check_filename(opts->prefix, arg);
1338
1339 if (!has_dash_dash && !no_wildcard(arg))
1340 recover_with_dwim = 0;
1341
1342 /*
1343 * Accept "git checkout foo", "git checkout foo --"
1344 * and "git switch foo" as candidates for dwim.
1345 */
1346 if (!(argc == 1 && !has_dash_dash) &&
1347 !(argc == 2 && has_dash_dash) &&
1348 opts->accept_pathspec)
1349 recover_with_dwim = 0;
1350
1351 if (recover_with_dwim) {
1352 const char *remote = parse_remote_branch(arg, rev,
1353 could_be_checkout_paths);
1354 if (remote) {
1355 *new_branch = arg;
1356 arg = remote;
1357 /* DWIMmed to create local branch, case (3).(b) */
1358 } else {
1359 recover_with_dwim = 0;
1360 }
1361 }
1362
1363 if (!recover_with_dwim) {
1364 if (has_dash_dash)
1365 die(_("invalid reference: %s"), arg);
1366 return argcount;
1367 }
1368 }
1369
1370 /* we can't end up being in (2) anymore, eat the argument */
1371 argcount++;
1372 argv++;
1373 argc--;
1374
1375 setup_new_branch_info_and_source_tree(new_branch_info, opts, rev, arg);
1376
1377 if (!opts->source_tree) /* case (1): want a tree */
1378 die(_("reference is not a tree: %s"), arg);
1379
1380 if (!has_dash_dash) { /* case (3).(d) -> (1) */
1381 /*
1382 * Do not complain the most common case
1383 * git checkout branch
1384 * even if there happen to be a file called 'branch';
1385 * it would be extremely annoying.
1386 */
1387 if (argc)
1388 verify_non_filename(opts->prefix, arg);
1389 } else if (opts->accept_pathspec) {
1390 argcount++;
1391 argv++;
1392 argc--;
1393 }
1394
1395 return argcount;
1396 }
1397
1398 static int switch_unborn_to_new_branch(const struct checkout_opts *opts)
1399 {
1400 int status;
1401 struct strbuf branch_ref = STRBUF_INIT;
1402
1403 trace2_cmd_mode("unborn");
1404
1405 if (!opts->new_branch)
1406 die(_("You are on a branch yet to be born"));
1407 strbuf_addf(&branch_ref, "refs/heads/%s", opts->new_branch);
1408 status = create_symref("HEAD", branch_ref.buf, "checkout -b");
1409 strbuf_release(&branch_ref);
1410 if (!opts->quiet)
1411 fprintf(stderr, _("Switched to a new branch '%s'\n"),
1412 opts->new_branch);
1413 return status;
1414 }
1415
1416 static void die_expecting_a_branch(const struct branch_info *branch_info)
1417 {
1418 struct object_id oid;
1419 char *to_free;
1420 int code;
1421
1422 if (dwim_ref(branch_info->name, strlen(branch_info->name), &oid, &to_free, 0) == 1) {
1423 const char *ref = to_free;
1424
1425 if (skip_prefix(ref, "refs/tags/", &ref))
1426 code = die_message(_("a branch is expected, got tag '%s'"), ref);
1427 else if (skip_prefix(ref, "refs/remotes/", &ref))
1428 code = die_message(_("a branch is expected, got remote branch '%s'"), ref);
1429 else
1430 code = die_message(_("a branch is expected, got '%s'"), ref);
1431 }
1432 else if (branch_info->commit)
1433 code = die_message(_("a branch is expected, got commit '%s'"), branch_info->name);
1434 else
1435 /*
1436 * This case should never happen because we already die() on
1437 * non-commit, but just in case.
1438 */
1439 code = die_message(_("a branch is expected, got '%s'"), branch_info->name);
1440
1441 if (advice_enabled(ADVICE_SUGGEST_DETACHING_HEAD))
1442 advise(_("If you want to detach HEAD at the commit, try again with the --detach option."));
1443
1444 exit(code);
1445 }
1446
1447 static void die_if_some_operation_in_progress(void)
1448 {
1449 struct wt_status_state state;
1450
1451 memset(&state, 0, sizeof(state));
1452 wt_status_get_state(the_repository, &state, 0);
1453
1454 if (state.merge_in_progress)
1455 die(_("cannot switch branch while merging\n"
1456 "Consider \"git merge --quit\" "
1457 "or \"git worktree add\"."));
1458 if (state.am_in_progress)
1459 die(_("cannot switch branch in the middle of an am session\n"
1460 "Consider \"git am --quit\" "
1461 "or \"git worktree add\"."));
1462 if (state.rebase_interactive_in_progress || state.rebase_in_progress)
1463 die(_("cannot switch branch while rebasing\n"
1464 "Consider \"git rebase --quit\" "
1465 "or \"git worktree add\"."));
1466 if (state.cherry_pick_in_progress)
1467 die(_("cannot switch branch while cherry-picking\n"
1468 "Consider \"git cherry-pick --quit\" "
1469 "or \"git worktree add\"."));
1470 if (state.revert_in_progress)
1471 die(_("cannot switch branch while reverting\n"
1472 "Consider \"git revert --quit\" "
1473 "or \"git worktree add\"."));
1474 if (state.bisect_in_progress)
1475 warning(_("you are switching branch while bisecting"));
1476
1477 wt_status_state_free_buffers(&state);
1478 }
1479
1480 static int checkout_branch(struct checkout_opts *opts,
1481 struct branch_info *new_branch_info)
1482 {
1483 if (opts->pathspec.nr)
1484 die(_("paths cannot be used with switching branches"));
1485
1486 if (opts->patch_mode)
1487 die(_("'%s' cannot be used with switching branches"),
1488 "--patch");
1489
1490 if (opts->overlay_mode != -1)
1491 die(_("'%s' cannot be used with switching branches"),
1492 "--[no]-overlay");
1493
1494 if (opts->writeout_stage)
1495 die(_("'%s' cannot be used with switching branches"),
1496 "--ours/--theirs");
1497
1498 if (opts->force && opts->merge)
1499 die(_("'%s' cannot be used with '%s'"), "-f", "-m");
1500
1501 if (opts->discard_changes && opts->merge)
1502 die(_("'%s' cannot be used with '%s'"), "--discard-changes", "--merge");
1503
1504 if (opts->force_detach && opts->new_branch)
1505 die(_("'%s' cannot be used with '%s'"),
1506 "--detach", "-b/-B/--orphan");
1507
1508 if (opts->new_orphan_branch) {
1509 if (opts->track != BRANCH_TRACK_UNSPECIFIED)
1510 die(_("'%s' cannot be used with '%s'"), "--orphan", "-t");
1511 if (opts->orphan_from_empty_tree && new_branch_info->name)
1512 die(_("'%s' cannot take <start-point>"), "--orphan");
1513 } else if (opts->force_detach) {
1514 if (opts->track != BRANCH_TRACK_UNSPECIFIED)
1515 die(_("'%s' cannot be used with '%s'"), "--detach", "-t");
1516 } else if (opts->track == BRANCH_TRACK_UNSPECIFIED)
1517 opts->track = git_branch_track;
1518
1519 if (new_branch_info->name && !new_branch_info->commit)
1520 die(_("Cannot switch branch to a non-commit '%s'"),
1521 new_branch_info->name);
1522
1523 if (!opts->switch_branch_doing_nothing_is_ok &&
1524 !new_branch_info->name &&
1525 !opts->new_branch &&
1526 !opts->force_detach)
1527 die(_("missing branch or commit argument"));
1528
1529 if (!opts->implicit_detach &&
1530 !opts->force_detach &&
1531 !opts->new_branch &&
1532 !opts->new_branch_force &&
1533 new_branch_info->name &&
1534 !new_branch_info->path)
1535 die_expecting_a_branch(new_branch_info);
1536
1537 if (!opts->can_switch_when_in_progress)
1538 die_if_some_operation_in_progress();
1539
1540 if (new_branch_info->path && !opts->force_detach && !opts->new_branch &&
1541 !opts->ignore_other_worktrees) {
1542 int flag;
1543 char *head_ref = resolve_refdup("HEAD", 0, NULL, &flag);
1544 if (head_ref &&
1545 (!(flag & REF_ISSYMREF) || strcmp(head_ref, new_branch_info->path)))
1546 die_if_checked_out(new_branch_info->path, 1);
1547 free(head_ref);
1548 }
1549
1550 if (!new_branch_info->commit && opts->new_branch) {
1551 struct object_id rev;
1552 int flag;
1553
1554 if (!read_ref_full("HEAD", 0, &rev, &flag) &&
1555 (flag & REF_ISSYMREF) && is_null_oid(&rev))
1556 return switch_unborn_to_new_branch(opts);
1557 }
1558 return switch_branches(opts, new_branch_info);
1559 }
1560
1561 static struct option *add_common_options(struct checkout_opts *opts,
1562 struct option *prevopts)
1563 {
1564 struct option options[] = {
1565 OPT__QUIET(&opts->quiet, N_("suppress progress reporting")),
1566 OPT_CALLBACK_F(0, "recurse-submodules", NULL,
1567 "checkout", "control recursive updating of submodules",
1568 PARSE_OPT_OPTARG, option_parse_recurse_submodules_worktree_updater),
1569 OPT_BOOL(0, "progress", &opts->show_progress, N_("force progress reporting")),
1570 OPT_BOOL('m', "merge", &opts->merge, N_("perform a 3-way merge with the new branch")),
1571 OPT_STRING(0, "conflict", &opts->conflict_style, N_("style"),
1572 N_("conflict style (merge, diff3, or zdiff3)")),
1573 OPT_END()
1574 };
1575 struct option *newopts = parse_options_concat(prevopts, options);
1576 free(prevopts);
1577 return newopts;
1578 }
1579
1580 static struct option *add_common_switch_branch_options(
1581 struct checkout_opts *opts, struct option *prevopts)
1582 {
1583 struct option options[] = {
1584 OPT_BOOL('d', "detach", &opts->force_detach, N_("detach HEAD at named commit")),
1585 OPT_CALLBACK_F('t', "track", &opts->track, "(direct|inherit)",
1586 N_("set branch tracking configuration"),
1587 PARSE_OPT_OPTARG,
1588 parse_opt_tracking_mode),
1589 OPT__FORCE(&opts->force, N_("force checkout (throw away local modifications)"),
1590 PARSE_OPT_NOCOMPLETE),
1591 OPT_STRING(0, "orphan", &opts->new_orphan_branch, N_("new-branch"), N_("new unparented branch")),
1592 OPT_BOOL_F(0, "overwrite-ignore", &opts->overwrite_ignore,
1593 N_("update ignored files (default)"),
1594 PARSE_OPT_NOCOMPLETE),
1595 OPT_BOOL(0, "ignore-other-worktrees", &opts->ignore_other_worktrees,
1596 N_("do not check if another worktree is holding the given ref")),
1597 OPT_END()
1598 };
1599 struct option *newopts = parse_options_concat(prevopts, options);
1600 free(prevopts);
1601 return newopts;
1602 }
1603
1604 static struct option *add_checkout_path_options(struct checkout_opts *opts,
1605 struct option *prevopts)
1606 {
1607 struct option options[] = {
1608 OPT_SET_INT_F('2', "ours", &opts->writeout_stage,
1609 N_("checkout our version for unmerged files"),
1610 2, PARSE_OPT_NONEG),
1611 OPT_SET_INT_F('3', "theirs", &opts->writeout_stage,
1612 N_("checkout their version for unmerged files"),
1613 3, PARSE_OPT_NONEG),
1614 OPT_BOOL('p', "patch", &opts->patch_mode, N_("select hunks interactively")),
1615 OPT_BOOL(0, "ignore-skip-worktree-bits", &opts->ignore_skipworktree,
1616 N_("do not limit pathspecs to sparse entries only")),
1617 OPT_PATHSPEC_FROM_FILE(&opts->pathspec_from_file),
1618 OPT_PATHSPEC_FILE_NUL(&opts->pathspec_file_nul),
1619 OPT_END()
1620 };
1621 struct option *newopts = parse_options_concat(prevopts, options);
1622 free(prevopts);
1623 return newopts;
1624 }
1625
1626 /* create-branch option (either b or c) */
1627 static char cb_option = 'b';
1628
1629 static int checkout_main(int argc, const char **argv, const char *prefix,
1630 struct checkout_opts *opts, struct option *options,
1631 const char * const usagestr[],
1632 struct branch_info *new_branch_info)
1633 {
1634 int parseopt_flags = 0;
1635
1636 opts->overwrite_ignore = 1;
1637 opts->prefix = prefix;
1638 opts->show_progress = -1;
1639
1640 git_config(git_checkout_config, opts);
1641 if (the_repository->gitdir) {
1642 prepare_repo_settings(the_repository);
1643 the_repository->settings.command_requires_full_index = 0;
1644 }
1645
1646 opts->track = BRANCH_TRACK_UNSPECIFIED;
1647
1648 if (!opts->accept_pathspec && !opts->accept_ref)
1649 BUG("make up your mind, you need to take _something_");
1650 if (opts->accept_pathspec && opts->accept_ref)
1651 parseopt_flags = PARSE_OPT_KEEP_DASHDASH;
1652
1653 argc = parse_options(argc, argv, prefix, options,
1654 usagestr, parseopt_flags);
1655
1656 if (opts->show_progress < 0) {
1657 if (opts->quiet)
1658 opts->show_progress = 0;
1659 else
1660 opts->show_progress = isatty(2);
1661 }
1662
1663 if (opts->conflict_style) {
1664 opts->merge = 1; /* implied */
1665 git_xmerge_config("merge.conflictstyle", opts->conflict_style, NULL);
1666 }
1667 if (opts->force) {
1668 opts->discard_changes = 1;
1669 opts->ignore_unmerged_opt = "--force";
1670 opts->ignore_unmerged = 1;
1671 }
1672
1673 if ((!!opts->new_branch + !!opts->new_branch_force + !!opts->new_orphan_branch) > 1)
1674 die(_("options '-%c', '-%c', and '%s' cannot be used together"),
1675 cb_option, toupper(cb_option), "--orphan");
1676
1677 if (opts->overlay_mode == 1 && opts->patch_mode)
1678 die(_("options '%s' and '%s' cannot be used together"), "-p", "--overlay");
1679
1680 if (opts->checkout_index >= 0 || opts->checkout_worktree >= 0) {
1681 if (opts->checkout_index < 0)
1682 opts->checkout_index = 0;
1683 if (opts->checkout_worktree < 0)
1684 opts->checkout_worktree = 0;
1685 } else {
1686 if (opts->checkout_index < 0)
1687 opts->checkout_index = -opts->checkout_index - 1;
1688 if (opts->checkout_worktree < 0)
1689 opts->checkout_worktree = -opts->checkout_worktree - 1;
1690 }
1691 if (opts->checkout_index < 0 || opts->checkout_worktree < 0)
1692 BUG("these flags should be non-negative by now");
1693 /*
1694 * convenient shortcut: "git restore --staged [--worktree]" equals
1695 * "git restore --staged [--worktree] --source HEAD"
1696 */
1697 if (!opts->from_treeish && opts->checkout_index)
1698 opts->from_treeish = "HEAD";
1699
1700 /*
1701 * From here on, new_branch will contain the branch to be checked out,
1702 * and new_branch_force and new_orphan_branch will tell us which one of
1703 * -b/-B/-c/-C/--orphan is being used.
1704 */
1705 if (opts->new_branch_force)
1706 opts->new_branch = opts->new_branch_force;
1707
1708 if (opts->new_orphan_branch)
1709 opts->new_branch = opts->new_orphan_branch;
1710
1711 /* --track without -c/-C/-b/-B/--orphan should DWIM */
1712 if (opts->track != BRANCH_TRACK_UNSPECIFIED && !opts->new_branch) {
1713 const char *argv0 = argv[0];
1714 if (!argc || !strcmp(argv0, "--"))
1715 die(_("--track needs a branch name"));
1716 skip_prefix(argv0, "refs/", &argv0);
1717 skip_prefix(argv0, "remotes/", &argv0);
1718 argv0 = strchr(argv0, '/');
1719 if (!argv0 || !argv0[1])
1720 die(_("missing branch name; try -%c"), cb_option);
1721 opts->new_branch = argv0 + 1;
1722 }
1723
1724 /*
1725 * Extract branch name from command line arguments, so
1726 * all that is left is pathspecs.
1727 *
1728 * Handle
1729 *
1730 * 1) git checkout <tree> -- [<paths>]
1731 * 2) git checkout -- [<paths>]
1732 * 3) git checkout <something> [<paths>]
1733 *
1734 * including "last branch" syntax and DWIM-ery for names of
1735 * remote branches, erroring out for invalid or ambiguous cases.
1736 */
1737 if (argc && opts->accept_ref) {
1738 struct object_id rev;
1739 int dwim_ok =
1740 !opts->patch_mode &&
1741 opts->dwim_new_local_branch &&
1742 opts->track == BRANCH_TRACK_UNSPECIFIED &&
1743 !opts->new_branch;
1744 int n = parse_branchname_arg(argc, argv, dwim_ok,
1745 new_branch_info, opts, &rev);
1746 argv += n;
1747 argc -= n;
1748 } else if (!opts->accept_ref && opts->from_treeish) {
1749 struct object_id rev;
1750
1751 if (get_oid_mb(opts->from_treeish, &rev))
1752 die(_("could not resolve %s"), opts->from_treeish);
1753
1754 setup_new_branch_info_and_source_tree(new_branch_info,
1755 opts, &rev,
1756 opts->from_treeish);
1757
1758 if (!opts->source_tree)
1759 die(_("reference is not a tree: %s"), opts->from_treeish);
1760 }
1761
1762 if (argc) {
1763 parse_pathspec(&opts->pathspec, 0,
1764 opts->patch_mode ? PATHSPEC_PREFIX_ORIGIN : 0,
1765 prefix, argv);
1766
1767 if (!opts->pathspec.nr)
1768 die(_("invalid path specification"));
1769
1770 /*
1771 * Try to give more helpful suggestion.
1772 * new_branch && argc > 1 will be caught later.
1773 */
1774 if (opts->new_branch && argc == 1 && !new_branch_info->commit)
1775 die(_("'%s' is not a commit and a branch '%s' cannot be created from it"),
1776 argv[0], opts->new_branch);
1777
1778 if (opts->force_detach)
1779 die(_("git checkout: --detach does not take a path argument '%s'"),
1780 argv[0]);
1781 }
1782
1783 if (opts->pathspec_from_file) {
1784 if (opts->pathspec.nr)
1785 die(_("'%s' and pathspec arguments cannot be used together"), "--pathspec-from-file");
1786
1787 if (opts->force_detach)
1788 die(_("options '%s' and '%s' cannot be used together"), "--pathspec-from-file", "--detach");
1789
1790 if (opts->patch_mode)
1791 die(_("options '%s' and '%s' cannot be used together"), "--pathspec-from-file", "--patch");
1792
1793 parse_pathspec_file(&opts->pathspec, 0,
1794 0,
1795 prefix, opts->pathspec_from_file, opts->pathspec_file_nul);
1796 } else if (opts->pathspec_file_nul) {
1797 die(_("the option '%s' requires '%s'"), "--pathspec-file-nul", "--pathspec-from-file");
1798 }
1799
1800 opts->pathspec.recursive = 1;
1801
1802 if (opts->pathspec.nr) {
1803 if (1 < !!opts->writeout_stage + !!opts->force + !!opts->merge)
1804 die(_("git checkout: --ours/--theirs, --force and --merge are incompatible when\n"
1805 "checking out of the index."));
1806 } else {
1807 if (opts->accept_pathspec && !opts->empty_pathspec_ok &&
1808 !opts->patch_mode) /* patch mode is special */
1809 die(_("you must specify path(s) to restore"));
1810 }
1811
1812 if (opts->new_branch) {
1813 struct strbuf buf = STRBUF_INIT;
1814
1815 if (opts->new_branch_force)
1816 opts->branch_exists = validate_branchname(opts->new_branch, &buf);
1817 else
1818 opts->branch_exists =
1819 validate_new_branchname(opts->new_branch, &buf, 0);
1820 strbuf_release(&buf);
1821 }
1822
1823 if (opts->patch_mode || opts->pathspec.nr)
1824 return checkout_paths(opts, new_branch_info);
1825 else
1826 return checkout_branch(opts, new_branch_info);
1827 }
1828
1829 int cmd_checkout(int argc, const char **argv, const char *prefix)
1830 {
1831 struct checkout_opts opts;
1832 struct option *options;
1833 struct option checkout_options[] = {
1834 OPT_STRING('b', NULL, &opts.new_branch, N_("branch"),
1835 N_("create and checkout a new branch")),
1836 OPT_STRING('B', NULL, &opts.new_branch_force, N_("branch"),
1837 N_("create/reset and checkout a branch")),
1838 OPT_BOOL('l', NULL, &opts.new_branch_log, N_("create reflog for new branch")),
1839 OPT_BOOL(0, "guess", &opts.dwim_new_local_branch,
1840 N_("second guess 'git checkout <no-such-branch>' (default)")),
1841 OPT_BOOL(0, "overlay", &opts.overlay_mode, N_("use overlay mode (default)")),
1842 OPT_END()
1843 };
1844 int ret;
1845 struct branch_info new_branch_info = { 0 };
1846
1847 memset(&opts, 0, sizeof(opts));
1848 opts.dwim_new_local_branch = 1;
1849 opts.switch_branch_doing_nothing_is_ok = 1;
1850 opts.only_merge_on_switching_branches = 0;
1851 opts.accept_ref = 1;
1852 opts.accept_pathspec = 1;
1853 opts.implicit_detach = 1;
1854 opts.can_switch_when_in_progress = 1;
1855 opts.orphan_from_empty_tree = 0;
1856 opts.empty_pathspec_ok = 1;
1857 opts.overlay_mode = -1;
1858 opts.checkout_index = -2; /* default on */
1859 opts.checkout_worktree = -2; /* default on */
1860
1861 if (argc == 3 && !strcmp(argv[1], "-b")) {
1862 /*
1863 * User ran 'git checkout -b <branch>' and expects
1864 * the same behavior as 'git switch -c <branch>'.
1865 */
1866 opts.switch_branch_doing_nothing_is_ok = 0;
1867 opts.only_merge_on_switching_branches = 1;
1868 }
1869
1870 options = parse_options_dup(checkout_options);
1871 options = add_common_options(&opts, options);
1872 options = add_common_switch_branch_options(&opts, options);
1873 options = add_checkout_path_options(&opts, options);
1874
1875 ret = checkout_main(argc, argv, prefix, &opts,
1876 options, checkout_usage, &new_branch_info);
1877 branch_info_release(&new_branch_info);
1878 clear_pathspec(&opts.pathspec);
1879 FREE_AND_NULL(options);
1880 return ret;
1881 }
1882
1883 int cmd_switch(int argc, const char **argv, const char *prefix)
1884 {
1885 struct checkout_opts opts;
1886 struct option *options = NULL;
1887 struct option switch_options[] = {
1888 OPT_STRING('c', "create", &opts.new_branch, N_("branch"),
1889 N_("create and switch to a new branch")),
1890 OPT_STRING('C', "force-create", &opts.new_branch_force, N_("branch"),
1891 N_("create/reset and switch to a branch")),
1892 OPT_BOOL(0, "guess", &opts.dwim_new_local_branch,
1893 N_("second guess 'git switch <no-such-branch>'")),
1894 OPT_BOOL(0, "discard-changes", &opts.discard_changes,
1895 N_("throw away local modifications")),
1896 OPT_END()
1897 };
1898 int ret;
1899 struct branch_info new_branch_info = { 0 };
1900
1901 memset(&opts, 0, sizeof(opts));
1902 opts.dwim_new_local_branch = 1;
1903 opts.accept_ref = 1;
1904 opts.accept_pathspec = 0;
1905 opts.switch_branch_doing_nothing_is_ok = 0;
1906 opts.only_merge_on_switching_branches = 1;
1907 opts.implicit_detach = 0;
1908 opts.can_switch_when_in_progress = 0;
1909 opts.orphan_from_empty_tree = 1;
1910 opts.overlay_mode = -1;
1911
1912 options = parse_options_dup(switch_options);
1913 options = add_common_options(&opts, options);
1914 options = add_common_switch_branch_options(&opts, options);
1915
1916 cb_option = 'c';
1917
1918 ret = checkout_main(argc, argv, prefix, &opts,
1919 options, switch_branch_usage, &new_branch_info);
1920 branch_info_release(&new_branch_info);
1921 FREE_AND_NULL(options);
1922 return ret;
1923 }
1924
1925 int cmd_restore(int argc, const char **argv, const char *prefix)
1926 {
1927 struct checkout_opts opts;
1928 struct option *options;
1929 struct option restore_options[] = {
1930 OPT_STRING('s', "source", &opts.from_treeish, "<tree-ish>",
1931 N_("which tree-ish to checkout from")),
1932 OPT_BOOL('S', "staged", &opts.checkout_index,
1933 N_("restore the index")),
1934 OPT_BOOL('W', "worktree", &opts.checkout_worktree,
1935 N_("restore the working tree (default)")),
1936 OPT_BOOL(0, "ignore-unmerged", &opts.ignore_unmerged,
1937 N_("ignore unmerged entries")),
1938 OPT_BOOL(0, "overlay", &opts.overlay_mode, N_("use overlay mode")),
1939 OPT_END()
1940 };
1941 int ret;
1942 struct branch_info new_branch_info = { 0 };
1943
1944 memset(&opts, 0, sizeof(opts));
1945 opts.accept_ref = 0;
1946 opts.accept_pathspec = 1;
1947 opts.empty_pathspec_ok = 0;
1948 opts.overlay_mode = 0;
1949 opts.checkout_index = -1; /* default off */
1950 opts.checkout_worktree = -2; /* default on */
1951 opts.ignore_unmerged_opt = "--ignore-unmerged";
1952
1953 options = parse_options_dup(restore_options);
1954 options = add_common_options(&opts, options);
1955 options = add_checkout_path_options(&opts, options);
1956
1957 ret = checkout_main(argc, argv, prefix, &opts,
1958 options, restore_usage, &new_branch_info);
1959 branch_info_release(&new_branch_info);
1960 FREE_AND_NULL(options);
1961 return ret;
1962 }