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