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