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