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