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