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