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