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