commit-graph: fix generation number v2 overflow values
[git/debian.git] / builtin / checkout.c
blobcc804ba8e1e6cdb8748eabc7e91575ac2ee53a4a
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 char *name; /* The short name used */
95 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 void branch_info_release(struct branch_info *info)
108 free(info->name);
109 free(info->path);
110 free(info->refname);
111 free(info->checkout);
114 static int post_checkout_hook(struct commit *old_commit, struct commit *new_commit,
115 int changed)
117 return run_hook_le(NULL, "post-checkout",
118 oid_to_hex(old_commit ? &old_commit->object.oid : null_oid()),
119 oid_to_hex(new_commit ? &new_commit->object.oid : null_oid()),
120 changed ? "1" : "0", NULL);
121 /* "new_commit" can be NULL when checking out from the index before
122 a commit exists. */
126 static int update_some(const struct object_id *oid, struct strbuf *base,
127 const char *pathname, unsigned mode, void *context)
129 int len;
130 struct cache_entry *ce;
131 int pos;
133 if (S_ISDIR(mode))
134 return READ_TREE_RECURSIVE;
136 len = base->len + strlen(pathname);
137 ce = make_empty_cache_entry(&the_index, len);
138 oidcpy(&ce->oid, oid);
139 memcpy(ce->name, base->buf, base->len);
140 memcpy(ce->name + base->len, pathname, len - base->len);
141 ce->ce_flags = create_ce_flags(0) | CE_UPDATE;
142 ce->ce_namelen = len;
143 ce->ce_mode = create_ce_mode(mode);
146 * If the entry is the same as the current index, we can leave the old
147 * entry in place. Whether it is UPTODATE or not, checkout_entry will
148 * do the right thing.
150 pos = cache_name_pos(ce->name, ce->ce_namelen);
151 if (pos >= 0) {
152 struct cache_entry *old = active_cache[pos];
153 if (ce->ce_mode == old->ce_mode &&
154 !ce_intent_to_add(old) &&
155 oideq(&ce->oid, &old->oid)) {
156 old->ce_flags |= CE_UPDATE;
157 discard_cache_entry(ce);
158 return 0;
162 add_cache_entry(ce, ADD_CACHE_OK_TO_ADD | ADD_CACHE_OK_TO_REPLACE);
163 return 0;
166 static int read_tree_some(struct tree *tree, const struct pathspec *pathspec)
168 read_tree(the_repository, tree,
169 pathspec, update_some, NULL);
171 /* update the index with the given tree's info
172 * for all args, expanding wildcards, and exit
173 * with any non-zero return code.
175 return 0;
178 static int skip_same_name(const struct cache_entry *ce, int pos)
180 while (++pos < active_nr &&
181 !strcmp(active_cache[pos]->name, ce->name))
182 ; /* skip */
183 return pos;
186 static int check_stage(int stage, const struct cache_entry *ce, int pos,
187 int overlay_mode)
189 while (pos < active_nr &&
190 !strcmp(active_cache[pos]->name, ce->name)) {
191 if (ce_stage(active_cache[pos]) == stage)
192 return 0;
193 pos++;
195 if (!overlay_mode)
196 return 0;
197 if (stage == 2)
198 return error(_("path '%s' does not have our version"), ce->name);
199 else
200 return error(_("path '%s' does not have their version"), ce->name);
203 static int check_stages(unsigned stages, const struct cache_entry *ce, int pos)
205 unsigned seen = 0;
206 const char *name = ce->name;
208 while (pos < active_nr) {
209 ce = active_cache[pos];
210 if (strcmp(name, ce->name))
211 break;
212 seen |= (1 << ce_stage(ce));
213 pos++;
215 if ((stages & seen) != stages)
216 return error(_("path '%s' does not have all necessary versions"),
217 name);
218 return 0;
221 static int checkout_stage(int stage, const struct cache_entry *ce, int pos,
222 const struct checkout *state, int *nr_checkouts,
223 int overlay_mode)
225 while (pos < active_nr &&
226 !strcmp(active_cache[pos]->name, ce->name)) {
227 if (ce_stage(active_cache[pos]) == stage)
228 return checkout_entry(active_cache[pos], state,
229 NULL, nr_checkouts);
230 pos++;
232 if (!overlay_mode) {
233 unlink_entry(ce);
234 return 0;
236 if (stage == 2)
237 return error(_("path '%s' does not have our version"), ce->name);
238 else
239 return error(_("path '%s' does not have their version"), ce->name);
242 static int checkout_merged(int pos, const struct checkout *state,
243 int *nr_checkouts, struct mem_pool *ce_mem_pool)
245 struct cache_entry *ce = active_cache[pos];
246 const char *path = ce->name;
247 mmfile_t ancestor, ours, theirs;
248 int status;
249 struct object_id oid;
250 mmbuffer_t result_buf;
251 struct object_id threeway[3];
252 unsigned mode = 0;
253 struct ll_merge_options ll_opts;
254 int renormalize = 0;
256 memset(threeway, 0, sizeof(threeway));
257 while (pos < active_nr) {
258 int stage;
259 stage = ce_stage(ce);
260 if (!stage || strcmp(path, ce->name))
261 break;
262 oidcpy(&threeway[stage - 1], &ce->oid);
263 if (stage == 2)
264 mode = create_ce_mode(ce->ce_mode);
265 pos++;
266 ce = active_cache[pos];
268 if (is_null_oid(&threeway[1]) || is_null_oid(&threeway[2]))
269 return error(_("path '%s' does not have necessary versions"), path);
271 read_mmblob(&ancestor, &threeway[0]);
272 read_mmblob(&ours, &threeway[1]);
273 read_mmblob(&theirs, &threeway[2]);
275 memset(&ll_opts, 0, sizeof(ll_opts));
276 git_config_get_bool("merge.renormalize", &renormalize);
277 ll_opts.renormalize = renormalize;
278 status = ll_merge(&result_buf, path, &ancestor, "base",
279 &ours, "ours", &theirs, "theirs",
280 state->istate, &ll_opts);
281 free(ancestor.ptr);
282 free(ours.ptr);
283 free(theirs.ptr);
284 if (status < 0 || !result_buf.ptr) {
285 free(result_buf.ptr);
286 return error(_("path '%s': cannot merge"), path);
290 * NEEDSWORK:
291 * There is absolutely no reason to write this as a blob object
292 * and create a phony cache entry. This hack is primarily to get
293 * to the write_entry() machinery that massages the contents to
294 * work-tree format and writes out which only allows it for a
295 * cache entry. The code in write_entry() needs to be refactored
296 * to allow us to feed a <buffer, size, mode> instead of a cache
297 * entry. Such a refactoring would help merge_recursive as well
298 * (it also writes the merge result to the object database even
299 * when it may contain conflicts).
301 if (write_object_file(result_buf.ptr, result_buf.size, blob_type, &oid))
302 die(_("Unable to add merge result for '%s'"), path);
303 free(result_buf.ptr);
304 ce = make_transient_cache_entry(mode, &oid, path, 2, ce_mem_pool);
305 if (!ce)
306 die(_("make_cache_entry failed for path '%s'"), path);
307 status = checkout_entry(ce, state, NULL, nr_checkouts);
308 return status;
311 static void mark_ce_for_checkout_overlay(struct cache_entry *ce,
312 char *ps_matched,
313 const struct checkout_opts *opts)
315 ce->ce_flags &= ~CE_MATCHED;
316 if (!opts->ignore_skipworktree && ce_skip_worktree(ce))
317 return;
318 if (opts->source_tree && !(ce->ce_flags & CE_UPDATE))
320 * "git checkout tree-ish -- path", but this entry
321 * is in the original index but is not in tree-ish
322 * or does not match the pathspec; it will not be
323 * checked out to the working tree. We will not do
324 * anything to this entry at all.
326 return;
328 * Either this entry came from the tree-ish we are
329 * checking the paths out of, or we are checking out
330 * of the index.
332 * If it comes from the tree-ish, we already know it
333 * matches the pathspec and could just stamp
334 * CE_MATCHED to it from update_some(). But we still
335 * need ps_matched and read_tree (and
336 * eventually tree_entry_interesting) cannot fill
337 * ps_matched yet. Once it can, we can avoid calling
338 * match_pathspec() for _all_ entries when
339 * opts->source_tree != NULL.
341 if (ce_path_match(&the_index, ce, &opts->pathspec, ps_matched))
342 ce->ce_flags |= CE_MATCHED;
345 static void mark_ce_for_checkout_no_overlay(struct cache_entry *ce,
346 char *ps_matched,
347 const struct checkout_opts *opts)
349 ce->ce_flags &= ~CE_MATCHED;
350 if (!opts->ignore_skipworktree && ce_skip_worktree(ce))
351 return;
352 if (ce_path_match(&the_index, ce, &opts->pathspec, ps_matched)) {
353 ce->ce_flags |= CE_MATCHED;
354 if (opts->source_tree && !(ce->ce_flags & CE_UPDATE))
356 * In overlay mode, but the path is not in
357 * tree-ish, which means we should remove it
358 * from the index and the working tree.
360 ce->ce_flags |= CE_REMOVE | CE_WT_REMOVE;
364 static int checkout_worktree(const struct checkout_opts *opts,
365 const struct branch_info *info)
367 struct checkout state = CHECKOUT_INIT;
368 int nr_checkouts = 0, nr_unmerged = 0;
369 int errs = 0;
370 int pos;
371 int pc_workers, pc_threshold;
372 struct mem_pool ce_mem_pool;
374 state.force = 1;
375 state.refresh_cache = 1;
376 state.istate = &the_index;
378 mem_pool_init(&ce_mem_pool, 0);
379 get_parallel_checkout_configs(&pc_workers, &pc_threshold);
380 init_checkout_metadata(&state.meta, info->refname,
381 info->commit ? &info->commit->object.oid : &info->oid,
382 NULL);
384 enable_delayed_checkout(&state);
386 if (pc_workers > 1)
387 init_parallel_checkout();
389 for (pos = 0; pos < active_nr; pos++) {
390 struct cache_entry *ce = active_cache[pos];
391 if (ce->ce_flags & CE_MATCHED) {
392 if (!ce_stage(ce)) {
393 errs |= checkout_entry(ce, &state,
394 NULL, &nr_checkouts);
395 continue;
397 if (opts->writeout_stage)
398 errs |= checkout_stage(opts->writeout_stage,
399 ce, pos,
400 &state,
401 &nr_checkouts, opts->overlay_mode);
402 else if (opts->merge)
403 errs |= checkout_merged(pos, &state,
404 &nr_unmerged,
405 &ce_mem_pool);
406 pos = skip_same_name(ce, pos) - 1;
409 if (pc_workers > 1)
410 errs |= run_parallel_checkout(&state, pc_workers, pc_threshold,
411 NULL, NULL);
412 mem_pool_discard(&ce_mem_pool, should_validate_cache_entries());
413 remove_marked_cache_entries(&the_index, 1);
414 remove_scheduled_dirs();
415 errs |= finish_delayed_checkout(&state, &nr_checkouts, opts->show_progress);
417 if (opts->count_checkout_paths) {
418 if (nr_unmerged)
419 fprintf_ln(stderr, Q_("Recreated %d merge conflict",
420 "Recreated %d merge conflicts",
421 nr_unmerged),
422 nr_unmerged);
423 if (opts->source_tree)
424 fprintf_ln(stderr, Q_("Updated %d path from %s",
425 "Updated %d paths from %s",
426 nr_checkouts),
427 nr_checkouts,
428 find_unique_abbrev(&opts->source_tree->object.oid,
429 DEFAULT_ABBREV));
430 else if (!nr_unmerged || nr_checkouts)
431 fprintf_ln(stderr, Q_("Updated %d path from the index",
432 "Updated %d paths from the index",
433 nr_checkouts),
434 nr_checkouts);
437 return errs;
440 static int checkout_paths(const struct checkout_opts *opts,
441 const struct branch_info *new_branch_info)
443 int pos;
444 static char *ps_matched;
445 struct object_id rev;
446 struct commit *head;
447 int errs = 0;
448 struct lock_file lock_file = LOCK_INIT;
449 int checkout_index;
451 trace2_cmd_mode(opts->patch_mode ? "patch" : "path");
453 if (opts->track != BRANCH_TRACK_UNSPECIFIED)
454 die(_("'%s' cannot be used with updating paths"), "--track");
456 if (opts->new_branch_log)
457 die(_("'%s' cannot be used with updating paths"), "-l");
459 if (opts->ignore_unmerged && opts->patch_mode)
460 die(_("'%s' cannot be used with updating paths"),
461 opts->ignore_unmerged_opt);
463 if (opts->force_detach)
464 die(_("'%s' cannot be used with updating paths"), "--detach");
466 if (opts->merge && opts->patch_mode)
467 die(_("options '%s' and '%s' cannot be used together"), "--merge", "--patch");
469 if (opts->ignore_unmerged && opts->merge)
470 die(_("options '%s' and '%s' cannot be used together"),
471 opts->ignore_unmerged_opt, "-m");
473 if (opts->new_branch)
474 die(_("Cannot update paths and switch to branch '%s' at the same time."),
475 opts->new_branch);
477 if (!opts->checkout_worktree && !opts->checkout_index)
478 die(_("neither '%s' or '%s' is specified"),
479 "--staged", "--worktree");
481 if (!opts->checkout_worktree && !opts->from_treeish)
482 die(_("'%s' must be used when '%s' is not specified"),
483 "--worktree", "--source");
485 if (opts->checkout_index && !opts->checkout_worktree &&
486 opts->writeout_stage)
487 die(_("'%s' or '%s' cannot be used with %s"),
488 "--ours", "--theirs", "--staged");
490 if (opts->checkout_index && !opts->checkout_worktree &&
491 opts->merge)
492 die(_("'%s' or '%s' cannot be used with %s"),
493 "--merge", "--conflict", "--staged");
495 if (opts->patch_mode) {
496 const char *patch_mode;
497 const char *rev = new_branch_info->name;
498 char rev_oid[GIT_MAX_HEXSZ + 1];
501 * Since rev can be in the form of `<a>...<b>` (which is not
502 * recognized by diff-index), we will always replace the name
503 * with the hex of the commit (whether it's in `...` form or
504 * not) for the run_add_interactive() machinery to work
505 * properly. However, there is special logic for the HEAD case
506 * so we mustn't replace that. Also, when we were given a
507 * tree-object, new_branch_info->commit would be NULL, but we
508 * do not have to do any replacement, either.
510 if (rev && new_branch_info->commit && strcmp(rev, "HEAD"))
511 rev = oid_to_hex_r(rev_oid, &new_branch_info->commit->object.oid);
513 if (opts->checkout_index && opts->checkout_worktree)
514 patch_mode = "--patch=checkout";
515 else if (opts->checkout_index && !opts->checkout_worktree)
516 patch_mode = "--patch=reset";
517 else if (!opts->checkout_index && opts->checkout_worktree)
518 patch_mode = "--patch=worktree";
519 else
520 BUG("either flag must have been set, worktree=%d, index=%d",
521 opts->checkout_worktree, opts->checkout_index);
522 return run_add_interactive(rev, patch_mode, &opts->pathspec);
525 repo_hold_locked_index(the_repository, &lock_file, LOCK_DIE_ON_ERROR);
526 if (read_cache_preload(&opts->pathspec) < 0)
527 return error(_("index file corrupt"));
529 if (opts->source_tree)
530 read_tree_some(opts->source_tree, &opts->pathspec);
532 ps_matched = xcalloc(opts->pathspec.nr, 1);
535 * Make sure all pathspecs participated in locating the paths
536 * to be checked out.
538 for (pos = 0; pos < active_nr; pos++)
539 if (opts->overlay_mode)
540 mark_ce_for_checkout_overlay(active_cache[pos],
541 ps_matched,
542 opts);
543 else
544 mark_ce_for_checkout_no_overlay(active_cache[pos],
545 ps_matched,
546 opts);
548 if (report_path_error(ps_matched, &opts->pathspec)) {
549 free(ps_matched);
550 return 1;
552 free(ps_matched);
554 /* "checkout -m path" to recreate conflicted state */
555 if (opts->merge)
556 unmerge_marked_index(&the_index);
558 /* Any unmerged paths? */
559 for (pos = 0; pos < active_nr; pos++) {
560 const struct cache_entry *ce = active_cache[pos];
561 if (ce->ce_flags & CE_MATCHED) {
562 if (!ce_stage(ce))
563 continue;
564 if (opts->ignore_unmerged) {
565 if (!opts->quiet)
566 warning(_("path '%s' is unmerged"), ce->name);
567 } else if (opts->writeout_stage) {
568 errs |= check_stage(opts->writeout_stage, ce, pos, opts->overlay_mode);
569 } else if (opts->merge) {
570 errs |= check_stages((1<<2) | (1<<3), ce, pos);
571 } else {
572 errs = 1;
573 error(_("path '%s' is unmerged"), ce->name);
575 pos = skip_same_name(ce, pos) - 1;
578 if (errs)
579 return 1;
581 /* Now we are committed to check them out */
582 if (opts->checkout_worktree)
583 errs |= checkout_worktree(opts, new_branch_info);
584 else
585 remove_marked_cache_entries(&the_index, 1);
588 * Allow updating the index when checking out from the index.
589 * This is to save new stat info.
591 if (opts->checkout_worktree && !opts->checkout_index && !opts->source_tree)
592 checkout_index = 1;
593 else
594 checkout_index = opts->checkout_index;
596 if (checkout_index) {
597 if (write_locked_index(&the_index, &lock_file, COMMIT_LOCK))
598 die(_("unable to write new index file"));
599 } else {
601 * NEEDSWORK: if --worktree is not specified, we
602 * should save stat info of checked out files in the
603 * index to avoid the next (potentially costly)
604 * refresh. But it's a bit tricker to do...
606 rollback_lock_file(&lock_file);
609 read_ref_full("HEAD", 0, &rev, NULL);
610 head = lookup_commit_reference_gently(the_repository, &rev, 1);
612 errs |= post_checkout_hook(head, head, 0);
613 return errs;
616 static void show_local_changes(struct object *head,
617 const struct diff_options *opts)
619 struct rev_info rev;
620 /* I think we want full paths, even if we're in a subdirectory. */
621 repo_init_revisions(the_repository, &rev, NULL);
622 rev.diffopt.flags = opts->flags;
623 rev.diffopt.output_format |= DIFF_FORMAT_NAME_STATUS;
624 diff_setup_done(&rev.diffopt);
625 add_pending_object(&rev, head, NULL);
626 run_diff_index(&rev, 0);
627 object_array_clear(&rev.pending);
630 static void describe_detached_head(const char *msg, struct commit *commit)
632 struct strbuf sb = STRBUF_INIT;
634 if (!parse_commit(commit))
635 pp_commit_easy(CMIT_FMT_ONELINE, commit, &sb);
636 if (print_sha1_ellipsis()) {
637 fprintf(stderr, "%s %s... %s\n", msg,
638 find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV), sb.buf);
639 } else {
640 fprintf(stderr, "%s %s %s\n", msg,
641 find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV), sb.buf);
643 strbuf_release(&sb);
646 static int reset_tree(struct tree *tree, const struct checkout_opts *o,
647 int worktree, int *writeout_error,
648 struct branch_info *info)
650 struct unpack_trees_options opts;
651 struct tree_desc tree_desc;
653 memset(&opts, 0, sizeof(opts));
654 opts.head_idx = -1;
655 opts.update = worktree;
656 opts.skip_unmerged = !worktree;
657 opts.reset = o->force ? UNPACK_RESET_OVERWRITE_UNTRACKED :
658 UNPACK_RESET_PROTECT_UNTRACKED;
659 opts.preserve_ignored = (!o->force && !o->overwrite_ignore);
660 opts.merge = 1;
661 opts.fn = oneway_merge;
662 opts.verbose_update = o->show_progress;
663 opts.src_index = &the_index;
664 opts.dst_index = &the_index;
665 init_checkout_metadata(&opts.meta, info->refname,
666 info->commit ? &info->commit->object.oid : null_oid(),
667 NULL);
668 parse_tree(tree);
669 init_tree_desc(&tree_desc, tree->buffer, tree->size);
670 switch (unpack_trees(1, &tree_desc, &opts)) {
671 case -2:
672 *writeout_error = 1;
674 * We return 0 nevertheless, as the index is all right
675 * and more importantly we have made best efforts to
676 * update paths in the work tree, and we cannot revert
677 * them.
679 /* fallthrough */
680 case 0:
681 return 0;
682 default:
683 return 128;
687 static void setup_branch_path(struct branch_info *branch)
689 struct strbuf buf = STRBUF_INIT;
692 * If this is a ref, resolve it; otherwise, look up the OID for our
693 * expression. Failure here is okay.
695 if (!dwim_ref(branch->name, strlen(branch->name), &branch->oid, &branch->refname, 0))
696 repo_get_oid_committish(the_repository, branch->name, &branch->oid);
698 strbuf_branchname(&buf, branch->name, INTERPRET_BRANCH_LOCAL);
699 if (strcmp(buf.buf, branch->name)) {
700 free(branch->name);
701 branch->name = xstrdup(buf.buf);
703 strbuf_splice(&buf, 0, 0, "refs/heads/", 11);
704 free(branch->path);
705 branch->path = strbuf_detach(&buf, NULL);
708 static int merge_working_tree(const struct checkout_opts *opts,
709 struct branch_info *old_branch_info,
710 struct branch_info *new_branch_info,
711 int *writeout_error)
713 int ret;
714 struct lock_file lock_file = LOCK_INIT;
715 struct tree *new_tree;
717 hold_locked_index(&lock_file, LOCK_DIE_ON_ERROR);
718 if (read_cache_preload(NULL) < 0)
719 return error(_("index file corrupt"));
721 resolve_undo_clear();
722 if (opts->new_orphan_branch && opts->orphan_from_empty_tree) {
723 if (new_branch_info->commit)
724 BUG("'switch --orphan' should never accept a commit as starting point");
725 new_tree = parse_tree_indirect(the_hash_algo->empty_tree);
726 } else
727 new_tree = get_commit_tree(new_branch_info->commit);
728 if (opts->discard_changes) {
729 ret = reset_tree(new_tree, opts, 1, writeout_error, new_branch_info);
730 if (ret)
731 return ret;
732 } else {
733 struct tree_desc trees[2];
734 struct tree *tree;
735 struct unpack_trees_options topts;
737 memset(&topts, 0, sizeof(topts));
738 topts.head_idx = -1;
739 topts.src_index = &the_index;
740 topts.dst_index = &the_index;
742 setup_unpack_trees_porcelain(&topts, "checkout");
744 refresh_cache(REFRESH_QUIET);
746 if (unmerged_cache()) {
747 error(_("you need to resolve your current index first"));
748 return 1;
751 /* 2-way merge to the new branch */
752 topts.initial_checkout = is_cache_unborn();
753 topts.update = 1;
754 topts.merge = 1;
755 topts.quiet = opts->merge && old_branch_info->commit;
756 topts.verbose_update = opts->show_progress;
757 topts.fn = twoway_merge;
758 init_checkout_metadata(&topts.meta, new_branch_info->refname,
759 new_branch_info->commit ?
760 &new_branch_info->commit->object.oid :
761 &new_branch_info->oid, NULL);
762 topts.preserve_ignored = !opts->overwrite_ignore;
763 tree = parse_tree_indirect(old_branch_info->commit ?
764 &old_branch_info->commit->object.oid :
765 the_hash_algo->empty_tree);
766 init_tree_desc(&trees[0], tree->buffer, tree->size);
767 parse_tree(new_tree);
768 tree = new_tree;
769 init_tree_desc(&trees[1], tree->buffer, tree->size);
771 ret = unpack_trees(2, trees, &topts);
772 clear_unpack_trees_porcelain(&topts);
773 if (ret == -1) {
775 * Unpack couldn't do a trivial merge; either
776 * give up or do a real merge, depending on
777 * whether the merge flag was used.
779 struct tree *work;
780 struct tree *old_tree;
781 struct merge_options o;
782 struct strbuf sb = STRBUF_INIT;
783 struct strbuf old_commit_shortname = STRBUF_INIT;
785 if (!opts->merge)
786 return 1;
789 * Without old_branch_info->commit, the below is the same as
790 * the two-tree unpack we already tried and failed.
792 if (!old_branch_info->commit)
793 return 1;
794 old_tree = get_commit_tree(old_branch_info->commit);
796 if (repo_index_has_changes(the_repository, old_tree, &sb))
797 die(_("cannot continue with staged changes in "
798 "the following files:\n%s"), sb.buf);
799 strbuf_release(&sb);
801 /* Do more real merge */
804 * We update the index fully, then write the
805 * tree from the index, then merge the new
806 * branch with the current tree, with the old
807 * branch as the base. Then we reset the index
808 * (but not the working tree) to the new
809 * branch, leaving the working tree as the
810 * merged version, but skipping unmerged
811 * entries in the index.
814 add_files_to_cache(NULL, NULL, 0);
815 init_merge_options(&o, the_repository);
816 o.verbosity = 0;
817 work = write_in_core_index_as_tree(the_repository);
819 ret = reset_tree(new_tree,
820 opts, 1,
821 writeout_error, new_branch_info);
822 if (ret)
823 return ret;
824 o.ancestor = old_branch_info->name;
825 if (old_branch_info->name == NULL) {
826 strbuf_add_unique_abbrev(&old_commit_shortname,
827 &old_branch_info->commit->object.oid,
828 DEFAULT_ABBREV);
829 o.ancestor = old_commit_shortname.buf;
831 o.branch1 = new_branch_info->name;
832 o.branch2 = "local";
833 ret = merge_trees(&o,
834 new_tree,
835 work,
836 old_tree);
837 if (ret < 0)
838 exit(128);
839 ret = reset_tree(new_tree,
840 opts, 0,
841 writeout_error, new_branch_info);
842 strbuf_release(&o.obuf);
843 strbuf_release(&old_commit_shortname);
844 if (ret)
845 return ret;
849 if (!cache_tree_fully_valid(active_cache_tree))
850 cache_tree_update(&the_index, WRITE_TREE_SILENT | WRITE_TREE_REPAIR);
852 if (write_locked_index(&the_index, &lock_file, COMMIT_LOCK))
853 die(_("unable to write new index file"));
855 if (!opts->discard_changes && !opts->quiet && new_branch_info->commit)
856 show_local_changes(&new_branch_info->commit->object, &opts->diff_options);
858 return 0;
861 static void report_tracking(struct branch_info *new_branch_info)
863 struct strbuf sb = STRBUF_INIT;
864 struct branch *branch = branch_get(new_branch_info->name);
866 if (!format_tracking_info(branch, &sb, AHEAD_BEHIND_FULL))
867 return;
868 fputs(sb.buf, stdout);
869 strbuf_release(&sb);
872 static void update_refs_for_switch(const struct checkout_opts *opts,
873 struct branch_info *old_branch_info,
874 struct branch_info *new_branch_info)
876 struct strbuf msg = STRBUF_INIT;
877 const char *old_desc, *reflog_msg;
878 if (opts->new_branch) {
879 if (opts->new_orphan_branch) {
880 char *refname;
882 refname = mkpathdup("refs/heads/%s", opts->new_orphan_branch);
883 if (opts->new_branch_log &&
884 !should_autocreate_reflog(refname)) {
885 int ret;
886 struct strbuf err = STRBUF_INIT;
888 ret = safe_create_reflog(refname, &err);
889 if (ret) {
890 fprintf(stderr, _("Can not do reflog for '%s': %s\n"),
891 opts->new_orphan_branch, err.buf);
892 strbuf_release(&err);
893 free(refname);
894 return;
896 strbuf_release(&err);
898 free(refname);
900 else
901 create_branch(the_repository,
902 opts->new_branch, new_branch_info->name,
903 opts->new_branch_force ? 1 : 0,
904 opts->new_branch_force ? 1 : 0,
905 opts->new_branch_log,
906 opts->quiet,
907 opts->track);
908 free(new_branch_info->name);
909 free(new_branch_info->refname);
910 new_branch_info->name = xstrdup(opts->new_branch);
911 setup_branch_path(new_branch_info);
914 old_desc = old_branch_info->name;
915 if (!old_desc && old_branch_info->commit)
916 old_desc = oid_to_hex(&old_branch_info->commit->object.oid);
918 reflog_msg = getenv("GIT_REFLOG_ACTION");
919 if (!reflog_msg)
920 strbuf_addf(&msg, "checkout: moving from %s to %s",
921 old_desc ? old_desc : "(invalid)", new_branch_info->name);
922 else
923 strbuf_insertstr(&msg, 0, reflog_msg);
925 if (!strcmp(new_branch_info->name, "HEAD") && !new_branch_info->path && !opts->force_detach) {
926 /* Nothing to do. */
927 } else if (opts->force_detach || !new_branch_info->path) { /* No longer on any branch. */
928 update_ref(msg.buf, "HEAD", &new_branch_info->commit->object.oid, NULL,
929 REF_NO_DEREF, UPDATE_REFS_DIE_ON_ERR);
930 if (!opts->quiet) {
931 if (old_branch_info->path &&
932 advice_enabled(ADVICE_DETACHED_HEAD) && !opts->force_detach)
933 detach_advice(new_branch_info->name);
934 describe_detached_head(_("HEAD is now at"), new_branch_info->commit);
936 } else if (new_branch_info->path) { /* Switch branches. */
937 if (create_symref("HEAD", new_branch_info->path, msg.buf) < 0)
938 die(_("unable to update HEAD"));
939 if (!opts->quiet) {
940 if (old_branch_info->path && !strcmp(new_branch_info->path, old_branch_info->path)) {
941 if (opts->new_branch_force)
942 fprintf(stderr, _("Reset branch '%s'\n"),
943 new_branch_info->name);
944 else
945 fprintf(stderr, _("Already on '%s'\n"),
946 new_branch_info->name);
947 } else if (opts->new_branch) {
948 if (opts->branch_exists)
949 fprintf(stderr, _("Switched to and reset branch '%s'\n"), new_branch_info->name);
950 else
951 fprintf(stderr, _("Switched to a new branch '%s'\n"), new_branch_info->name);
952 } else {
953 fprintf(stderr, _("Switched to branch '%s'\n"),
954 new_branch_info->name);
957 if (old_branch_info->path && old_branch_info->name) {
958 if (!ref_exists(old_branch_info->path) && reflog_exists(old_branch_info->path))
959 delete_reflog(old_branch_info->path);
962 remove_branch_state(the_repository, !opts->quiet);
963 strbuf_release(&msg);
964 if (!opts->quiet &&
965 (new_branch_info->path || (!opts->force_detach && !strcmp(new_branch_info->name, "HEAD"))))
966 report_tracking(new_branch_info);
969 static int add_pending_uninteresting_ref(const char *refname,
970 const struct object_id *oid,
971 int flags, void *cb_data)
973 add_pending_oid(cb_data, refname, oid, UNINTERESTING);
974 return 0;
977 static void describe_one_orphan(struct strbuf *sb, struct commit *commit)
979 strbuf_addstr(sb, " ");
980 strbuf_add_unique_abbrev(sb, &commit->object.oid, DEFAULT_ABBREV);
981 strbuf_addch(sb, ' ');
982 if (!parse_commit(commit))
983 pp_commit_easy(CMIT_FMT_ONELINE, commit, sb);
984 strbuf_addch(sb, '\n');
987 #define ORPHAN_CUTOFF 4
988 static void suggest_reattach(struct commit *commit, struct rev_info *revs)
990 struct commit *c, *last = NULL;
991 struct strbuf sb = STRBUF_INIT;
992 int lost = 0;
993 while ((c = get_revision(revs)) != NULL) {
994 if (lost < ORPHAN_CUTOFF)
995 describe_one_orphan(&sb, c);
996 last = c;
997 lost++;
999 if (ORPHAN_CUTOFF < lost) {
1000 int more = lost - ORPHAN_CUTOFF;
1001 if (more == 1)
1002 describe_one_orphan(&sb, last);
1003 else
1004 strbuf_addf(&sb, _(" ... and %d more.\n"), more);
1007 fprintf(stderr,
1009 /* The singular version */
1010 "Warning: you are leaving %d commit behind, "
1011 "not connected to\n"
1012 "any of your branches:\n\n"
1013 "%s\n",
1014 /* The plural version */
1015 "Warning: you are leaving %d commits behind, "
1016 "not connected to\n"
1017 "any of your branches:\n\n"
1018 "%s\n",
1019 /* Give ngettext() the count */
1020 lost),
1021 lost,
1022 sb.buf);
1023 strbuf_release(&sb);
1025 if (advice_enabled(ADVICE_DETACHED_HEAD))
1026 fprintf(stderr,
1028 /* The singular version */
1029 "If you want to keep it by creating a new branch, "
1030 "this may be a good time\nto do so with:\n\n"
1031 " git branch <new-branch-name> %s\n\n",
1032 /* The plural version */
1033 "If you want to keep them by creating a new branch, "
1034 "this may be a good time\nto do so with:\n\n"
1035 " git branch <new-branch-name> %s\n\n",
1036 /* Give ngettext() the count */
1037 lost),
1038 find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV));
1042 * We are about to leave commit that was at the tip of a detached
1043 * HEAD. If it is not reachable from any ref, this is the last chance
1044 * for the user to do so without resorting to reflog.
1046 static void orphaned_commit_warning(struct commit *old_commit, struct commit *new_commit)
1048 struct rev_info revs;
1049 struct object *object = &old_commit->object;
1051 repo_init_revisions(the_repository, &revs, NULL);
1052 setup_revisions(0, NULL, &revs, NULL);
1054 object->flags &= ~UNINTERESTING;
1055 add_pending_object(&revs, object, oid_to_hex(&object->oid));
1057 for_each_ref(add_pending_uninteresting_ref, &revs);
1058 if (new_commit)
1059 add_pending_oid(&revs, "HEAD",
1060 &new_commit->object.oid,
1061 UNINTERESTING);
1063 if (prepare_revision_walk(&revs))
1064 die(_("internal error in revision walk"));
1065 if (!(old_commit->object.flags & UNINTERESTING))
1066 suggest_reattach(old_commit, &revs);
1067 else
1068 describe_detached_head(_("Previous HEAD position was"), old_commit);
1070 /* Clean up objects used, as they will be reused. */
1071 repo_clear_commit_marks(the_repository, ALL_REV_FLAGS);
1074 static int switch_branches(const struct checkout_opts *opts,
1075 struct branch_info *new_branch_info)
1077 int ret = 0;
1078 struct branch_info old_branch_info = { 0 };
1079 struct object_id rev;
1080 int flag, writeout_error = 0;
1081 int do_merge = 1;
1083 trace2_cmd_mode("branch");
1085 memset(&old_branch_info, 0, sizeof(old_branch_info));
1086 old_branch_info.path = resolve_refdup("HEAD", 0, &rev, &flag);
1087 if (old_branch_info.path)
1088 old_branch_info.commit = lookup_commit_reference_gently(the_repository, &rev, 1);
1089 if (!(flag & REF_ISSYMREF))
1090 FREE_AND_NULL(old_branch_info.path);
1092 if (old_branch_info.path) {
1093 const char *const prefix = "refs/heads/";
1094 const char *p;
1095 if (skip_prefix(old_branch_info.path, prefix, &p))
1096 old_branch_info.name = xstrdup(p);
1099 if (opts->new_orphan_branch && opts->orphan_from_empty_tree) {
1100 if (new_branch_info->name)
1101 BUG("'switch --orphan' should never accept a commit as starting point");
1102 new_branch_info->commit = NULL;
1103 new_branch_info->name = xstrdup("(empty)");
1104 do_merge = 1;
1107 if (!new_branch_info->name) {
1108 new_branch_info->name = xstrdup("HEAD");
1109 new_branch_info->commit = old_branch_info.commit;
1110 if (!new_branch_info->commit)
1111 die(_("You are on a branch yet to be born"));
1112 parse_commit_or_die(new_branch_info->commit);
1114 if (opts->only_merge_on_switching_branches)
1115 do_merge = 0;
1118 if (do_merge) {
1119 ret = merge_working_tree(opts, &old_branch_info, new_branch_info, &writeout_error);
1120 if (ret) {
1121 branch_info_release(&old_branch_info);
1122 return ret;
1126 if (!opts->quiet && !old_branch_info.path && old_branch_info.commit && new_branch_info->commit != old_branch_info.commit)
1127 orphaned_commit_warning(old_branch_info.commit, new_branch_info->commit);
1129 update_refs_for_switch(opts, &old_branch_info, new_branch_info);
1131 ret = post_checkout_hook(old_branch_info.commit, new_branch_info->commit, 1);
1132 branch_info_release(&old_branch_info);
1134 return ret || writeout_error;
1137 static int git_checkout_config(const char *var, const char *value, void *cb)
1139 struct checkout_opts *opts = cb;
1141 if (!strcmp(var, "diff.ignoresubmodules")) {
1142 handle_ignore_submodules_arg(&opts->diff_options, value);
1143 return 0;
1145 if (!strcmp(var, "checkout.guess")) {
1146 opts->dwim_new_local_branch = git_config_bool(var, value);
1147 return 0;
1150 if (starts_with(var, "submodule."))
1151 return git_default_submodule_config(var, value, NULL);
1153 return git_xmerge_config(var, value, NULL);
1156 static void setup_new_branch_info_and_source_tree(
1157 struct branch_info *new_branch_info,
1158 struct checkout_opts *opts,
1159 struct object_id *rev,
1160 const char *arg)
1162 struct tree **source_tree = &opts->source_tree;
1163 struct object_id branch_rev;
1165 new_branch_info->name = xstrdup(arg);
1166 setup_branch_path(new_branch_info);
1168 if (!check_refname_format(new_branch_info->path, 0) &&
1169 !read_ref(new_branch_info->path, &branch_rev))
1170 oidcpy(rev, &branch_rev);
1171 else
1172 /* not an existing branch */
1173 FREE_AND_NULL(new_branch_info->path);
1175 new_branch_info->commit = lookup_commit_reference_gently(the_repository, rev, 1);
1176 if (!new_branch_info->commit) {
1177 /* not a commit */
1178 *source_tree = parse_tree_indirect(rev);
1179 } else {
1180 parse_commit_or_die(new_branch_info->commit);
1181 *source_tree = get_commit_tree(new_branch_info->commit);
1185 static const char *parse_remote_branch(const char *arg,
1186 struct object_id *rev,
1187 int could_be_checkout_paths)
1189 int num_matches = 0;
1190 const char *remote = unique_tracking_name(arg, rev, &num_matches);
1192 if (remote && could_be_checkout_paths) {
1193 die(_("'%s' could be both a local file and a tracking branch.\n"
1194 "Please use -- (and optionally --no-guess) to disambiguate"),
1195 arg);
1198 if (!remote && num_matches > 1) {
1199 if (advice_enabled(ADVICE_CHECKOUT_AMBIGUOUS_REMOTE_BRANCH_NAME)) {
1200 advise(_("If you meant to check out a remote tracking branch on, e.g. 'origin',\n"
1201 "you can do so by fully qualifying the name with the --track option:\n"
1202 "\n"
1203 " git checkout --track origin/<name>\n"
1204 "\n"
1205 "If you'd like to always have checkouts of an ambiguous <name> prefer\n"
1206 "one remote, e.g. the 'origin' remote, consider setting\n"
1207 "checkout.defaultRemote=origin in your config."));
1210 die(_("'%s' matched multiple (%d) remote tracking branches"),
1211 arg, num_matches);
1214 return remote;
1217 static int parse_branchname_arg(int argc, const char **argv,
1218 int dwim_new_local_branch_ok,
1219 struct branch_info *new_branch_info,
1220 struct checkout_opts *opts,
1221 struct object_id *rev)
1223 const char **new_branch = &opts->new_branch;
1224 int argcount = 0;
1225 const char *arg;
1226 int dash_dash_pos;
1227 int has_dash_dash = 0;
1228 int i;
1231 * case 1: git checkout <ref> -- [<paths>]
1233 * <ref> must be a valid tree, everything after the '--' must be
1234 * a path.
1236 * case 2: git checkout -- [<paths>]
1238 * everything after the '--' must be paths.
1240 * case 3: git checkout <something> [--]
1242 * (a) If <something> is a commit, that is to
1243 * switch to the branch or detach HEAD at it. As a special case,
1244 * if <something> is A...B (missing A or B means HEAD but you can
1245 * omit at most one side), and if there is a unique merge base
1246 * between A and B, A...B names that merge base.
1248 * (b) If <something> is _not_ a commit, either "--" is present
1249 * or <something> is not a path, no -t or -b was given, and
1250 * and there is a tracking branch whose name is <something>
1251 * in one and only one remote (or if the branch exists on the
1252 * remote named in checkout.defaultRemote), then this is a
1253 * short-hand to fork local <something> from that
1254 * remote-tracking branch.
1256 * (c) Otherwise, if "--" is present, treat it like case (1).
1258 * (d) Otherwise :
1259 * - if it's a reference, treat it like case (1)
1260 * - else if it's a path, treat it like case (2)
1261 * - else: fail.
1263 * case 4: git checkout <something> <paths>
1265 * The first argument must not be ambiguous.
1266 * - If it's *only* a reference, treat it like case (1).
1267 * - If it's only a path, treat it like case (2).
1268 * - else: fail.
1271 if (!argc)
1272 return 0;
1274 if (!opts->accept_pathspec) {
1275 if (argc > 1)
1276 die(_("only one reference expected"));
1277 has_dash_dash = 1; /* helps disambiguate */
1280 arg = argv[0];
1281 dash_dash_pos = -1;
1282 for (i = 0; i < argc; i++) {
1283 if (opts->accept_pathspec && !strcmp(argv[i], "--")) {
1284 dash_dash_pos = i;
1285 break;
1288 if (dash_dash_pos == 0)
1289 return 1; /* case (2) */
1290 else if (dash_dash_pos == 1)
1291 has_dash_dash = 1; /* case (3) or (1) */
1292 else if (dash_dash_pos >= 2)
1293 die(_("only one reference expected, %d given."), dash_dash_pos);
1294 opts->count_checkout_paths = !opts->quiet && !has_dash_dash;
1296 if (!strcmp(arg, "-"))
1297 arg = "@{-1}";
1299 if (get_oid_mb(arg, rev)) {
1301 * Either case (3) or (4), with <something> not being
1302 * a commit, or an attempt to use case (1) with an
1303 * invalid ref.
1305 * It's likely an error, but we need to find out if
1306 * we should auto-create the branch, case (3).(b).
1308 int recover_with_dwim = dwim_new_local_branch_ok;
1310 int could_be_checkout_paths = !has_dash_dash &&
1311 check_filename(opts->prefix, arg);
1313 if (!has_dash_dash && !no_wildcard(arg))
1314 recover_with_dwim = 0;
1317 * Accept "git checkout foo", "git checkout foo --"
1318 * and "git switch foo" as candidates for dwim.
1320 if (!(argc == 1 && !has_dash_dash) &&
1321 !(argc == 2 && has_dash_dash) &&
1322 opts->accept_pathspec)
1323 recover_with_dwim = 0;
1325 if (recover_with_dwim) {
1326 const char *remote = parse_remote_branch(arg, rev,
1327 could_be_checkout_paths);
1328 if (remote) {
1329 *new_branch = arg;
1330 arg = remote;
1331 /* DWIMmed to create local branch, case (3).(b) */
1332 } else {
1333 recover_with_dwim = 0;
1337 if (!recover_with_dwim) {
1338 if (has_dash_dash)
1339 die(_("invalid reference: %s"), arg);
1340 return argcount;
1344 /* we can't end up being in (2) anymore, eat the argument */
1345 argcount++;
1346 argv++;
1347 argc--;
1349 setup_new_branch_info_and_source_tree(new_branch_info, opts, rev, arg);
1351 if (!opts->source_tree) /* case (1): want a tree */
1352 die(_("reference is not a tree: %s"), arg);
1354 if (!has_dash_dash) { /* case (3).(d) -> (1) */
1356 * Do not complain the most common case
1357 * git checkout branch
1358 * even if there happen to be a file called 'branch';
1359 * it would be extremely annoying.
1361 if (argc)
1362 verify_non_filename(opts->prefix, arg);
1363 } else if (opts->accept_pathspec) {
1364 argcount++;
1365 argv++;
1366 argc--;
1369 return argcount;
1372 static int switch_unborn_to_new_branch(const struct checkout_opts *opts)
1374 int status;
1375 struct strbuf branch_ref = STRBUF_INIT;
1377 trace2_cmd_mode("unborn");
1379 if (!opts->new_branch)
1380 die(_("You are on a branch yet to be born"));
1381 strbuf_addf(&branch_ref, "refs/heads/%s", opts->new_branch);
1382 status = create_symref("HEAD", branch_ref.buf, "checkout -b");
1383 strbuf_release(&branch_ref);
1384 if (!opts->quiet)
1385 fprintf(stderr, _("Switched to a new branch '%s'\n"),
1386 opts->new_branch);
1387 return status;
1390 static void die_expecting_a_branch(const struct branch_info *branch_info)
1392 struct object_id oid;
1393 char *to_free;
1395 if (dwim_ref(branch_info->name, strlen(branch_info->name), &oid, &to_free, 0) == 1) {
1396 const char *ref = to_free;
1398 if (skip_prefix(ref, "refs/tags/", &ref))
1399 die(_("a branch is expected, got tag '%s'"), ref);
1400 if (skip_prefix(ref, "refs/remotes/", &ref))
1401 die(_("a branch is expected, got remote branch '%s'"), ref);
1402 die(_("a branch is expected, got '%s'"), ref);
1404 if (branch_info->commit)
1405 die(_("a branch is expected, got commit '%s'"), branch_info->name);
1407 * This case should never happen because we already die() on
1408 * non-commit, but just in case.
1410 die(_("a branch is expected, got '%s'"), branch_info->name);
1413 static void die_if_some_operation_in_progress(void)
1415 struct wt_status_state state;
1417 memset(&state, 0, sizeof(state));
1418 wt_status_get_state(the_repository, &state, 0);
1420 if (state.merge_in_progress)
1421 die(_("cannot switch branch while merging\n"
1422 "Consider \"git merge --quit\" "
1423 "or \"git worktree add\"."));
1424 if (state.am_in_progress)
1425 die(_("cannot switch branch in the middle of an am session\n"
1426 "Consider \"git am --quit\" "
1427 "or \"git worktree add\"."));
1428 if (state.rebase_interactive_in_progress || state.rebase_in_progress)
1429 die(_("cannot switch branch while rebasing\n"
1430 "Consider \"git rebase --quit\" "
1431 "or \"git worktree add\"."));
1432 if (state.cherry_pick_in_progress)
1433 die(_("cannot switch branch while cherry-picking\n"
1434 "Consider \"git cherry-pick --quit\" "
1435 "or \"git worktree add\"."));
1436 if (state.revert_in_progress)
1437 die(_("cannot switch branch while reverting\n"
1438 "Consider \"git revert --quit\" "
1439 "or \"git worktree add\"."));
1440 if (state.bisect_in_progress)
1441 warning(_("you are switching branch while bisecting"));
1444 static int checkout_branch(struct checkout_opts *opts,
1445 struct branch_info *new_branch_info)
1447 if (opts->pathspec.nr)
1448 die(_("paths cannot be used with switching branches"));
1450 if (opts->patch_mode)
1451 die(_("'%s' cannot be used with switching branches"),
1452 "--patch");
1454 if (opts->overlay_mode != -1)
1455 die(_("'%s' cannot be used with switching branches"),
1456 "--[no]-overlay");
1458 if (opts->writeout_stage)
1459 die(_("'%s' cannot be used with switching branches"),
1460 "--ours/--theirs");
1462 if (opts->force && opts->merge)
1463 die(_("'%s' cannot be used with '%s'"), "-f", "-m");
1465 if (opts->discard_changes && opts->merge)
1466 die(_("'%s' cannot be used with '%s'"), "--discard-changes", "--merge");
1468 if (opts->force_detach && opts->new_branch)
1469 die(_("'%s' cannot be used with '%s'"),
1470 "--detach", "-b/-B/--orphan");
1472 if (opts->new_orphan_branch) {
1473 if (opts->track != BRANCH_TRACK_UNSPECIFIED)
1474 die(_("'%s' cannot be used with '%s'"), "--orphan", "-t");
1475 if (opts->orphan_from_empty_tree && new_branch_info->name)
1476 die(_("'%s' cannot take <start-point>"), "--orphan");
1477 } else if (opts->force_detach) {
1478 if (opts->track != BRANCH_TRACK_UNSPECIFIED)
1479 die(_("'%s' cannot be used with '%s'"), "--detach", "-t");
1480 } else if (opts->track == BRANCH_TRACK_UNSPECIFIED)
1481 opts->track = git_branch_track;
1483 if (new_branch_info->name && !new_branch_info->commit)
1484 die(_("Cannot switch branch to a non-commit '%s'"),
1485 new_branch_info->name);
1487 if (!opts->switch_branch_doing_nothing_is_ok &&
1488 !new_branch_info->name &&
1489 !opts->new_branch &&
1490 !opts->force_detach)
1491 die(_("missing branch or commit argument"));
1493 if (!opts->implicit_detach &&
1494 !opts->force_detach &&
1495 !opts->new_branch &&
1496 !opts->new_branch_force &&
1497 new_branch_info->name &&
1498 !new_branch_info->path)
1499 die_expecting_a_branch(new_branch_info);
1501 if (!opts->can_switch_when_in_progress)
1502 die_if_some_operation_in_progress();
1504 if (new_branch_info->path && !opts->force_detach && !opts->new_branch &&
1505 !opts->ignore_other_worktrees) {
1506 int flag;
1507 char *head_ref = resolve_refdup("HEAD", 0, NULL, &flag);
1508 if (head_ref &&
1509 (!(flag & REF_ISSYMREF) || strcmp(head_ref, new_branch_info->path)))
1510 die_if_checked_out(new_branch_info->path, 1);
1511 free(head_ref);
1514 if (!new_branch_info->commit && opts->new_branch) {
1515 struct object_id rev;
1516 int flag;
1518 if (!read_ref_full("HEAD", 0, &rev, &flag) &&
1519 (flag & REF_ISSYMREF) && is_null_oid(&rev))
1520 return switch_unborn_to_new_branch(opts);
1522 return switch_branches(opts, new_branch_info);
1525 static struct option *add_common_options(struct checkout_opts *opts,
1526 struct option *prevopts)
1528 struct option options[] = {
1529 OPT__QUIET(&opts->quiet, N_("suppress progress reporting")),
1530 OPT_CALLBACK_F(0, "recurse-submodules", NULL,
1531 "checkout", "control recursive updating of submodules",
1532 PARSE_OPT_OPTARG, option_parse_recurse_submodules_worktree_updater),
1533 OPT_BOOL(0, "progress", &opts->show_progress, N_("force progress reporting")),
1534 OPT_BOOL('m', "merge", &opts->merge, N_("perform a 3-way merge with the new branch")),
1535 OPT_STRING(0, "conflict", &opts->conflict_style, N_("style"),
1536 N_("conflict style (merge, diff3, or zdiff3)")),
1537 OPT_END()
1539 struct option *newopts = parse_options_concat(prevopts, options);
1540 free(prevopts);
1541 return newopts;
1544 static struct option *add_common_switch_branch_options(
1545 struct checkout_opts *opts, struct option *prevopts)
1547 struct option options[] = {
1548 OPT_BOOL('d', "detach", &opts->force_detach, N_("detach HEAD at named commit")),
1549 OPT_CALLBACK_F('t', "track", &opts->track, "(direct|inherit)",
1550 N_("set branch tracking configuration"),
1551 PARSE_OPT_OPTARG,
1552 parse_opt_tracking_mode),
1553 OPT__FORCE(&opts->force, N_("force checkout (throw away local modifications)"),
1554 PARSE_OPT_NOCOMPLETE),
1555 OPT_STRING(0, "orphan", &opts->new_orphan_branch, N_("new-branch"), N_("new unparented branch")),
1556 OPT_BOOL_F(0, "overwrite-ignore", &opts->overwrite_ignore,
1557 N_("update ignored files (default)"),
1558 PARSE_OPT_NOCOMPLETE),
1559 OPT_BOOL(0, "ignore-other-worktrees", &opts->ignore_other_worktrees,
1560 N_("do not check if another worktree is holding the given ref")),
1561 OPT_END()
1563 struct option *newopts = parse_options_concat(prevopts, options);
1564 free(prevopts);
1565 return newopts;
1568 static struct option *add_checkout_path_options(struct checkout_opts *opts,
1569 struct option *prevopts)
1571 struct option options[] = {
1572 OPT_SET_INT_F('2', "ours", &opts->writeout_stage,
1573 N_("checkout our version for unmerged files"),
1574 2, PARSE_OPT_NONEG),
1575 OPT_SET_INT_F('3', "theirs", &opts->writeout_stage,
1576 N_("checkout their version for unmerged files"),
1577 3, PARSE_OPT_NONEG),
1578 OPT_BOOL('p', "patch", &opts->patch_mode, N_("select hunks interactively")),
1579 OPT_BOOL(0, "ignore-skip-worktree-bits", &opts->ignore_skipworktree,
1580 N_("do not limit pathspecs to sparse entries only")),
1581 OPT_PATHSPEC_FROM_FILE(&opts->pathspec_from_file),
1582 OPT_PATHSPEC_FILE_NUL(&opts->pathspec_file_nul),
1583 OPT_END()
1585 struct option *newopts = parse_options_concat(prevopts, options);
1586 free(prevopts);
1587 return newopts;
1590 /* create-branch option (either b or c) */
1591 static char cb_option = 'b';
1593 static int checkout_main(int argc, const char **argv, const char *prefix,
1594 struct checkout_opts *opts, struct option *options,
1595 const char * const usagestr[],
1596 struct branch_info *new_branch_info)
1598 int parseopt_flags = 0;
1600 opts->overwrite_ignore = 1;
1601 opts->prefix = prefix;
1602 opts->show_progress = -1;
1604 git_config(git_checkout_config, opts);
1606 prepare_repo_settings(the_repository);
1607 the_repository->settings.command_requires_full_index = 0;
1609 opts->track = BRANCH_TRACK_UNSPECIFIED;
1611 if (!opts->accept_pathspec && !opts->accept_ref)
1612 BUG("make up your mind, you need to take _something_");
1613 if (opts->accept_pathspec && opts->accept_ref)
1614 parseopt_flags = PARSE_OPT_KEEP_DASHDASH;
1616 argc = parse_options(argc, argv, prefix, options,
1617 usagestr, parseopt_flags);
1619 if (opts->show_progress < 0) {
1620 if (opts->quiet)
1621 opts->show_progress = 0;
1622 else
1623 opts->show_progress = isatty(2);
1626 if (opts->conflict_style) {
1627 opts->merge = 1; /* implied */
1628 git_xmerge_config("merge.conflictstyle", opts->conflict_style, NULL);
1630 if (opts->force) {
1631 opts->discard_changes = 1;
1632 opts->ignore_unmerged_opt = "--force";
1633 opts->ignore_unmerged = 1;
1636 if ((!!opts->new_branch + !!opts->new_branch_force + !!opts->new_orphan_branch) > 1)
1637 die(_("options '-%c', '-%c', and '%s' cannot be used together"),
1638 cb_option, toupper(cb_option), "--orphan");
1640 if (opts->overlay_mode == 1 && opts->patch_mode)
1641 die(_("options '%s' and '%s' cannot be used together"), "-p", "--overlay");
1643 if (opts->checkout_index >= 0 || opts->checkout_worktree >= 0) {
1644 if (opts->checkout_index < 0)
1645 opts->checkout_index = 0;
1646 if (opts->checkout_worktree < 0)
1647 opts->checkout_worktree = 0;
1648 } else {
1649 if (opts->checkout_index < 0)
1650 opts->checkout_index = -opts->checkout_index - 1;
1651 if (opts->checkout_worktree < 0)
1652 opts->checkout_worktree = -opts->checkout_worktree - 1;
1654 if (opts->checkout_index < 0 || opts->checkout_worktree < 0)
1655 BUG("these flags should be non-negative by now");
1657 * convenient shortcut: "git restore --staged [--worktree]" equals
1658 * "git restore --staged [--worktree] --source HEAD"
1660 if (!opts->from_treeish && opts->checkout_index)
1661 opts->from_treeish = "HEAD";
1664 * From here on, new_branch will contain the branch to be checked out,
1665 * and new_branch_force and new_orphan_branch will tell us which one of
1666 * -b/-B/-c/-C/--orphan is being used.
1668 if (opts->new_branch_force)
1669 opts->new_branch = opts->new_branch_force;
1671 if (opts->new_orphan_branch)
1672 opts->new_branch = opts->new_orphan_branch;
1674 /* --track without -c/-C/-b/-B/--orphan should DWIM */
1675 if (opts->track != BRANCH_TRACK_UNSPECIFIED && !opts->new_branch) {
1676 const char *argv0 = argv[0];
1677 if (!argc || !strcmp(argv0, "--"))
1678 die(_("--track needs a branch name"));
1679 skip_prefix(argv0, "refs/", &argv0);
1680 skip_prefix(argv0, "remotes/", &argv0);
1681 argv0 = strchr(argv0, '/');
1682 if (!argv0 || !argv0[1])
1683 die(_("missing branch name; try -%c"), cb_option);
1684 opts->new_branch = argv0 + 1;
1688 * Extract branch name from command line arguments, so
1689 * all that is left is pathspecs.
1691 * Handle
1693 * 1) git checkout <tree> -- [<paths>]
1694 * 2) git checkout -- [<paths>]
1695 * 3) git checkout <something> [<paths>]
1697 * including "last branch" syntax and DWIM-ery for names of
1698 * remote branches, erroring out for invalid or ambiguous cases.
1700 if (argc && opts->accept_ref) {
1701 struct object_id rev;
1702 int dwim_ok =
1703 !opts->patch_mode &&
1704 opts->dwim_new_local_branch &&
1705 opts->track == BRANCH_TRACK_UNSPECIFIED &&
1706 !opts->new_branch;
1707 int n = parse_branchname_arg(argc, argv, dwim_ok,
1708 new_branch_info, opts, &rev);
1709 argv += n;
1710 argc -= n;
1711 } else if (!opts->accept_ref && opts->from_treeish) {
1712 struct object_id rev;
1714 if (get_oid_mb(opts->from_treeish, &rev))
1715 die(_("could not resolve %s"), opts->from_treeish);
1717 setup_new_branch_info_and_source_tree(new_branch_info,
1718 opts, &rev,
1719 opts->from_treeish);
1721 if (!opts->source_tree)
1722 die(_("reference is not a tree: %s"), opts->from_treeish);
1725 if (argc) {
1726 parse_pathspec(&opts->pathspec, 0,
1727 opts->patch_mode ? PATHSPEC_PREFIX_ORIGIN : 0,
1728 prefix, argv);
1730 if (!opts->pathspec.nr)
1731 die(_("invalid path specification"));
1734 * Try to give more helpful suggestion.
1735 * new_branch && argc > 1 will be caught later.
1737 if (opts->new_branch && argc == 1 && !new_branch_info->commit)
1738 die(_("'%s' is not a commit and a branch '%s' cannot be created from it"),
1739 argv[0], opts->new_branch);
1741 if (opts->force_detach)
1742 die(_("git checkout: --detach does not take a path argument '%s'"),
1743 argv[0]);
1746 if (opts->pathspec_from_file) {
1747 if (opts->pathspec.nr)
1748 die(_("'%s' and pathspec arguments cannot be used together"), "--pathspec-from-file");
1750 if (opts->force_detach)
1751 die(_("options '%s' and '%s' cannot be used together"), "--pathspec-from-file", "--detach");
1753 if (opts->patch_mode)
1754 die(_("options '%s' and '%s' cannot be used together"), "--pathspec-from-file", "--patch");
1756 parse_pathspec_file(&opts->pathspec, 0,
1758 prefix, opts->pathspec_from_file, opts->pathspec_file_nul);
1759 } else if (opts->pathspec_file_nul) {
1760 die(_("the option '%s' requires '%s'"), "--pathspec-file-nul", "--pathspec-from-file");
1763 opts->pathspec.recursive = 1;
1765 if (opts->pathspec.nr) {
1766 if (1 < !!opts->writeout_stage + !!opts->force + !!opts->merge)
1767 die(_("git checkout: --ours/--theirs, --force and --merge are incompatible when\n"
1768 "checking out of the index."));
1769 } else {
1770 if (opts->accept_pathspec && !opts->empty_pathspec_ok &&
1771 !opts->patch_mode) /* patch mode is special */
1772 die(_("you must specify path(s) to restore"));
1775 if (opts->new_branch) {
1776 struct strbuf buf = STRBUF_INIT;
1778 if (opts->new_branch_force)
1779 opts->branch_exists = validate_branchname(opts->new_branch, &buf);
1780 else
1781 opts->branch_exists =
1782 validate_new_branchname(opts->new_branch, &buf, 0);
1783 strbuf_release(&buf);
1786 if (opts->patch_mode || opts->pathspec.nr)
1787 return checkout_paths(opts, new_branch_info);
1788 else
1789 return checkout_branch(opts, new_branch_info);
1792 int cmd_checkout(int argc, const char **argv, const char *prefix)
1794 struct checkout_opts opts;
1795 struct option *options;
1796 struct option checkout_options[] = {
1797 OPT_STRING('b', NULL, &opts.new_branch, N_("branch"),
1798 N_("create and checkout a new branch")),
1799 OPT_STRING('B', NULL, &opts.new_branch_force, N_("branch"),
1800 N_("create/reset and checkout a branch")),
1801 OPT_BOOL('l', NULL, &opts.new_branch_log, N_("create reflog for new branch")),
1802 OPT_BOOL(0, "guess", &opts.dwim_new_local_branch,
1803 N_("second guess 'git checkout <no-such-branch>' (default)")),
1804 OPT_BOOL(0, "overlay", &opts.overlay_mode, N_("use overlay mode (default)")),
1805 OPT_END()
1807 int ret;
1808 struct branch_info new_branch_info = { 0 };
1810 memset(&opts, 0, sizeof(opts));
1811 opts.dwim_new_local_branch = 1;
1812 opts.switch_branch_doing_nothing_is_ok = 1;
1813 opts.only_merge_on_switching_branches = 0;
1814 opts.accept_ref = 1;
1815 opts.accept_pathspec = 1;
1816 opts.implicit_detach = 1;
1817 opts.can_switch_when_in_progress = 1;
1818 opts.orphan_from_empty_tree = 0;
1819 opts.empty_pathspec_ok = 1;
1820 opts.overlay_mode = -1;
1821 opts.checkout_index = -2; /* default on */
1822 opts.checkout_worktree = -2; /* default on */
1824 if (argc == 3 && !strcmp(argv[1], "-b")) {
1826 * User ran 'git checkout -b <branch>' and expects
1827 * the same behavior as 'git switch -c <branch>'.
1829 opts.switch_branch_doing_nothing_is_ok = 0;
1830 opts.only_merge_on_switching_branches = 1;
1833 options = parse_options_dup(checkout_options);
1834 options = add_common_options(&opts, options);
1835 options = add_common_switch_branch_options(&opts, options);
1836 options = add_checkout_path_options(&opts, options);
1838 ret = checkout_main(argc, argv, prefix, &opts,
1839 options, checkout_usage, &new_branch_info);
1840 branch_info_release(&new_branch_info);
1841 clear_pathspec(&opts.pathspec);
1842 FREE_AND_NULL(options);
1843 return ret;
1846 int cmd_switch(int argc, const char **argv, const char *prefix)
1848 struct checkout_opts opts;
1849 struct option *options = NULL;
1850 struct option switch_options[] = {
1851 OPT_STRING('c', "create", &opts.new_branch, N_("branch"),
1852 N_("create and switch to a new branch")),
1853 OPT_STRING('C', "force-create", &opts.new_branch_force, N_("branch"),
1854 N_("create/reset and switch to a branch")),
1855 OPT_BOOL(0, "guess", &opts.dwim_new_local_branch,
1856 N_("second guess 'git switch <no-such-branch>'")),
1857 OPT_BOOL(0, "discard-changes", &opts.discard_changes,
1858 N_("throw away local modifications")),
1859 OPT_END()
1861 int ret;
1862 struct branch_info new_branch_info = { 0 };
1864 memset(&opts, 0, sizeof(opts));
1865 opts.dwim_new_local_branch = 1;
1866 opts.accept_ref = 1;
1867 opts.accept_pathspec = 0;
1868 opts.switch_branch_doing_nothing_is_ok = 0;
1869 opts.only_merge_on_switching_branches = 1;
1870 opts.implicit_detach = 0;
1871 opts.can_switch_when_in_progress = 0;
1872 opts.orphan_from_empty_tree = 1;
1873 opts.overlay_mode = -1;
1875 options = parse_options_dup(switch_options);
1876 options = add_common_options(&opts, options);
1877 options = add_common_switch_branch_options(&opts, options);
1879 cb_option = 'c';
1881 ret = checkout_main(argc, argv, prefix, &opts,
1882 options, switch_branch_usage, &new_branch_info);
1883 branch_info_release(&new_branch_info);
1884 FREE_AND_NULL(options);
1885 return ret;
1888 int cmd_restore(int argc, const char **argv, const char *prefix)
1890 struct checkout_opts opts;
1891 struct option *options;
1892 struct option restore_options[] = {
1893 OPT_STRING('s', "source", &opts.from_treeish, "<tree-ish>",
1894 N_("which tree-ish to checkout from")),
1895 OPT_BOOL('S', "staged", &opts.checkout_index,
1896 N_("restore the index")),
1897 OPT_BOOL('W', "worktree", &opts.checkout_worktree,
1898 N_("restore the working tree (default)")),
1899 OPT_BOOL(0, "ignore-unmerged", &opts.ignore_unmerged,
1900 N_("ignore unmerged entries")),
1901 OPT_BOOL(0, "overlay", &opts.overlay_mode, N_("use overlay mode")),
1902 OPT_END()
1904 int ret;
1905 struct branch_info new_branch_info = { 0 };
1907 memset(&opts, 0, sizeof(opts));
1908 opts.accept_ref = 0;
1909 opts.accept_pathspec = 1;
1910 opts.empty_pathspec_ok = 0;
1911 opts.overlay_mode = 0;
1912 opts.checkout_index = -1; /* default off */
1913 opts.checkout_worktree = -2; /* default on */
1914 opts.ignore_unmerged_opt = "--ignore-unmerged";
1916 options = parse_options_dup(restore_options);
1917 options = add_common_options(&opts, options);
1918 options = add_checkout_path_options(&opts, options);
1920 ret = checkout_main(argc, argv, prefix, &opts,
1921 options, restore_usage, &new_branch_info);
1922 branch_info_release(&new_branch_info);
1923 FREE_AND_NULL(options);
1924 return ret;