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