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