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