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