Merge branch 'js/log-protocol-version'
[alt-git.git] / builtin / checkout.c
blobb5d477919a743885ab536608e86d28662ac3b615
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 #include "entry.h"
30 #include "parallel-checkout.h"
32 static const char * const checkout_usage[] = {
33 N_("git checkout [<options>] <branch>"),
34 N_("git checkout [<options>] [<branch>] -- <file>..."),
35 NULL,
38 static const char * const switch_branch_usage[] = {
39 N_("git switch [<options>] [<branch>]"),
40 NULL,
43 static const char * const restore_usage[] = {
44 N_("git restore [<options>] [--source=<branch>] <file>..."),
45 NULL,
48 struct checkout_opts {
49 int patch_mode;
50 int quiet;
51 int merge;
52 int force;
53 int force_detach;
54 int implicit_detach;
55 int writeout_stage;
56 int overwrite_ignore;
57 int ignore_skipworktree;
58 int ignore_other_worktrees;
59 int show_progress;
60 int count_checkout_paths;
61 int overlay_mode;
62 int dwim_new_local_branch;
63 int discard_changes;
64 int accept_ref;
65 int accept_pathspec;
66 int switch_branch_doing_nothing_is_ok;
67 int only_merge_on_switching_branches;
68 int can_switch_when_in_progress;
69 int orphan_from_empty_tree;
70 int empty_pathspec_ok;
71 int checkout_index;
72 int checkout_worktree;
73 const char *ignore_unmerged_opt;
74 int ignore_unmerged;
75 int pathspec_file_nul;
76 const char *pathspec_from_file;
78 const char *new_branch;
79 const char *new_branch_force;
80 const char *new_orphan_branch;
81 int new_branch_log;
82 enum branch_track track;
83 struct diff_options diff_options;
84 char *conflict_style;
86 int branch_exists;
87 const char *prefix;
88 struct pathspec pathspec;
89 const char *from_treeish;
90 struct tree *source_tree;
93 struct branch_info {
94 const char *name; /* The short name used */
95 const char *path; /* The full name of a real branch */
96 struct commit *commit; /* The named commit */
97 char *refname; /* The full name of the ref being checked out. */
98 struct object_id oid; /* The object ID of the commit being checked out. */
100 * if not null the branch is detached because it's already
101 * checked out in this checkout
103 char *checkout;
106 static int post_checkout_hook(struct commit *old_commit, struct commit *new_commit,
107 int changed)
109 return run_hook_le(NULL, "post-checkout",
110 oid_to_hex(old_commit ? &old_commit->object.oid : null_oid()),
111 oid_to_hex(new_commit ? &new_commit->object.oid : null_oid()),
112 changed ? "1" : "0", NULL);
113 /* "new_commit" can be NULL when checking out from the index before
114 a commit exists. */
118 static int update_some(const struct object_id *oid, struct strbuf *base,
119 const char *pathname, unsigned mode, void *context)
121 int len;
122 struct cache_entry *ce;
123 int pos;
125 if (S_ISDIR(mode))
126 return READ_TREE_RECURSIVE;
128 len = base->len + strlen(pathname);
129 ce = make_empty_cache_entry(&the_index, len);
130 oidcpy(&ce->oid, oid);
131 memcpy(ce->name, base->buf, base->len);
132 memcpy(ce->name + base->len, pathname, len - base->len);
133 ce->ce_flags = create_ce_flags(0) | CE_UPDATE;
134 ce->ce_namelen = len;
135 ce->ce_mode = create_ce_mode(mode);
138 * If the entry is the same as the current index, we can leave the old
139 * entry in place. Whether it is UPTODATE or not, checkout_entry will
140 * do the right thing.
142 pos = cache_name_pos(ce->name, ce->ce_namelen);
143 if (pos >= 0) {
144 struct cache_entry *old = active_cache[pos];
145 if (ce->ce_mode == old->ce_mode &&
146 !ce_intent_to_add(old) &&
147 oideq(&ce->oid, &old->oid)) {
148 old->ce_flags |= CE_UPDATE;
149 discard_cache_entry(ce);
150 return 0;
154 add_cache_entry(ce, ADD_CACHE_OK_TO_ADD | ADD_CACHE_OK_TO_REPLACE);
155 return 0;
158 static int read_tree_some(struct tree *tree, const struct pathspec *pathspec)
160 read_tree(the_repository, tree,
161 pathspec, update_some, NULL);
163 /* update the index with the given tree's info
164 * for all args, expanding wildcards, and exit
165 * with any non-zero return code.
167 return 0;
170 static int skip_same_name(const struct cache_entry *ce, int pos)
172 while (++pos < active_nr &&
173 !strcmp(active_cache[pos]->name, ce->name))
174 ; /* skip */
175 return pos;
178 static int check_stage(int stage, const struct cache_entry *ce, int pos,
179 int overlay_mode)
181 while (pos < active_nr &&
182 !strcmp(active_cache[pos]->name, ce->name)) {
183 if (ce_stage(active_cache[pos]) == stage)
184 return 0;
185 pos++;
187 if (!overlay_mode)
188 return 0;
189 if (stage == 2)
190 return error(_("path '%s' does not have our version"), ce->name);
191 else
192 return error(_("path '%s' does not have their version"), ce->name);
195 static int check_stages(unsigned stages, const struct cache_entry *ce, int pos)
197 unsigned seen = 0;
198 const char *name = ce->name;
200 while (pos < active_nr) {
201 ce = active_cache[pos];
202 if (strcmp(name, ce->name))
203 break;
204 seen |= (1 << ce_stage(ce));
205 pos++;
207 if ((stages & seen) != stages)
208 return error(_("path '%s' does not have all necessary versions"),
209 name);
210 return 0;
213 static int checkout_stage(int stage, const struct cache_entry *ce, int pos,
214 const struct checkout *state, int *nr_checkouts,
215 int overlay_mode)
217 while (pos < active_nr &&
218 !strcmp(active_cache[pos]->name, ce->name)) {
219 if (ce_stage(active_cache[pos]) == stage)
220 return checkout_entry(active_cache[pos], state,
221 NULL, nr_checkouts);
222 pos++;
224 if (!overlay_mode) {
225 unlink_entry(ce);
226 return 0;
228 if (stage == 2)
229 return error(_("path '%s' does not have our version"), ce->name);
230 else
231 return error(_("path '%s' does not have their version"), ce->name);
234 static int checkout_merged(int pos, const struct checkout *state,
235 int *nr_checkouts, struct mem_pool *ce_mem_pool)
237 struct cache_entry *ce = active_cache[pos];
238 const char *path = ce->name;
239 mmfile_t ancestor, ours, theirs;
240 int status;
241 struct object_id oid;
242 mmbuffer_t result_buf;
243 struct object_id threeway[3];
244 unsigned mode = 0;
245 struct ll_merge_options ll_opts;
246 int renormalize = 0;
248 memset(threeway, 0, sizeof(threeway));
249 while (pos < active_nr) {
250 int stage;
251 stage = ce_stage(ce);
252 if (!stage || strcmp(path, ce->name))
253 break;
254 oidcpy(&threeway[stage - 1], &ce->oid);
255 if (stage == 2)
256 mode = create_ce_mode(ce->ce_mode);
257 pos++;
258 ce = active_cache[pos];
260 if (is_null_oid(&threeway[1]) || is_null_oid(&threeway[2]))
261 return error(_("path '%s' does not have necessary versions"), path);
263 read_mmblob(&ancestor, &threeway[0]);
264 read_mmblob(&ours, &threeway[1]);
265 read_mmblob(&theirs, &threeway[2]);
267 memset(&ll_opts, 0, sizeof(ll_opts));
268 git_config_get_bool("merge.renormalize", &renormalize);
269 ll_opts.renormalize = renormalize;
270 status = ll_merge(&result_buf, path, &ancestor, "base",
271 &ours, "ours", &theirs, "theirs",
272 state->istate, &ll_opts);
273 free(ancestor.ptr);
274 free(ours.ptr);
275 free(theirs.ptr);
276 if (status < 0 || !result_buf.ptr) {
277 free(result_buf.ptr);
278 return error(_("path '%s': cannot merge"), path);
282 * NEEDSWORK:
283 * There is absolutely no reason to write this as a blob object
284 * and create a phony cache entry. This hack is primarily to get
285 * to the write_entry() machinery that massages the contents to
286 * work-tree format and writes out which only allows it for a
287 * cache entry. The code in write_entry() needs to be refactored
288 * to allow us to feed a <buffer, size, mode> instead of a cache
289 * entry. Such a refactoring would help merge_recursive as well
290 * (it also writes the merge result to the object database even
291 * when it may contain conflicts).
293 if (write_object_file(result_buf.ptr, result_buf.size, blob_type, &oid))
294 die(_("Unable to add merge result for '%s'"), path);
295 free(result_buf.ptr);
296 ce = make_transient_cache_entry(mode, &oid, path, 2, ce_mem_pool);
297 if (!ce)
298 die(_("make_cache_entry failed for path '%s'"), path);
299 status = checkout_entry(ce, state, NULL, nr_checkouts);
300 return status;
303 static void mark_ce_for_checkout_overlay(struct cache_entry *ce,
304 char *ps_matched,
305 const struct checkout_opts *opts)
307 ce->ce_flags &= ~CE_MATCHED;
308 if (!opts->ignore_skipworktree && ce_skip_worktree(ce))
309 return;
310 if (opts->source_tree && !(ce->ce_flags & CE_UPDATE))
312 * "git checkout tree-ish -- path", but this entry
313 * is in the original index but is not in tree-ish
314 * or does not match the pathspec; it will not be
315 * checked out to the working tree. We will not do
316 * anything to this entry at all.
318 return;
320 * Either this entry came from the tree-ish we are
321 * checking the paths out of, or we are checking out
322 * of the index.
324 * If it comes from the tree-ish, we already know it
325 * matches the pathspec and could just stamp
326 * CE_MATCHED to it from update_some(). But we still
327 * need ps_matched and read_tree (and
328 * eventually tree_entry_interesting) cannot fill
329 * ps_matched yet. Once it can, we can avoid calling
330 * match_pathspec() for _all_ entries when
331 * opts->source_tree != NULL.
333 if (ce_path_match(&the_index, ce, &opts->pathspec, ps_matched))
334 ce->ce_flags |= CE_MATCHED;
337 static void mark_ce_for_checkout_no_overlay(struct cache_entry *ce,
338 char *ps_matched,
339 const struct checkout_opts *opts)
341 ce->ce_flags &= ~CE_MATCHED;
342 if (!opts->ignore_skipworktree && ce_skip_worktree(ce))
343 return;
344 if (ce_path_match(&the_index, ce, &opts->pathspec, ps_matched)) {
345 ce->ce_flags |= CE_MATCHED;
346 if (opts->source_tree && !(ce->ce_flags & CE_UPDATE))
348 * In overlay mode, but the path is not in
349 * tree-ish, which means we should remove it
350 * from the index and the working tree.
352 ce->ce_flags |= CE_REMOVE | CE_WT_REMOVE;
356 static int checkout_worktree(const struct checkout_opts *opts,
357 const struct branch_info *info)
359 struct checkout state = CHECKOUT_INIT;
360 int nr_checkouts = 0, nr_unmerged = 0;
361 int errs = 0;
362 int pos;
363 int pc_workers, pc_threshold;
364 struct mem_pool ce_mem_pool;
366 state.force = 1;
367 state.refresh_cache = 1;
368 state.istate = &the_index;
370 mem_pool_init(&ce_mem_pool, 0);
371 get_parallel_checkout_configs(&pc_workers, &pc_threshold);
372 init_checkout_metadata(&state.meta, info->refname,
373 info->commit ? &info->commit->object.oid : &info->oid,
374 NULL);
376 enable_delayed_checkout(&state);
378 if (pc_workers > 1)
379 init_parallel_checkout();
381 for (pos = 0; pos < active_nr; pos++) {
382 struct cache_entry *ce = active_cache[pos];
383 if (ce->ce_flags & CE_MATCHED) {
384 if (!ce_stage(ce)) {
385 errs |= checkout_entry(ce, &state,
386 NULL, &nr_checkouts);
387 continue;
389 if (opts->writeout_stage)
390 errs |= checkout_stage(opts->writeout_stage,
391 ce, pos,
392 &state,
393 &nr_checkouts, opts->overlay_mode);
394 else if (opts->merge)
395 errs |= checkout_merged(pos, &state,
396 &nr_unmerged,
397 &ce_mem_pool);
398 pos = skip_same_name(ce, pos) - 1;
401 if (pc_workers > 1)
402 errs |= run_parallel_checkout(&state, pc_workers, pc_threshold,
403 NULL, NULL);
404 mem_pool_discard(&ce_mem_pool, should_validate_cache_entries());
405 remove_marked_cache_entries(&the_index, 1);
406 remove_scheduled_dirs();
407 errs |= finish_delayed_checkout(&state, &nr_checkouts);
409 if (opts->count_checkout_paths) {
410 if (nr_unmerged)
411 fprintf_ln(stderr, Q_("Recreated %d merge conflict",
412 "Recreated %d merge conflicts",
413 nr_unmerged),
414 nr_unmerged);
415 if (opts->source_tree)
416 fprintf_ln(stderr, Q_("Updated %d path from %s",
417 "Updated %d paths from %s",
418 nr_checkouts),
419 nr_checkouts,
420 find_unique_abbrev(&opts->source_tree->object.oid,
421 DEFAULT_ABBREV));
422 else if (!nr_unmerged || nr_checkouts)
423 fprintf_ln(stderr, Q_("Updated %d path from the index",
424 "Updated %d paths from the index",
425 nr_checkouts),
426 nr_checkouts);
429 return errs;
432 static int checkout_paths(const struct checkout_opts *opts,
433 const struct branch_info *new_branch_info)
435 int pos;
436 static char *ps_matched;
437 struct object_id rev;
438 struct commit *head;
439 int errs = 0;
440 struct lock_file lock_file = LOCK_INIT;
441 int checkout_index;
443 trace2_cmd_mode(opts->patch_mode ? "patch" : "path");
445 if (opts->track != BRANCH_TRACK_UNSPECIFIED)
446 die(_("'%s' cannot be used with updating paths"), "--track");
448 if (opts->new_branch_log)
449 die(_("'%s' cannot be used with updating paths"), "-l");
451 if (opts->ignore_unmerged && opts->patch_mode)
452 die(_("'%s' cannot be used with updating paths"),
453 opts->ignore_unmerged_opt);
455 if (opts->force_detach)
456 die(_("'%s' cannot be used with updating paths"), "--detach");
458 if (opts->merge && opts->patch_mode)
459 die(_("'%s' cannot be used with %s"), "--merge", "--patch");
461 if (opts->ignore_unmerged && opts->merge)
462 die(_("'%s' cannot be used with %s"),
463 opts->ignore_unmerged_opt, "-m");
465 if (opts->new_branch)
466 die(_("Cannot update paths and switch to branch '%s' at the same time."),
467 opts->new_branch);
469 if (!opts->checkout_worktree && !opts->checkout_index)
470 die(_("neither '%s' or '%s' is specified"),
471 "--staged", "--worktree");
473 if (!opts->checkout_worktree && !opts->from_treeish)
474 die(_("'%s' must be used when '%s' is not specified"),
475 "--worktree", "--source");
477 if (opts->checkout_index && !opts->checkout_worktree &&
478 opts->writeout_stage)
479 die(_("'%s' or '%s' cannot be used with %s"),
480 "--ours", "--theirs", "--staged");
482 if (opts->checkout_index && !opts->checkout_worktree &&
483 opts->merge)
484 die(_("'%s' or '%s' cannot be used with %s"),
485 "--merge", "--conflict", "--staged");
487 if (opts->patch_mode) {
488 const char *patch_mode;
489 const char *rev = new_branch_info->name;
490 char rev_oid[GIT_MAX_HEXSZ + 1];
493 * Since rev can be in the form of `<a>...<b>` (which is not
494 * recognized by diff-index), we will always replace the name
495 * with the hex of the commit (whether it's in `...` form or
496 * not) for the run_add_interactive() machinery to work
497 * properly. However, there is special logic for the HEAD case
498 * so we mustn't replace that. Also, when we were given a
499 * tree-object, new_branch_info->commit would be NULL, but we
500 * do not have to do any replacement, either.
502 if (rev && new_branch_info->commit && strcmp(rev, "HEAD"))
503 rev = oid_to_hex_r(rev_oid, &new_branch_info->commit->object.oid);
505 if (opts->checkout_index && opts->checkout_worktree)
506 patch_mode = "--patch=checkout";
507 else if (opts->checkout_index && !opts->checkout_worktree)
508 patch_mode = "--patch=reset";
509 else if (!opts->checkout_index && opts->checkout_worktree)
510 patch_mode = "--patch=worktree";
511 else
512 BUG("either flag must have been set, worktree=%d, index=%d",
513 opts->checkout_worktree, opts->checkout_index);
514 return run_add_interactive(rev, patch_mode, &opts->pathspec);
517 repo_hold_locked_index(the_repository, &lock_file, LOCK_DIE_ON_ERROR);
518 if (read_cache_preload(&opts->pathspec) < 0)
519 return error(_("index file corrupt"));
521 if (opts->source_tree)
522 read_tree_some(opts->source_tree, &opts->pathspec);
524 ps_matched = xcalloc(opts->pathspec.nr, 1);
527 * Make sure all pathspecs participated in locating the paths
528 * to be checked out.
530 for (pos = 0; pos < active_nr; pos++)
531 if (opts->overlay_mode)
532 mark_ce_for_checkout_overlay(active_cache[pos],
533 ps_matched,
534 opts);
535 else
536 mark_ce_for_checkout_no_overlay(active_cache[pos],
537 ps_matched,
538 opts);
540 if (report_path_error(ps_matched, &opts->pathspec)) {
541 free(ps_matched);
542 return 1;
544 free(ps_matched);
546 /* "checkout -m path" to recreate conflicted state */
547 if (opts->merge)
548 unmerge_marked_index(&the_index);
550 /* Any unmerged paths? */
551 for (pos = 0; pos < active_nr; pos++) {
552 const struct cache_entry *ce = active_cache[pos];
553 if (ce->ce_flags & CE_MATCHED) {
554 if (!ce_stage(ce))
555 continue;
556 if (opts->ignore_unmerged) {
557 if (!opts->quiet)
558 warning(_("path '%s' is unmerged"), ce->name);
559 } else if (opts->writeout_stage) {
560 errs |= check_stage(opts->writeout_stage, ce, pos, opts->overlay_mode);
561 } else if (opts->merge) {
562 errs |= check_stages((1<<2) | (1<<3), ce, pos);
563 } else {
564 errs = 1;
565 error(_("path '%s' is unmerged"), ce->name);
567 pos = skip_same_name(ce, pos) - 1;
570 if (errs)
571 return 1;
573 /* Now we are committed to check them out */
574 if (opts->checkout_worktree)
575 errs |= checkout_worktree(opts, new_branch_info);
576 else
577 remove_marked_cache_entries(&the_index, 1);
580 * Allow updating the index when checking out from the index.
581 * This is to save new stat info.
583 if (opts->checkout_worktree && !opts->checkout_index && !opts->source_tree)
584 checkout_index = 1;
585 else
586 checkout_index = opts->checkout_index;
588 if (checkout_index) {
589 if (write_locked_index(&the_index, &lock_file, COMMIT_LOCK))
590 die(_("unable to write new index file"));
591 } else {
593 * NEEDSWORK: if --worktree is not specified, we
594 * should save stat info of checked out files in the
595 * index to avoid the next (potentially costly)
596 * refresh. But it's a bit tricker to do...
598 rollback_lock_file(&lock_file);
601 read_ref_full("HEAD", 0, &rev, NULL);
602 head = lookup_commit_reference_gently(the_repository, &rev, 1);
604 errs |= post_checkout_hook(head, head, 0);
605 return errs;
608 static void show_local_changes(struct object *head,
609 const struct diff_options *opts)
611 struct rev_info rev;
612 /* I think we want full paths, even if we're in a subdirectory. */
613 repo_init_revisions(the_repository, &rev, NULL);
614 rev.diffopt.flags = opts->flags;
615 rev.diffopt.output_format |= DIFF_FORMAT_NAME_STATUS;
616 diff_setup_done(&rev.diffopt);
617 add_pending_object(&rev, head, NULL);
618 run_diff_index(&rev, 0);
619 object_array_clear(&rev.pending);
622 static void describe_detached_head(const char *msg, struct commit *commit)
624 struct strbuf sb = STRBUF_INIT;
626 if (!parse_commit(commit))
627 pp_commit_easy(CMIT_FMT_ONELINE, commit, &sb);
628 if (print_sha1_ellipsis()) {
629 fprintf(stderr, "%s %s... %s\n", msg,
630 find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV), sb.buf);
631 } else {
632 fprintf(stderr, "%s %s %s\n", msg,
633 find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV), sb.buf);
635 strbuf_release(&sb);
638 static int reset_tree(struct tree *tree, const struct checkout_opts *o,
639 int worktree, int *writeout_error,
640 struct branch_info *info)
642 struct unpack_trees_options opts;
643 struct tree_desc tree_desc;
645 memset(&opts, 0, sizeof(opts));
646 opts.head_idx = -1;
647 opts.update = worktree;
648 opts.skip_unmerged = !worktree;
649 opts.reset = 1;
650 opts.merge = 1;
651 opts.fn = oneway_merge;
652 opts.verbose_update = o->show_progress;
653 opts.src_index = &the_index;
654 opts.dst_index = &the_index;
655 init_checkout_metadata(&opts.meta, info->refname,
656 info->commit ? &info->commit->object.oid : null_oid(),
657 NULL);
658 parse_tree(tree);
659 init_tree_desc(&tree_desc, tree->buffer, tree->size);
660 switch (unpack_trees(1, &tree_desc, &opts)) {
661 case -2:
662 *writeout_error = 1;
664 * We return 0 nevertheless, as the index is all right
665 * and more importantly we have made best efforts to
666 * update paths in the work tree, and we cannot revert
667 * them.
669 /* fallthrough */
670 case 0:
671 return 0;
672 default:
673 return 128;
677 static void setup_branch_path(struct branch_info *branch)
679 struct strbuf buf = STRBUF_INIT;
682 * If this is a ref, resolve it; otherwise, look up the OID for our
683 * expression. Failure here is okay.
685 if (!dwim_ref(branch->name, strlen(branch->name), &branch->oid, &branch->refname, 0))
686 repo_get_oid_committish(the_repository, branch->name, &branch->oid);
688 strbuf_branchname(&buf, branch->name, INTERPRET_BRANCH_LOCAL);
689 if (strcmp(buf.buf, branch->name))
690 branch->name = xstrdup(buf.buf);
691 strbuf_splice(&buf, 0, 0, "refs/heads/", 11);
692 branch->path = strbuf_detach(&buf, NULL);
695 static int merge_working_tree(const struct checkout_opts *opts,
696 struct branch_info *old_branch_info,
697 struct branch_info *new_branch_info,
698 int *writeout_error)
700 int ret;
701 struct lock_file lock_file = LOCK_INIT;
702 struct tree *new_tree;
704 hold_locked_index(&lock_file, LOCK_DIE_ON_ERROR);
705 if (read_cache_preload(NULL) < 0)
706 return error(_("index file corrupt"));
708 resolve_undo_clear();
709 if (opts->new_orphan_branch && opts->orphan_from_empty_tree) {
710 if (new_branch_info->commit)
711 BUG("'switch --orphan' should never accept a commit as starting point");
712 new_tree = parse_tree_indirect(the_hash_algo->empty_tree);
713 } else
714 new_tree = get_commit_tree(new_branch_info->commit);
715 if (opts->discard_changes) {
716 ret = reset_tree(new_tree, opts, 1, writeout_error, new_branch_info);
717 if (ret)
718 return ret;
719 } else {
720 struct tree_desc trees[2];
721 struct tree *tree;
722 struct unpack_trees_options topts;
724 memset(&topts, 0, sizeof(topts));
725 topts.head_idx = -1;
726 topts.src_index = &the_index;
727 topts.dst_index = &the_index;
729 setup_unpack_trees_porcelain(&topts, "checkout");
731 refresh_cache(REFRESH_QUIET);
733 if (unmerged_cache()) {
734 error(_("you need to resolve your current index first"));
735 return 1;
738 /* 2-way merge to the new branch */
739 topts.initial_checkout = is_cache_unborn();
740 topts.update = 1;
741 topts.merge = 1;
742 topts.quiet = opts->merge && old_branch_info->commit;
743 topts.verbose_update = opts->show_progress;
744 topts.fn = twoway_merge;
745 init_checkout_metadata(&topts.meta, new_branch_info->refname,
746 new_branch_info->commit ?
747 &new_branch_info->commit->object.oid :
748 &new_branch_info->oid, NULL);
749 if (opts->overwrite_ignore) {
750 topts.dir = xcalloc(1, sizeof(*topts.dir));
751 topts.dir->flags |= DIR_SHOW_IGNORED;
752 setup_standard_excludes(topts.dir);
754 tree = parse_tree_indirect(old_branch_info->commit ?
755 &old_branch_info->commit->object.oid :
756 the_hash_algo->empty_tree);
757 init_tree_desc(&trees[0], tree->buffer, tree->size);
758 parse_tree(new_tree);
759 tree = new_tree;
760 init_tree_desc(&trees[1], tree->buffer, tree->size);
762 ret = unpack_trees(2, trees, &topts);
763 clear_unpack_trees_porcelain(&topts);
764 if (ret == -1) {
766 * Unpack couldn't do a trivial merge; either
767 * give up or do a real merge, depending on
768 * whether the merge flag was used.
770 struct tree *work;
771 struct tree *old_tree;
772 struct merge_options o;
773 struct strbuf sb = STRBUF_INIT;
774 struct strbuf old_commit_shortname = STRBUF_INIT;
776 if (!opts->merge)
777 return 1;
780 * Without old_branch_info->commit, the below is the same as
781 * the two-tree unpack we already tried and failed.
783 if (!old_branch_info->commit)
784 return 1;
785 old_tree = get_commit_tree(old_branch_info->commit);
787 if (repo_index_has_changes(the_repository, old_tree, &sb))
788 die(_("cannot continue with staged changes in "
789 "the following files:\n%s"), sb.buf);
790 strbuf_release(&sb);
792 /* Do more real merge */
795 * We update the index fully, then write the
796 * tree from the index, then merge the new
797 * branch with the current tree, with the old
798 * branch as the base. Then we reset the index
799 * (but not the working tree) to the new
800 * branch, leaving the working tree as the
801 * merged version, but skipping unmerged
802 * entries in the index.
805 add_files_to_cache(NULL, NULL, 0);
806 init_merge_options(&o, the_repository);
807 o.verbosity = 0;
808 work = write_in_core_index_as_tree(the_repository);
810 ret = reset_tree(new_tree,
811 opts, 1,
812 writeout_error, new_branch_info);
813 if (ret)
814 return ret;
815 o.ancestor = old_branch_info->name;
816 if (old_branch_info->name == NULL) {
817 strbuf_add_unique_abbrev(&old_commit_shortname,
818 &old_branch_info->commit->object.oid,
819 DEFAULT_ABBREV);
820 o.ancestor = old_commit_shortname.buf;
822 o.branch1 = new_branch_info->name;
823 o.branch2 = "local";
824 ret = merge_trees(&o,
825 new_tree,
826 work,
827 old_tree);
828 if (ret < 0)
829 exit(128);
830 ret = reset_tree(new_tree,
831 opts, 0,
832 writeout_error, new_branch_info);
833 strbuf_release(&o.obuf);
834 strbuf_release(&old_commit_shortname);
835 if (ret)
836 return ret;
840 if (!cache_tree_fully_valid(active_cache_tree))
841 cache_tree_update(&the_index, WRITE_TREE_SILENT | WRITE_TREE_REPAIR);
843 if (write_locked_index(&the_index, &lock_file, COMMIT_LOCK))
844 die(_("unable to write new index file"));
846 if (!opts->discard_changes && !opts->quiet && new_branch_info->commit)
847 show_local_changes(&new_branch_info->commit->object, &opts->diff_options);
849 return 0;
852 static void report_tracking(struct branch_info *new_branch_info)
854 struct strbuf sb = STRBUF_INIT;
855 struct branch *branch = branch_get(new_branch_info->name);
857 if (!format_tracking_info(branch, &sb, AHEAD_BEHIND_FULL))
858 return;
859 fputs(sb.buf, stdout);
860 strbuf_release(&sb);
863 static void update_refs_for_switch(const struct checkout_opts *opts,
864 struct branch_info *old_branch_info,
865 struct branch_info *new_branch_info)
867 struct strbuf msg = STRBUF_INIT;
868 const char *old_desc, *reflog_msg;
869 if (opts->new_branch) {
870 if (opts->new_orphan_branch) {
871 char *refname;
873 refname = mkpathdup("refs/heads/%s", opts->new_orphan_branch);
874 if (opts->new_branch_log &&
875 !should_autocreate_reflog(refname)) {
876 int ret;
877 struct strbuf err = STRBUF_INIT;
879 ret = safe_create_reflog(refname, 1, &err);
880 if (ret) {
881 fprintf(stderr, _("Can not do reflog for '%s': %s\n"),
882 opts->new_orphan_branch, err.buf);
883 strbuf_release(&err);
884 free(refname);
885 return;
887 strbuf_release(&err);
889 free(refname);
891 else
892 create_branch(the_repository,
893 opts->new_branch, new_branch_info->name,
894 opts->new_branch_force ? 1 : 0,
895 opts->new_branch_force ? 1 : 0,
896 opts->new_branch_log,
897 opts->quiet,
898 opts->track);
899 new_branch_info->name = opts->new_branch;
900 setup_branch_path(new_branch_info);
903 old_desc = old_branch_info->name;
904 if (!old_desc && old_branch_info->commit)
905 old_desc = oid_to_hex(&old_branch_info->commit->object.oid);
907 reflog_msg = getenv("GIT_REFLOG_ACTION");
908 if (!reflog_msg)
909 strbuf_addf(&msg, "checkout: moving from %s to %s",
910 old_desc ? old_desc : "(invalid)", new_branch_info->name);
911 else
912 strbuf_insertstr(&msg, 0, reflog_msg);
914 if (!strcmp(new_branch_info->name, "HEAD") && !new_branch_info->path && !opts->force_detach) {
915 /* Nothing to do. */
916 } else if (opts->force_detach || !new_branch_info->path) { /* No longer on any branch. */
917 update_ref(msg.buf, "HEAD", &new_branch_info->commit->object.oid, NULL,
918 REF_NO_DEREF, UPDATE_REFS_DIE_ON_ERR);
919 if (!opts->quiet) {
920 if (old_branch_info->path &&
921 advice_detached_head && !opts->force_detach)
922 detach_advice(new_branch_info->name);
923 describe_detached_head(_("HEAD is now at"), new_branch_info->commit);
925 } else if (new_branch_info->path) { /* Switch branches. */
926 if (create_symref("HEAD", new_branch_info->path, msg.buf) < 0)
927 die(_("unable to update HEAD"));
928 if (!opts->quiet) {
929 if (old_branch_info->path && !strcmp(new_branch_info->path, old_branch_info->path)) {
930 if (opts->new_branch_force)
931 fprintf(stderr, _("Reset branch '%s'\n"),
932 new_branch_info->name);
933 else
934 fprintf(stderr, _("Already on '%s'\n"),
935 new_branch_info->name);
936 } else if (opts->new_branch) {
937 if (opts->branch_exists)
938 fprintf(stderr, _("Switched to and reset branch '%s'\n"), new_branch_info->name);
939 else
940 fprintf(stderr, _("Switched to a new branch '%s'\n"), new_branch_info->name);
941 } else {
942 fprintf(stderr, _("Switched to branch '%s'\n"),
943 new_branch_info->name);
946 if (old_branch_info->path && old_branch_info->name) {
947 if (!ref_exists(old_branch_info->path) && reflog_exists(old_branch_info->path))
948 delete_reflog(old_branch_info->path);
951 remove_branch_state(the_repository, !opts->quiet);
952 strbuf_release(&msg);
953 if (!opts->quiet &&
954 (new_branch_info->path || (!opts->force_detach && !strcmp(new_branch_info->name, "HEAD"))))
955 report_tracking(new_branch_info);
958 static int add_pending_uninteresting_ref(const char *refname,
959 const struct object_id *oid,
960 int flags, void *cb_data)
962 add_pending_oid(cb_data, refname, oid, UNINTERESTING);
963 return 0;
966 static void describe_one_orphan(struct strbuf *sb, struct commit *commit)
968 strbuf_addstr(sb, " ");
969 strbuf_add_unique_abbrev(sb, &commit->object.oid, DEFAULT_ABBREV);
970 strbuf_addch(sb, ' ');
971 if (!parse_commit(commit))
972 pp_commit_easy(CMIT_FMT_ONELINE, commit, sb);
973 strbuf_addch(sb, '\n');
976 #define ORPHAN_CUTOFF 4
977 static void suggest_reattach(struct commit *commit, struct rev_info *revs)
979 struct commit *c, *last = NULL;
980 struct strbuf sb = STRBUF_INIT;
981 int lost = 0;
982 while ((c = get_revision(revs)) != NULL) {
983 if (lost < ORPHAN_CUTOFF)
984 describe_one_orphan(&sb, c);
985 last = c;
986 lost++;
988 if (ORPHAN_CUTOFF < lost) {
989 int more = lost - ORPHAN_CUTOFF;
990 if (more == 1)
991 describe_one_orphan(&sb, last);
992 else
993 strbuf_addf(&sb, _(" ... and %d more.\n"), more);
996 fprintf(stderr,
998 /* The singular version */
999 "Warning: you are leaving %d commit behind, "
1000 "not connected to\n"
1001 "any of your branches:\n\n"
1002 "%s\n",
1003 /* The plural version */
1004 "Warning: you are leaving %d commits behind, "
1005 "not connected to\n"
1006 "any of your branches:\n\n"
1007 "%s\n",
1008 /* Give ngettext() the count */
1009 lost),
1010 lost,
1011 sb.buf);
1012 strbuf_release(&sb);
1014 if (advice_detached_head)
1015 fprintf(stderr,
1017 /* The singular version */
1018 "If you want to keep it by creating a new branch, "
1019 "this may be a good time\nto do so with:\n\n"
1020 " git branch <new-branch-name> %s\n\n",
1021 /* The plural version */
1022 "If you want to keep them by creating a new branch, "
1023 "this may be a good time\nto do so with:\n\n"
1024 " git branch <new-branch-name> %s\n\n",
1025 /* Give ngettext() the count */
1026 lost),
1027 find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV));
1031 * We are about to leave commit that was at the tip of a detached
1032 * HEAD. If it is not reachable from any ref, this is the last chance
1033 * for the user to do so without resorting to reflog.
1035 static void orphaned_commit_warning(struct commit *old_commit, struct commit *new_commit)
1037 struct rev_info revs;
1038 struct object *object = &old_commit->object;
1040 repo_init_revisions(the_repository, &revs, NULL);
1041 setup_revisions(0, NULL, &revs, NULL);
1043 object->flags &= ~UNINTERESTING;
1044 add_pending_object(&revs, object, oid_to_hex(&object->oid));
1046 for_each_ref(add_pending_uninteresting_ref, &revs);
1047 if (new_commit)
1048 add_pending_oid(&revs, "HEAD",
1049 &new_commit->object.oid,
1050 UNINTERESTING);
1052 if (prepare_revision_walk(&revs))
1053 die(_("internal error in revision walk"));
1054 if (!(old_commit->object.flags & UNINTERESTING))
1055 suggest_reattach(old_commit, &revs);
1056 else
1057 describe_detached_head(_("Previous HEAD position was"), old_commit);
1059 /* Clean up objects used, as they will be reused. */
1060 repo_clear_commit_marks(the_repository, ALL_REV_FLAGS);
1063 static int switch_branches(const struct checkout_opts *opts,
1064 struct branch_info *new_branch_info)
1066 int ret = 0;
1067 struct branch_info old_branch_info;
1068 void *path_to_free;
1069 struct object_id rev;
1070 int flag, writeout_error = 0;
1071 int do_merge = 1;
1073 trace2_cmd_mode("branch");
1075 memset(&old_branch_info, 0, sizeof(old_branch_info));
1076 old_branch_info.path = path_to_free = resolve_refdup("HEAD", 0, &rev, &flag);
1077 if (old_branch_info.path)
1078 old_branch_info.commit = lookup_commit_reference_gently(the_repository, &rev, 1);
1079 if (!(flag & REF_ISSYMREF))
1080 old_branch_info.path = NULL;
1082 if (old_branch_info.path)
1083 skip_prefix(old_branch_info.path, "refs/heads/", &old_branch_info.name);
1085 if (opts->new_orphan_branch && opts->orphan_from_empty_tree) {
1086 if (new_branch_info->name)
1087 BUG("'switch --orphan' should never accept a commit as starting point");
1088 new_branch_info->commit = NULL;
1089 new_branch_info->name = "(empty)";
1090 do_merge = 1;
1093 if (!new_branch_info->name) {
1094 new_branch_info->name = "HEAD";
1095 new_branch_info->commit = old_branch_info.commit;
1096 if (!new_branch_info->commit)
1097 die(_("You are on a branch yet to be born"));
1098 parse_commit_or_die(new_branch_info->commit);
1100 if (opts->only_merge_on_switching_branches)
1101 do_merge = 0;
1104 if (do_merge) {
1105 ret = merge_working_tree(opts, &old_branch_info, new_branch_info, &writeout_error);
1106 if (ret) {
1107 free(path_to_free);
1108 return ret;
1112 if (!opts->quiet && !old_branch_info.path && old_branch_info.commit && new_branch_info->commit != old_branch_info.commit)
1113 orphaned_commit_warning(old_branch_info.commit, new_branch_info->commit);
1115 update_refs_for_switch(opts, &old_branch_info, new_branch_info);
1117 ret = post_checkout_hook(old_branch_info.commit, new_branch_info->commit, 1);
1118 free(path_to_free);
1119 return ret || writeout_error;
1122 static int git_checkout_config(const char *var, const char *value, void *cb)
1124 struct checkout_opts *opts = cb;
1126 if (!strcmp(var, "diff.ignoresubmodules")) {
1127 handle_ignore_submodules_arg(&opts->diff_options, value);
1128 return 0;
1130 if (!strcmp(var, "checkout.guess")) {
1131 opts->dwim_new_local_branch = git_config_bool(var, value);
1132 return 0;
1135 if (starts_with(var, "submodule."))
1136 return git_default_submodule_config(var, value, NULL);
1138 return git_xmerge_config(var, value, NULL);
1141 static void setup_new_branch_info_and_source_tree(
1142 struct branch_info *new_branch_info,
1143 struct checkout_opts *opts,
1144 struct object_id *rev,
1145 const char *arg)
1147 struct tree **source_tree = &opts->source_tree;
1148 struct object_id branch_rev;
1150 new_branch_info->name = arg;
1151 setup_branch_path(new_branch_info);
1153 if (!check_refname_format(new_branch_info->path, 0) &&
1154 !read_ref(new_branch_info->path, &branch_rev))
1155 oidcpy(rev, &branch_rev);
1156 else {
1157 free((char *)new_branch_info->path);
1158 new_branch_info->path = NULL; /* not an existing branch */
1161 new_branch_info->commit = lookup_commit_reference_gently(the_repository, rev, 1);
1162 if (!new_branch_info->commit) {
1163 /* not a commit */
1164 *source_tree = parse_tree_indirect(rev);
1165 } else {
1166 parse_commit_or_die(new_branch_info->commit);
1167 *source_tree = get_commit_tree(new_branch_info->commit);
1171 static const char *parse_remote_branch(const char *arg,
1172 struct object_id *rev,
1173 int could_be_checkout_paths)
1175 int num_matches = 0;
1176 const char *remote = unique_tracking_name(arg, rev, &num_matches);
1178 if (remote && could_be_checkout_paths) {
1179 die(_("'%s' could be both a local file and a tracking branch.\n"
1180 "Please use -- (and optionally --no-guess) to disambiguate"),
1181 arg);
1184 if (!remote && num_matches > 1) {
1185 if (advice_checkout_ambiguous_remote_branch_name) {
1186 advise(_("If you meant to check out a remote tracking branch on, e.g. 'origin',\n"
1187 "you can do so by fully qualifying the name with the --track option:\n"
1188 "\n"
1189 " git checkout --track origin/<name>\n"
1190 "\n"
1191 "If you'd like to always have checkouts of an ambiguous <name> prefer\n"
1192 "one remote, e.g. the 'origin' remote, consider setting\n"
1193 "checkout.defaultRemote=origin in your config."));
1196 die(_("'%s' matched multiple (%d) remote tracking branches"),
1197 arg, num_matches);
1200 return remote;
1203 static int parse_branchname_arg(int argc, const char **argv,
1204 int dwim_new_local_branch_ok,
1205 struct branch_info *new_branch_info,
1206 struct checkout_opts *opts,
1207 struct object_id *rev)
1209 const char **new_branch = &opts->new_branch;
1210 int argcount = 0;
1211 const char *arg;
1212 int dash_dash_pos;
1213 int has_dash_dash = 0;
1214 int i;
1217 * case 1: git checkout <ref> -- [<paths>]
1219 * <ref> must be a valid tree, everything after the '--' must be
1220 * a path.
1222 * case 2: git checkout -- [<paths>]
1224 * everything after the '--' must be paths.
1226 * case 3: git checkout <something> [--]
1228 * (a) If <something> is a commit, that is to
1229 * switch to the branch or detach HEAD at it. As a special case,
1230 * if <something> is A...B (missing A or B means HEAD but you can
1231 * omit at most one side), and if there is a unique merge base
1232 * between A and B, A...B names that merge base.
1234 * (b) If <something> is _not_ a commit, either "--" is present
1235 * or <something> is not a path, no -t or -b was given, and
1236 * and there is a tracking branch whose name is <something>
1237 * in one and only one remote (or if the branch exists on the
1238 * remote named in checkout.defaultRemote), then this is a
1239 * short-hand to fork local <something> from that
1240 * remote-tracking branch.
1242 * (c) Otherwise, if "--" is present, treat it like case (1).
1244 * (d) Otherwise :
1245 * - if it's a reference, treat it like case (1)
1246 * - else if it's a path, treat it like case (2)
1247 * - else: fail.
1249 * case 4: git checkout <something> <paths>
1251 * The first argument must not be ambiguous.
1252 * - If it's *only* a reference, treat it like case (1).
1253 * - If it's only a path, treat it like case (2).
1254 * - else: fail.
1257 if (!argc)
1258 return 0;
1260 if (!opts->accept_pathspec) {
1261 if (argc > 1)
1262 die(_("only one reference expected"));
1263 has_dash_dash = 1; /* helps disambiguate */
1266 arg = argv[0];
1267 dash_dash_pos = -1;
1268 for (i = 0; i < argc; i++) {
1269 if (opts->accept_pathspec && !strcmp(argv[i], "--")) {
1270 dash_dash_pos = i;
1271 break;
1274 if (dash_dash_pos == 0)
1275 return 1; /* case (2) */
1276 else if (dash_dash_pos == 1)
1277 has_dash_dash = 1; /* case (3) or (1) */
1278 else if (dash_dash_pos >= 2)
1279 die(_("only one reference expected, %d given."), dash_dash_pos);
1280 opts->count_checkout_paths = !opts->quiet && !has_dash_dash;
1282 if (!strcmp(arg, "-"))
1283 arg = "@{-1}";
1285 if (get_oid_mb(arg, rev)) {
1287 * Either case (3) or (4), with <something> not being
1288 * a commit, or an attempt to use case (1) with an
1289 * invalid ref.
1291 * It's likely an error, but we need to find out if
1292 * we should auto-create the branch, case (3).(b).
1294 int recover_with_dwim = dwim_new_local_branch_ok;
1296 int could_be_checkout_paths = !has_dash_dash &&
1297 check_filename(opts->prefix, arg);
1299 if (!has_dash_dash && !no_wildcard(arg))
1300 recover_with_dwim = 0;
1303 * Accept "git checkout foo", "git checkout foo --"
1304 * and "git switch foo" as candidates for dwim.
1306 if (!(argc == 1 && !has_dash_dash) &&
1307 !(argc == 2 && has_dash_dash) &&
1308 opts->accept_pathspec)
1309 recover_with_dwim = 0;
1311 if (recover_with_dwim) {
1312 const char *remote = parse_remote_branch(arg, rev,
1313 could_be_checkout_paths);
1314 if (remote) {
1315 *new_branch = arg;
1316 arg = remote;
1317 /* DWIMmed to create local branch, case (3).(b) */
1318 } else {
1319 recover_with_dwim = 0;
1323 if (!recover_with_dwim) {
1324 if (has_dash_dash)
1325 die(_("invalid reference: %s"), arg);
1326 return argcount;
1330 /* we can't end up being in (2) anymore, eat the argument */
1331 argcount++;
1332 argv++;
1333 argc--;
1335 setup_new_branch_info_and_source_tree(new_branch_info, opts, rev, arg);
1337 if (!opts->source_tree) /* case (1): want a tree */
1338 die(_("reference is not a tree: %s"), arg);
1340 if (!has_dash_dash) { /* case (3).(d) -> (1) */
1342 * Do not complain the most common case
1343 * git checkout branch
1344 * even if there happen to be a file called 'branch';
1345 * it would be extremely annoying.
1347 if (argc)
1348 verify_non_filename(opts->prefix, arg);
1349 } else if (opts->accept_pathspec) {
1350 argcount++;
1351 argv++;
1352 argc--;
1355 return argcount;
1358 static int switch_unborn_to_new_branch(const struct checkout_opts *opts)
1360 int status;
1361 struct strbuf branch_ref = STRBUF_INIT;
1363 trace2_cmd_mode("unborn");
1365 if (!opts->new_branch)
1366 die(_("You are on a branch yet to be born"));
1367 strbuf_addf(&branch_ref, "refs/heads/%s", opts->new_branch);
1368 status = create_symref("HEAD", branch_ref.buf, "checkout -b");
1369 strbuf_release(&branch_ref);
1370 if (!opts->quiet)
1371 fprintf(stderr, _("Switched to a new branch '%s'\n"),
1372 opts->new_branch);
1373 return status;
1376 static void die_expecting_a_branch(const struct branch_info *branch_info)
1378 struct object_id oid;
1379 char *to_free;
1381 if (dwim_ref(branch_info->name, strlen(branch_info->name), &oid, &to_free, 0) == 1) {
1382 const char *ref = to_free;
1384 if (skip_prefix(ref, "refs/tags/", &ref))
1385 die(_("a branch is expected, got tag '%s'"), ref);
1386 if (skip_prefix(ref, "refs/remotes/", &ref))
1387 die(_("a branch is expected, got remote branch '%s'"), ref);
1388 die(_("a branch is expected, got '%s'"), ref);
1390 if (branch_info->commit)
1391 die(_("a branch is expected, got commit '%s'"), branch_info->name);
1393 * This case should never happen because we already die() on
1394 * non-commit, but just in case.
1396 die(_("a branch is expected, got '%s'"), branch_info->name);
1399 static void die_if_some_operation_in_progress(void)
1401 struct wt_status_state state;
1403 memset(&state, 0, sizeof(state));
1404 wt_status_get_state(the_repository, &state, 0);
1406 if (state.merge_in_progress)
1407 die(_("cannot switch branch while merging\n"
1408 "Consider \"git merge --quit\" "
1409 "or \"git worktree add\"."));
1410 if (state.am_in_progress)
1411 die(_("cannot switch branch in the middle of an am session\n"
1412 "Consider \"git am --quit\" "
1413 "or \"git worktree add\"."));
1414 if (state.rebase_interactive_in_progress || state.rebase_in_progress)
1415 die(_("cannot switch branch while rebasing\n"
1416 "Consider \"git rebase --quit\" "
1417 "or \"git worktree add\"."));
1418 if (state.cherry_pick_in_progress)
1419 die(_("cannot switch branch while cherry-picking\n"
1420 "Consider \"git cherry-pick --quit\" "
1421 "or \"git worktree add\"."));
1422 if (state.revert_in_progress)
1423 die(_("cannot switch branch while reverting\n"
1424 "Consider \"git revert --quit\" "
1425 "or \"git worktree add\"."));
1426 if (state.bisect_in_progress)
1427 warning(_("you are switching branch while bisecting"));
1430 static int checkout_branch(struct checkout_opts *opts,
1431 struct branch_info *new_branch_info)
1433 if (opts->pathspec.nr)
1434 die(_("paths cannot be used with switching branches"));
1436 if (opts->patch_mode)
1437 die(_("'%s' cannot be used with switching branches"),
1438 "--patch");
1440 if (opts->overlay_mode != -1)
1441 die(_("'%s' cannot be used with switching branches"),
1442 "--[no]-overlay");
1444 if (opts->writeout_stage)
1445 die(_("'%s' cannot be used with switching branches"),
1446 "--ours/--theirs");
1448 if (opts->force && opts->merge)
1449 die(_("'%s' cannot be used with '%s'"), "-f", "-m");
1451 if (opts->discard_changes && opts->merge)
1452 die(_("'%s' cannot be used with '%s'"), "--discard-changes", "--merge");
1454 if (opts->force_detach && opts->new_branch)
1455 die(_("'%s' cannot be used with '%s'"),
1456 "--detach", "-b/-B/--orphan");
1458 if (opts->new_orphan_branch) {
1459 if (opts->track != BRANCH_TRACK_UNSPECIFIED)
1460 die(_("'%s' cannot be used with '%s'"), "--orphan", "-t");
1461 if (opts->orphan_from_empty_tree && new_branch_info->name)
1462 die(_("'%s' cannot take <start-point>"), "--orphan");
1463 } else if (opts->force_detach) {
1464 if (opts->track != BRANCH_TRACK_UNSPECIFIED)
1465 die(_("'%s' cannot be used with '%s'"), "--detach", "-t");
1466 } else if (opts->track == BRANCH_TRACK_UNSPECIFIED)
1467 opts->track = git_branch_track;
1469 if (new_branch_info->name && !new_branch_info->commit)
1470 die(_("Cannot switch branch to a non-commit '%s'"),
1471 new_branch_info->name);
1473 if (!opts->switch_branch_doing_nothing_is_ok &&
1474 !new_branch_info->name &&
1475 !opts->new_branch &&
1476 !opts->force_detach)
1477 die(_("missing branch or commit argument"));
1479 if (!opts->implicit_detach &&
1480 !opts->force_detach &&
1481 !opts->new_branch &&
1482 !opts->new_branch_force &&
1483 new_branch_info->name &&
1484 !new_branch_info->path)
1485 die_expecting_a_branch(new_branch_info);
1487 if (!opts->can_switch_when_in_progress)
1488 die_if_some_operation_in_progress();
1490 if (new_branch_info->path && !opts->force_detach && !opts->new_branch &&
1491 !opts->ignore_other_worktrees) {
1492 int flag;
1493 char *head_ref = resolve_refdup("HEAD", 0, NULL, &flag);
1494 if (head_ref &&
1495 (!(flag & REF_ISSYMREF) || strcmp(head_ref, new_branch_info->path)))
1496 die_if_checked_out(new_branch_info->path, 1);
1497 free(head_ref);
1500 if (!new_branch_info->commit && opts->new_branch) {
1501 struct object_id rev;
1502 int flag;
1504 if (!read_ref_full("HEAD", 0, &rev, &flag) &&
1505 (flag & REF_ISSYMREF) && is_null_oid(&rev))
1506 return switch_unborn_to_new_branch(opts);
1508 return switch_branches(opts, new_branch_info);
1511 static struct option *add_common_options(struct checkout_opts *opts,
1512 struct option *prevopts)
1514 struct option options[] = {
1515 OPT__QUIET(&opts->quiet, N_("suppress progress reporting")),
1516 OPT_CALLBACK_F(0, "recurse-submodules", NULL,
1517 "checkout", "control recursive updating of submodules",
1518 PARSE_OPT_OPTARG, option_parse_recurse_submodules_worktree_updater),
1519 OPT_BOOL(0, "progress", &opts->show_progress, N_("force progress reporting")),
1520 OPT_BOOL('m', "merge", &opts->merge, N_("perform a 3-way merge with the new branch")),
1521 OPT_STRING(0, "conflict", &opts->conflict_style, N_("style"),
1522 N_("conflict style (merge or diff3)")),
1523 OPT_END()
1525 struct option *newopts = parse_options_concat(prevopts, options);
1526 free(prevopts);
1527 return newopts;
1530 static struct option *add_common_switch_branch_options(
1531 struct checkout_opts *opts, struct option *prevopts)
1533 struct option options[] = {
1534 OPT_BOOL('d', "detach", &opts->force_detach, N_("detach HEAD at named commit")),
1535 OPT_SET_INT('t', "track", &opts->track, N_("set upstream info for new branch"),
1536 BRANCH_TRACK_EXPLICIT),
1537 OPT__FORCE(&opts->force, N_("force checkout (throw away local modifications)"),
1538 PARSE_OPT_NOCOMPLETE),
1539 OPT_STRING(0, "orphan", &opts->new_orphan_branch, N_("new-branch"), N_("new unparented branch")),
1540 OPT_BOOL_F(0, "overwrite-ignore", &opts->overwrite_ignore,
1541 N_("update ignored files (default)"),
1542 PARSE_OPT_NOCOMPLETE),
1543 OPT_BOOL(0, "ignore-other-worktrees", &opts->ignore_other_worktrees,
1544 N_("do not check if another worktree is holding the given ref")),
1545 OPT_END()
1547 struct option *newopts = parse_options_concat(prevopts, options);
1548 free(prevopts);
1549 return newopts;
1552 static struct option *add_checkout_path_options(struct checkout_opts *opts,
1553 struct option *prevopts)
1555 struct option options[] = {
1556 OPT_SET_INT_F('2', "ours", &opts->writeout_stage,
1557 N_("checkout our version for unmerged files"),
1558 2, PARSE_OPT_NONEG),
1559 OPT_SET_INT_F('3', "theirs", &opts->writeout_stage,
1560 N_("checkout their version for unmerged files"),
1561 3, PARSE_OPT_NONEG),
1562 OPT_BOOL('p', "patch", &opts->patch_mode, N_("select hunks interactively")),
1563 OPT_BOOL(0, "ignore-skip-worktree-bits", &opts->ignore_skipworktree,
1564 N_("do not limit pathspecs to sparse entries only")),
1565 OPT_PATHSPEC_FROM_FILE(&opts->pathspec_from_file),
1566 OPT_PATHSPEC_FILE_NUL(&opts->pathspec_file_nul),
1567 OPT_END()
1569 struct option *newopts = parse_options_concat(prevopts, options);
1570 free(prevopts);
1571 return newopts;
1574 /* create-branch option (either b or c) */
1575 static char cb_option = 'b';
1577 static int checkout_main(int argc, const char **argv, const char *prefix,
1578 struct checkout_opts *opts, struct option *options,
1579 const char * const usagestr[])
1581 struct branch_info new_branch_info;
1582 int parseopt_flags = 0;
1584 memset(&new_branch_info, 0, sizeof(new_branch_info));
1585 opts->overwrite_ignore = 1;
1586 opts->prefix = prefix;
1587 opts->show_progress = -1;
1589 git_config(git_checkout_config, opts);
1591 prepare_repo_settings(the_repository);
1592 the_repository->settings.command_requires_full_index = 0;
1594 opts->track = BRANCH_TRACK_UNSPECIFIED;
1596 if (!opts->accept_pathspec && !opts->accept_ref)
1597 BUG("make up your mind, you need to take _something_");
1598 if (opts->accept_pathspec && opts->accept_ref)
1599 parseopt_flags = PARSE_OPT_KEEP_DASHDASH;
1601 argc = parse_options(argc, argv, prefix, options,
1602 usagestr, parseopt_flags);
1604 if (opts->show_progress < 0) {
1605 if (opts->quiet)
1606 opts->show_progress = 0;
1607 else
1608 opts->show_progress = isatty(2);
1611 if (opts->conflict_style) {
1612 opts->merge = 1; /* implied */
1613 git_xmerge_config("merge.conflictstyle", opts->conflict_style, NULL);
1615 if (opts->force) {
1616 opts->discard_changes = 1;
1617 opts->ignore_unmerged_opt = "--force";
1618 opts->ignore_unmerged = 1;
1621 if ((!!opts->new_branch + !!opts->new_branch_force + !!opts->new_orphan_branch) > 1)
1622 die(_("-%c, -%c and --orphan are mutually exclusive"),
1623 cb_option, toupper(cb_option));
1625 if (opts->overlay_mode == 1 && opts->patch_mode)
1626 die(_("-p and --overlay are mutually exclusive"));
1628 if (opts->checkout_index >= 0 || opts->checkout_worktree >= 0) {
1629 if (opts->checkout_index < 0)
1630 opts->checkout_index = 0;
1631 if (opts->checkout_worktree < 0)
1632 opts->checkout_worktree = 0;
1633 } else {
1634 if (opts->checkout_index < 0)
1635 opts->checkout_index = -opts->checkout_index - 1;
1636 if (opts->checkout_worktree < 0)
1637 opts->checkout_worktree = -opts->checkout_worktree - 1;
1639 if (opts->checkout_index < 0 || opts->checkout_worktree < 0)
1640 BUG("these flags should be non-negative by now");
1642 * convenient shortcut: "git restore --staged [--worktree]" equals
1643 * "git restore --staged [--worktree] --source HEAD"
1645 if (!opts->from_treeish && opts->checkout_index)
1646 opts->from_treeish = "HEAD";
1649 * From here on, new_branch will contain the branch to be checked out,
1650 * and new_branch_force and new_orphan_branch will tell us which one of
1651 * -b/-B/-c/-C/--orphan is being used.
1653 if (opts->new_branch_force)
1654 opts->new_branch = opts->new_branch_force;
1656 if (opts->new_orphan_branch)
1657 opts->new_branch = opts->new_orphan_branch;
1659 /* --track without -c/-C/-b/-B/--orphan should DWIM */
1660 if (opts->track != BRANCH_TRACK_UNSPECIFIED && !opts->new_branch) {
1661 const char *argv0 = argv[0];
1662 if (!argc || !strcmp(argv0, "--"))
1663 die(_("--track needs a branch name"));
1664 skip_prefix(argv0, "refs/", &argv0);
1665 skip_prefix(argv0, "remotes/", &argv0);
1666 argv0 = strchr(argv0, '/');
1667 if (!argv0 || !argv0[1])
1668 die(_("missing branch name; try -%c"), cb_option);
1669 opts->new_branch = argv0 + 1;
1673 * Extract branch name from command line arguments, so
1674 * all that is left is pathspecs.
1676 * Handle
1678 * 1) git checkout <tree> -- [<paths>]
1679 * 2) git checkout -- [<paths>]
1680 * 3) git checkout <something> [<paths>]
1682 * including "last branch" syntax and DWIM-ery for names of
1683 * remote branches, erroring out for invalid or ambiguous cases.
1685 if (argc && opts->accept_ref) {
1686 struct object_id rev;
1687 int dwim_ok =
1688 !opts->patch_mode &&
1689 opts->dwim_new_local_branch &&
1690 opts->track == BRANCH_TRACK_UNSPECIFIED &&
1691 !opts->new_branch;
1692 int n = parse_branchname_arg(argc, argv, dwim_ok,
1693 &new_branch_info, opts, &rev);
1694 argv += n;
1695 argc -= n;
1696 } else if (!opts->accept_ref && opts->from_treeish) {
1697 struct object_id rev;
1699 if (get_oid_mb(opts->from_treeish, &rev))
1700 die(_("could not resolve %s"), opts->from_treeish);
1702 setup_new_branch_info_and_source_tree(&new_branch_info,
1703 opts, &rev,
1704 opts->from_treeish);
1706 if (!opts->source_tree)
1707 die(_("reference is not a tree: %s"), opts->from_treeish);
1710 if (argc) {
1711 parse_pathspec(&opts->pathspec, 0,
1712 opts->patch_mode ? PATHSPEC_PREFIX_ORIGIN : 0,
1713 prefix, argv);
1715 if (!opts->pathspec.nr)
1716 die(_("invalid path specification"));
1719 * Try to give more helpful suggestion.
1720 * new_branch && argc > 1 will be caught later.
1722 if (opts->new_branch && argc == 1 && !new_branch_info.commit)
1723 die(_("'%s' is not a commit and a branch '%s' cannot be created from it"),
1724 argv[0], opts->new_branch);
1726 if (opts->force_detach)
1727 die(_("git checkout: --detach does not take a path argument '%s'"),
1728 argv[0]);
1731 if (opts->pathspec_from_file) {
1732 if (opts->pathspec.nr)
1733 die(_("--pathspec-from-file is incompatible with pathspec arguments"));
1735 if (opts->force_detach)
1736 die(_("--pathspec-from-file is incompatible with --detach"));
1738 if (opts->patch_mode)
1739 die(_("--pathspec-from-file is incompatible with --patch"));
1741 parse_pathspec_file(&opts->pathspec, 0,
1743 prefix, opts->pathspec_from_file, opts->pathspec_file_nul);
1744 } else if (opts->pathspec_file_nul) {
1745 die(_("--pathspec-file-nul requires --pathspec-from-file"));
1748 opts->pathspec.recursive = 1;
1750 if (opts->pathspec.nr) {
1751 if (1 < !!opts->writeout_stage + !!opts->force + !!opts->merge)
1752 die(_("git checkout: --ours/--theirs, --force and --merge are incompatible when\n"
1753 "checking out of the index."));
1754 } else {
1755 if (opts->accept_pathspec && !opts->empty_pathspec_ok &&
1756 !opts->patch_mode) /* patch mode is special */
1757 die(_("you must specify path(s) to restore"));
1760 if (opts->new_branch) {
1761 struct strbuf buf = STRBUF_INIT;
1763 if (opts->new_branch_force)
1764 opts->branch_exists = validate_branchname(opts->new_branch, &buf);
1765 else
1766 opts->branch_exists =
1767 validate_new_branchname(opts->new_branch, &buf, 0);
1768 strbuf_release(&buf);
1771 UNLEAK(opts);
1772 if (opts->patch_mode || opts->pathspec.nr)
1773 return checkout_paths(opts, &new_branch_info);
1774 else
1775 return checkout_branch(opts, &new_branch_info);
1778 int cmd_checkout(int argc, const char **argv, const char *prefix)
1780 struct checkout_opts opts;
1781 struct option *options;
1782 struct option checkout_options[] = {
1783 OPT_STRING('b', NULL, &opts.new_branch, N_("branch"),
1784 N_("create and checkout a new branch")),
1785 OPT_STRING('B', NULL, &opts.new_branch_force, N_("branch"),
1786 N_("create/reset and checkout a branch")),
1787 OPT_BOOL('l', NULL, &opts.new_branch_log, N_("create reflog for new branch")),
1788 OPT_BOOL(0, "guess", &opts.dwim_new_local_branch,
1789 N_("second guess 'git checkout <no-such-branch>' (default)")),
1790 OPT_BOOL(0, "overlay", &opts.overlay_mode, N_("use overlay mode (default)")),
1791 OPT_END()
1793 int ret;
1795 memset(&opts, 0, sizeof(opts));
1796 opts.dwim_new_local_branch = 1;
1797 opts.switch_branch_doing_nothing_is_ok = 1;
1798 opts.only_merge_on_switching_branches = 0;
1799 opts.accept_ref = 1;
1800 opts.accept_pathspec = 1;
1801 opts.implicit_detach = 1;
1802 opts.can_switch_when_in_progress = 1;
1803 opts.orphan_from_empty_tree = 0;
1804 opts.empty_pathspec_ok = 1;
1805 opts.overlay_mode = -1;
1806 opts.checkout_index = -2; /* default on */
1807 opts.checkout_worktree = -2; /* default on */
1809 if (argc == 3 && !strcmp(argv[1], "-b")) {
1811 * User ran 'git checkout -b <branch>' and expects
1812 * the same behavior as 'git switch -c <branch>'.
1814 opts.switch_branch_doing_nothing_is_ok = 0;
1815 opts.only_merge_on_switching_branches = 1;
1818 options = parse_options_dup(checkout_options);
1819 options = add_common_options(&opts, options);
1820 options = add_common_switch_branch_options(&opts, options);
1821 options = add_checkout_path_options(&opts, options);
1823 ret = checkout_main(argc, argv, prefix, &opts,
1824 options, checkout_usage);
1825 FREE_AND_NULL(options);
1826 return ret;
1829 int cmd_switch(int argc, const char **argv, const char *prefix)
1831 struct checkout_opts opts;
1832 struct option *options = NULL;
1833 struct option switch_options[] = {
1834 OPT_STRING('c', "create", &opts.new_branch, N_("branch"),
1835 N_("create and switch to a new branch")),
1836 OPT_STRING('C', "force-create", &opts.new_branch_force, N_("branch"),
1837 N_("create/reset and switch to a branch")),
1838 OPT_BOOL(0, "guess", &opts.dwim_new_local_branch,
1839 N_("second guess 'git switch <no-such-branch>'")),
1840 OPT_BOOL(0, "discard-changes", &opts.discard_changes,
1841 N_("throw away local modifications")),
1842 OPT_END()
1844 int ret;
1846 memset(&opts, 0, sizeof(opts));
1847 opts.dwim_new_local_branch = 1;
1848 opts.accept_ref = 1;
1849 opts.accept_pathspec = 0;
1850 opts.switch_branch_doing_nothing_is_ok = 0;
1851 opts.only_merge_on_switching_branches = 1;
1852 opts.implicit_detach = 0;
1853 opts.can_switch_when_in_progress = 0;
1854 opts.orphan_from_empty_tree = 1;
1855 opts.overlay_mode = -1;
1857 options = parse_options_dup(switch_options);
1858 options = add_common_options(&opts, options);
1859 options = add_common_switch_branch_options(&opts, options);
1861 cb_option = 'c';
1863 ret = checkout_main(argc, argv, prefix, &opts,
1864 options, switch_branch_usage);
1865 FREE_AND_NULL(options);
1866 return ret;
1869 int cmd_restore(int argc, const char **argv, const char *prefix)
1871 struct checkout_opts opts;
1872 struct option *options;
1873 struct option restore_options[] = {
1874 OPT_STRING('s', "source", &opts.from_treeish, "<tree-ish>",
1875 N_("which tree-ish to checkout from")),
1876 OPT_BOOL('S', "staged", &opts.checkout_index,
1877 N_("restore the index")),
1878 OPT_BOOL('W', "worktree", &opts.checkout_worktree,
1879 N_("restore the working tree (default)")),
1880 OPT_BOOL(0, "ignore-unmerged", &opts.ignore_unmerged,
1881 N_("ignore unmerged entries")),
1882 OPT_BOOL(0, "overlay", &opts.overlay_mode, N_("use overlay mode")),
1883 OPT_END()
1885 int ret;
1887 memset(&opts, 0, sizeof(opts));
1888 opts.accept_ref = 0;
1889 opts.accept_pathspec = 1;
1890 opts.empty_pathspec_ok = 0;
1891 opts.overlay_mode = 0;
1892 opts.checkout_index = -1; /* default off */
1893 opts.checkout_worktree = -2; /* default on */
1894 opts.ignore_unmerged_opt = "--ignore-unmerged";
1896 options = parse_options_dup(restore_options);
1897 options = add_common_options(&opts, options);
1898 options = add_checkout_path_options(&opts, options);
1900 ret = checkout_main(argc, argv, prefix, &opts,
1901 options, restore_usage);
1902 FREE_AND_NULL(options);
1903 return ret;