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