test-lib: add a GIT_TEST_PASSING_SANITIZE_LEAK=check mode
[git.git] / builtin / checkout.c
blob1109f1301f41e26a8f59ab0ff5f63befa9f42bb0
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 "hook.h"
13 #include "ll-merge.h"
14 #include "lockfile.h"
15 #include "merge-recursive.h"
16 #include "object-store.h"
17 #include "parse-options.h"
18 #include "refs.h"
19 #include "remote.h"
20 #include "resolve-undo.h"
21 #include "revision.h"
22 #include "run-command.h"
23 #include "submodule.h"
24 #include "submodule-config.h"
25 #include "tree.h"
26 #include "tree-walk.h"
27 #include "unpack-trees.h"
28 #include "wt-status.h"
29 #include "xdiff-interface.h"
30 #include "entry.h"
31 #include "parallel-checkout.h"
33 static const char * const checkout_usage[] = {
34 N_("git checkout [<options>] <branch>"),
35 N_("git checkout [<options>] [<branch>] -- <file>..."),
36 NULL,
39 static const char * const switch_branch_usage[] = {
40 N_("git switch [<options>] [<branch>]"),
41 NULL,
44 static const char * const restore_usage[] = {
45 N_("git restore [<options>] [--source=<branch>] <file>..."),
46 NULL,
49 struct checkout_opts {
50 int patch_mode;
51 int quiet;
52 int merge;
53 int force;
54 int force_detach;
55 int implicit_detach;
56 int writeout_stage;
57 int overwrite_ignore;
58 int ignore_skipworktree;
59 int ignore_other_worktrees;
60 int show_progress;
61 int count_checkout_paths;
62 int overlay_mode;
63 int dwim_new_local_branch;
64 int discard_changes;
65 int accept_ref;
66 int accept_pathspec;
67 int switch_branch_doing_nothing_is_ok;
68 int only_merge_on_switching_branches;
69 int can_switch_when_in_progress;
70 int orphan_from_empty_tree;
71 int empty_pathspec_ok;
72 int checkout_index;
73 int checkout_worktree;
74 const char *ignore_unmerged_opt;
75 int ignore_unmerged;
76 int pathspec_file_nul;
77 const char *pathspec_from_file;
79 const char *new_branch;
80 const char *new_branch_force;
81 const char *new_orphan_branch;
82 int new_branch_log;
83 enum branch_track track;
84 struct diff_options diff_options;
85 char *conflict_style;
87 int branch_exists;
88 const char *prefix;
89 struct pathspec pathspec;
90 const char *from_treeish;
91 struct tree *source_tree;
94 struct branch_info {
95 char *name; /* The short name used */
96 char *path; /* The full name of a real branch */
97 struct commit *commit; /* The named commit */
98 char *refname; /* The full name of the ref being checked out. */
99 struct object_id oid; /* The object ID of the commit being checked out. */
101 * if not null the branch is detached because it's already
102 * checked out in this checkout
104 char *checkout;
107 static void branch_info_release(struct branch_info *info)
109 free(info->name);
110 free(info->path);
111 free(info->refname);
112 free(info->checkout);
115 static int post_checkout_hook(struct commit *old_commit, struct commit *new_commit,
116 int changed)
118 return run_hooks_l("post-checkout",
119 oid_to_hex(old_commit ? &old_commit->object.oid : null_oid()),
120 oid_to_hex(new_commit ? &new_commit->object.oid : null_oid()),
121 changed ? "1" : "0", NULL);
122 /* "new_commit" can be NULL when checking out from the index before
123 a commit exists. */
127 static int update_some(const struct object_id *oid, struct strbuf *base,
128 const char *pathname, unsigned mode, void *context)
130 int len;
131 struct cache_entry *ce;
132 int pos;
134 if (S_ISDIR(mode))
135 return READ_TREE_RECURSIVE;
137 len = base->len + strlen(pathname);
138 ce = make_empty_cache_entry(&the_index, len);
139 oidcpy(&ce->oid, oid);
140 memcpy(ce->name, base->buf, base->len);
141 memcpy(ce->name + base->len, pathname, len - base->len);
142 ce->ce_flags = create_ce_flags(0) | CE_UPDATE;
143 ce->ce_namelen = len;
144 ce->ce_mode = create_ce_mode(mode);
147 * If the entry is the same as the current index, we can leave the old
148 * entry in place. Whether it is UPTODATE or not, checkout_entry will
149 * do the right thing.
151 pos = cache_name_pos(ce->name, ce->ce_namelen);
152 if (pos >= 0) {
153 struct cache_entry *old = active_cache[pos];
154 if (ce->ce_mode == old->ce_mode &&
155 !ce_intent_to_add(old) &&
156 oideq(&ce->oid, &old->oid)) {
157 old->ce_flags |= CE_UPDATE;
158 discard_cache_entry(ce);
159 return 0;
163 add_cache_entry(ce, ADD_CACHE_OK_TO_ADD | ADD_CACHE_OK_TO_REPLACE);
164 return 0;
167 static int read_tree_some(struct tree *tree, const struct pathspec *pathspec)
169 read_tree(the_repository, tree,
170 pathspec, update_some, NULL);
172 /* update the index with the given tree's info
173 * for all args, expanding wildcards, and exit
174 * with any non-zero return code.
176 return 0;
179 static int skip_same_name(const struct cache_entry *ce, int pos)
181 while (++pos < active_nr &&
182 !strcmp(active_cache[pos]->name, ce->name))
183 ; /* skip */
184 return pos;
187 static int check_stage(int stage, const struct cache_entry *ce, int pos,
188 int overlay_mode)
190 while (pos < active_nr &&
191 !strcmp(active_cache[pos]->name, ce->name)) {
192 if (ce_stage(active_cache[pos]) == stage)
193 return 0;
194 pos++;
196 if (!overlay_mode)
197 return 0;
198 if (stage == 2)
199 return error(_("path '%s' does not have our version"), ce->name);
200 else
201 return error(_("path '%s' does not have their version"), ce->name);
204 static int check_stages(unsigned stages, const struct cache_entry *ce, int pos)
206 unsigned seen = 0;
207 const char *name = ce->name;
209 while (pos < active_nr) {
210 ce = active_cache[pos];
211 if (strcmp(name, ce->name))
212 break;
213 seen |= (1 << ce_stage(ce));
214 pos++;
216 if ((stages & seen) != stages)
217 return error(_("path '%s' does not have all necessary versions"),
218 name);
219 return 0;
222 static int checkout_stage(int stage, const struct cache_entry *ce, int pos,
223 const struct checkout *state, int *nr_checkouts,
224 int overlay_mode)
226 while (pos < active_nr &&
227 !strcmp(active_cache[pos]->name, ce->name)) {
228 if (ce_stage(active_cache[pos]) == stage)
229 return checkout_entry(active_cache[pos], state,
230 NULL, nr_checkouts);
231 pos++;
233 if (!overlay_mode) {
234 unlink_entry(ce);
235 return 0;
237 if (stage == 2)
238 return error(_("path '%s' does not have our version"), ce->name);
239 else
240 return error(_("path '%s' does not have their version"), ce->name);
243 static int checkout_merged(int pos, const struct checkout *state,
244 int *nr_checkouts, struct mem_pool *ce_mem_pool)
246 struct cache_entry *ce = active_cache[pos];
247 const char *path = ce->name;
248 mmfile_t ancestor, ours, theirs;
249 enum ll_merge_result merge_status;
250 int status;
251 struct object_id oid;
252 mmbuffer_t result_buf;
253 struct object_id threeway[3];
254 unsigned mode = 0;
255 struct ll_merge_options ll_opts;
256 int renormalize = 0;
258 memset(threeway, 0, sizeof(threeway));
259 while (pos < active_nr) {
260 int stage;
261 stage = ce_stage(ce);
262 if (!stage || strcmp(path, ce->name))
263 break;
264 oidcpy(&threeway[stage - 1], &ce->oid);
265 if (stage == 2)
266 mode = create_ce_mode(ce->ce_mode);
267 pos++;
268 ce = active_cache[pos];
270 if (is_null_oid(&threeway[1]) || is_null_oid(&threeway[2]))
271 return error(_("path '%s' does not have necessary versions"), path);
273 read_mmblob(&ancestor, &threeway[0]);
274 read_mmblob(&ours, &threeway[1]);
275 read_mmblob(&theirs, &threeway[2]);
277 memset(&ll_opts, 0, sizeof(ll_opts));
278 git_config_get_bool("merge.renormalize", &renormalize);
279 ll_opts.renormalize = renormalize;
280 merge_status = ll_merge(&result_buf, path, &ancestor, "base",
281 &ours, "ours", &theirs, "theirs",
282 state->istate, &ll_opts);
283 free(ancestor.ptr);
284 free(ours.ptr);
285 free(theirs.ptr);
286 if (merge_status == LL_MERGE_BINARY_CONFLICT)
287 warning("Cannot merge binary files: %s (%s vs. %s)",
288 path, "ours", "theirs");
289 if (merge_status < 0 || !result_buf.ptr) {
290 free(result_buf.ptr);
291 return error(_("path '%s': cannot merge"), path);
295 * NEEDSWORK:
296 * There is absolutely no reason to write this as a blob object
297 * and create a phony cache entry. This hack is primarily to get
298 * to the write_entry() machinery that massages the contents to
299 * work-tree format and writes out which only allows it for a
300 * cache entry. The code in write_entry() needs to be refactored
301 * to allow us to feed a <buffer, size, mode> instead of a cache
302 * entry. Such a refactoring would help merge_recursive as well
303 * (it also writes the merge result to the object database even
304 * when it may contain conflicts).
306 if (write_object_file(result_buf.ptr, result_buf.size, OBJ_BLOB, &oid))
307 die(_("Unable to add merge result for '%s'"), path);
308 free(result_buf.ptr);
309 ce = make_transient_cache_entry(mode, &oid, path, 2, ce_mem_pool);
310 if (!ce)
311 die(_("make_cache_entry failed for path '%s'"), path);
312 status = checkout_entry(ce, state, NULL, nr_checkouts);
313 return status;
316 static void mark_ce_for_checkout_overlay(struct cache_entry *ce,
317 char *ps_matched,
318 const struct checkout_opts *opts)
320 ce->ce_flags &= ~CE_MATCHED;
321 if (!opts->ignore_skipworktree && ce_skip_worktree(ce))
322 return;
323 if (opts->source_tree && !(ce->ce_flags & CE_UPDATE))
325 * "git checkout tree-ish -- path", but this entry
326 * is in the original index but is not in tree-ish
327 * or does not match the pathspec; it will not be
328 * checked out to the working tree. We will not do
329 * anything to this entry at all.
331 return;
333 * Either this entry came from the tree-ish we are
334 * checking the paths out of, or we are checking out
335 * of the index.
337 * If it comes from the tree-ish, we already know it
338 * matches the pathspec and could just stamp
339 * CE_MATCHED to it from update_some(). But we still
340 * need ps_matched and read_tree (and
341 * eventually tree_entry_interesting) cannot fill
342 * ps_matched yet. Once it can, we can avoid calling
343 * match_pathspec() for _all_ entries when
344 * opts->source_tree != NULL.
346 if (ce_path_match(&the_index, ce, &opts->pathspec, ps_matched))
347 ce->ce_flags |= CE_MATCHED;
350 static void mark_ce_for_checkout_no_overlay(struct cache_entry *ce,
351 char *ps_matched,
352 const struct checkout_opts *opts)
354 ce->ce_flags &= ~CE_MATCHED;
355 if (!opts->ignore_skipworktree && ce_skip_worktree(ce))
356 return;
357 if (ce_path_match(&the_index, ce, &opts->pathspec, ps_matched)) {
358 ce->ce_flags |= CE_MATCHED;
359 if (opts->source_tree && !(ce->ce_flags & CE_UPDATE))
361 * In overlay mode, but the path is not in
362 * tree-ish, which means we should remove it
363 * from the index and the working tree.
365 ce->ce_flags |= CE_REMOVE | CE_WT_REMOVE;
369 static int checkout_worktree(const struct checkout_opts *opts,
370 const struct branch_info *info)
372 struct checkout state = CHECKOUT_INIT;
373 int nr_checkouts = 0, nr_unmerged = 0;
374 int errs = 0;
375 int pos;
376 int pc_workers, pc_threshold;
377 struct mem_pool ce_mem_pool;
379 state.force = 1;
380 state.refresh_cache = 1;
381 state.istate = &the_index;
383 mem_pool_init(&ce_mem_pool, 0);
384 get_parallel_checkout_configs(&pc_workers, &pc_threshold);
385 init_checkout_metadata(&state.meta, info->refname,
386 info->commit ? &info->commit->object.oid : &info->oid,
387 NULL);
389 enable_delayed_checkout(&state);
391 if (pc_workers > 1)
392 init_parallel_checkout();
394 for (pos = 0; pos < active_nr; pos++) {
395 struct cache_entry *ce = active_cache[pos];
396 if (ce->ce_flags & CE_MATCHED) {
397 if (!ce_stage(ce)) {
398 errs |= checkout_entry(ce, &state,
399 NULL, &nr_checkouts);
400 continue;
402 if (opts->writeout_stage)
403 errs |= checkout_stage(opts->writeout_stage,
404 ce, pos,
405 &state,
406 &nr_checkouts, opts->overlay_mode);
407 else if (opts->merge)
408 errs |= checkout_merged(pos, &state,
409 &nr_unmerged,
410 &ce_mem_pool);
411 pos = skip_same_name(ce, pos) - 1;
414 if (pc_workers > 1)
415 errs |= run_parallel_checkout(&state, pc_workers, pc_threshold,
416 NULL, NULL);
417 mem_pool_discard(&ce_mem_pool, should_validate_cache_entries());
418 remove_marked_cache_entries(&the_index, 1);
419 remove_scheduled_dirs();
420 errs |= finish_delayed_checkout(&state, &nr_checkouts, opts->show_progress);
422 if (opts->count_checkout_paths) {
423 if (nr_unmerged)
424 fprintf_ln(stderr, Q_("Recreated %d merge conflict",
425 "Recreated %d merge conflicts",
426 nr_unmerged),
427 nr_unmerged);
428 if (opts->source_tree)
429 fprintf_ln(stderr, Q_("Updated %d path from %s",
430 "Updated %d paths from %s",
431 nr_checkouts),
432 nr_checkouts,
433 find_unique_abbrev(&opts->source_tree->object.oid,
434 DEFAULT_ABBREV));
435 else if (!nr_unmerged || nr_checkouts)
436 fprintf_ln(stderr, Q_("Updated %d path from the index",
437 "Updated %d paths from the index",
438 nr_checkouts),
439 nr_checkouts);
442 return errs;
445 static int checkout_paths(const struct checkout_opts *opts,
446 const struct branch_info *new_branch_info)
448 int pos;
449 static char *ps_matched;
450 struct object_id rev;
451 struct commit *head;
452 int errs = 0;
453 struct lock_file lock_file = LOCK_INIT;
454 int checkout_index;
456 trace2_cmd_mode(opts->patch_mode ? "patch" : "path");
458 if (opts->track != BRANCH_TRACK_UNSPECIFIED)
459 die(_("'%s' cannot be used with updating paths"), "--track");
461 if (opts->new_branch_log)
462 die(_("'%s' cannot be used with updating paths"), "-l");
464 if (opts->ignore_unmerged && opts->patch_mode)
465 die(_("'%s' cannot be used with updating paths"),
466 opts->ignore_unmerged_opt);
468 if (opts->force_detach)
469 die(_("'%s' cannot be used with updating paths"), "--detach");
471 if (opts->merge && opts->patch_mode)
472 die(_("options '%s' and '%s' cannot be used together"), "--merge", "--patch");
474 if (opts->ignore_unmerged && opts->merge)
475 die(_("options '%s' and '%s' cannot be used together"),
476 opts->ignore_unmerged_opt, "-m");
478 if (opts->new_branch)
479 die(_("Cannot update paths and switch to branch '%s' at the same time."),
480 opts->new_branch);
482 if (!opts->checkout_worktree && !opts->checkout_index)
483 die(_("neither '%s' or '%s' is specified"),
484 "--staged", "--worktree");
486 if (!opts->checkout_worktree && !opts->from_treeish)
487 die(_("'%s' must be used when '%s' is not specified"),
488 "--worktree", "--source");
490 if (opts->checkout_index && !opts->checkout_worktree &&
491 opts->writeout_stage)
492 die(_("'%s' or '%s' cannot be used with %s"),
493 "--ours", "--theirs", "--staged");
495 if (opts->checkout_index && !opts->checkout_worktree &&
496 opts->merge)
497 die(_("'%s' or '%s' cannot be used with %s"),
498 "--merge", "--conflict", "--staged");
500 if (opts->patch_mode) {
501 const char *patch_mode;
502 const char *rev = new_branch_info->name;
503 char rev_oid[GIT_MAX_HEXSZ + 1];
506 * Since rev can be in the form of `<a>...<b>` (which is not
507 * recognized by diff-index), we will always replace the name
508 * with the hex of the commit (whether it's in `...` form or
509 * not) for the run_add_interactive() machinery to work
510 * properly. However, there is special logic for the HEAD case
511 * so we mustn't replace that. Also, when we were given a
512 * tree-object, new_branch_info->commit would be NULL, but we
513 * do not have to do any replacement, either.
515 if (rev && new_branch_info->commit && strcmp(rev, "HEAD"))
516 rev = oid_to_hex_r(rev_oid, &new_branch_info->commit->object.oid);
518 if (opts->checkout_index && opts->checkout_worktree)
519 patch_mode = "--patch=checkout";
520 else if (opts->checkout_index && !opts->checkout_worktree)
521 patch_mode = "--patch=reset";
522 else if (!opts->checkout_index && opts->checkout_worktree)
523 patch_mode = "--patch=worktree";
524 else
525 BUG("either flag must have been set, worktree=%d, index=%d",
526 opts->checkout_worktree, opts->checkout_index);
527 return run_add_interactive(rev, patch_mode, &opts->pathspec);
530 repo_hold_locked_index(the_repository, &lock_file, LOCK_DIE_ON_ERROR);
531 if (read_cache_preload(&opts->pathspec) < 0)
532 return error(_("index file corrupt"));
534 if (opts->source_tree)
535 read_tree_some(opts->source_tree, &opts->pathspec);
537 ps_matched = xcalloc(opts->pathspec.nr, 1);
540 * Make sure all pathspecs participated in locating the paths
541 * to be checked out.
543 for (pos = 0; pos < active_nr; pos++)
544 if (opts->overlay_mode)
545 mark_ce_for_checkout_overlay(active_cache[pos],
546 ps_matched,
547 opts);
548 else
549 mark_ce_for_checkout_no_overlay(active_cache[pos],
550 ps_matched,
551 opts);
553 if (report_path_error(ps_matched, &opts->pathspec)) {
554 free(ps_matched);
555 return 1;
557 free(ps_matched);
559 /* "checkout -m path" to recreate conflicted state */
560 if (opts->merge)
561 unmerge_marked_index(&the_index);
563 /* Any unmerged paths? */
564 for (pos = 0; pos < active_nr; pos++) {
565 const struct cache_entry *ce = active_cache[pos];
566 if (ce->ce_flags & CE_MATCHED) {
567 if (!ce_stage(ce))
568 continue;
569 if (opts->ignore_unmerged) {
570 if (!opts->quiet)
571 warning(_("path '%s' is unmerged"), ce->name);
572 } else if (opts->writeout_stage) {
573 errs |= check_stage(opts->writeout_stage, ce, pos, opts->overlay_mode);
574 } else if (opts->merge) {
575 errs |= check_stages((1<<2) | (1<<3), ce, pos);
576 } else {
577 errs = 1;
578 error(_("path '%s' is unmerged"), ce->name);
580 pos = skip_same_name(ce, pos) - 1;
583 if (errs)
584 return 1;
586 /* Now we are committed to check them out */
587 if (opts->checkout_worktree)
588 errs |= checkout_worktree(opts, new_branch_info);
589 else
590 remove_marked_cache_entries(&the_index, 1);
593 * Allow updating the index when checking out from the index.
594 * This is to save new stat info.
596 if (opts->checkout_worktree && !opts->checkout_index && !opts->source_tree)
597 checkout_index = 1;
598 else
599 checkout_index = opts->checkout_index;
601 if (checkout_index) {
602 if (write_locked_index(&the_index, &lock_file, COMMIT_LOCK))
603 die(_("unable to write new index file"));
604 } else {
606 * NEEDSWORK: if --worktree is not specified, we
607 * should save stat info of checked out files in the
608 * index to avoid the next (potentially costly)
609 * refresh. But it's a bit tricker to do...
611 rollback_lock_file(&lock_file);
614 read_ref_full("HEAD", 0, &rev, NULL);
615 head = lookup_commit_reference_gently(the_repository, &rev, 1);
617 errs |= post_checkout_hook(head, head, 0);
618 return errs;
621 static void show_local_changes(struct object *head,
622 const struct diff_options *opts)
624 struct rev_info rev;
625 /* I think we want full paths, even if we're in a subdirectory. */
626 repo_init_revisions(the_repository, &rev, NULL);
627 rev.diffopt.flags = opts->flags;
628 rev.diffopt.output_format |= DIFF_FORMAT_NAME_STATUS;
629 diff_setup_done(&rev.diffopt);
630 add_pending_object(&rev, head, NULL);
631 run_diff_index(&rev, 0);
632 release_revisions(&rev);
635 static void describe_detached_head(const char *msg, struct commit *commit)
637 struct strbuf sb = STRBUF_INIT;
639 if (!parse_commit(commit))
640 pp_commit_easy(CMIT_FMT_ONELINE, commit, &sb);
641 if (print_sha1_ellipsis()) {
642 fprintf(stderr, "%s %s... %s\n", msg,
643 find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV), sb.buf);
644 } else {
645 fprintf(stderr, "%s %s %s\n", msg,
646 find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV), sb.buf);
648 strbuf_release(&sb);
651 static int reset_tree(struct tree *tree, const struct checkout_opts *o,
652 int worktree, int *writeout_error,
653 struct branch_info *info)
655 struct unpack_trees_options opts;
656 struct tree_desc tree_desc;
658 memset(&opts, 0, sizeof(opts));
659 opts.head_idx = -1;
660 opts.update = worktree;
661 opts.skip_unmerged = !worktree;
662 opts.reset = o->force ? UNPACK_RESET_OVERWRITE_UNTRACKED :
663 UNPACK_RESET_PROTECT_UNTRACKED;
664 opts.preserve_ignored = (!o->force && !o->overwrite_ignore);
665 opts.merge = 1;
666 opts.fn = oneway_merge;
667 opts.verbose_update = o->show_progress;
668 opts.src_index = &the_index;
669 opts.dst_index = &the_index;
670 init_checkout_metadata(&opts.meta, info->refname,
671 info->commit ? &info->commit->object.oid : null_oid(),
672 NULL);
673 parse_tree(tree);
674 init_tree_desc(&tree_desc, tree->buffer, tree->size);
675 switch (unpack_trees(1, &tree_desc, &opts)) {
676 case -2:
677 *writeout_error = 1;
679 * We return 0 nevertheless, as the index is all right
680 * and more importantly we have made best efforts to
681 * update paths in the work tree, and we cannot revert
682 * them.
684 /* fallthrough */
685 case 0:
686 return 0;
687 default:
688 return 128;
692 static void setup_branch_path(struct branch_info *branch)
694 struct strbuf buf = STRBUF_INIT;
697 * If this is a ref, resolve it; otherwise, look up the OID for our
698 * expression. Failure here is okay.
700 if (!dwim_ref(branch->name, strlen(branch->name), &branch->oid, &branch->refname, 0))
701 repo_get_oid_committish(the_repository, branch->name, &branch->oid);
703 strbuf_branchname(&buf, branch->name, INTERPRET_BRANCH_LOCAL);
704 if (strcmp(buf.buf, branch->name)) {
705 free(branch->name);
706 branch->name = xstrdup(buf.buf);
708 strbuf_splice(&buf, 0, 0, "refs/heads/", 11);
709 free(branch->path);
710 branch->path = strbuf_detach(&buf, NULL);
713 static void init_topts(struct unpack_trees_options *topts, int merge,
714 int show_progress, int overwrite_ignore,
715 struct commit *old_commit)
717 memset(topts, 0, sizeof(*topts));
718 topts->head_idx = -1;
719 topts->src_index = &the_index;
720 topts->dst_index = &the_index;
722 setup_unpack_trees_porcelain(topts, "checkout");
724 topts->initial_checkout = is_cache_unborn();
725 topts->update = 1;
726 topts->merge = 1;
727 topts->quiet = merge && old_commit;
728 topts->verbose_update = show_progress;
729 topts->fn = twoway_merge;
730 topts->preserve_ignored = !overwrite_ignore;
733 static int merge_working_tree(const struct checkout_opts *opts,
734 struct branch_info *old_branch_info,
735 struct branch_info *new_branch_info,
736 int *writeout_error)
738 int ret;
739 struct lock_file lock_file = LOCK_INIT;
740 struct tree *new_tree;
742 hold_locked_index(&lock_file, LOCK_DIE_ON_ERROR);
743 if (read_cache_preload(NULL) < 0)
744 return error(_("index file corrupt"));
746 resolve_undo_clear();
747 if (opts->new_orphan_branch && opts->orphan_from_empty_tree) {
748 if (new_branch_info->commit)
749 BUG("'switch --orphan' should never accept a commit as starting point");
750 new_tree = parse_tree_indirect(the_hash_algo->empty_tree);
751 } else
752 new_tree = get_commit_tree(new_branch_info->commit);
753 if (opts->discard_changes) {
754 ret = reset_tree(new_tree, opts, 1, writeout_error, new_branch_info);
755 if (ret)
756 return ret;
757 } else {
758 struct tree_desc trees[2];
759 struct tree *tree;
760 struct unpack_trees_options topts;
761 const struct object_id *old_commit_oid;
763 refresh_cache(REFRESH_QUIET);
765 if (unmerged_cache()) {
766 error(_("you need to resolve your current index first"));
767 return 1;
770 /* 2-way merge to the new branch */
771 init_topts(&topts, opts->merge, opts->show_progress,
772 opts->overwrite_ignore, old_branch_info->commit);
773 init_checkout_metadata(&topts.meta, new_branch_info->refname,
774 new_branch_info->commit ?
775 &new_branch_info->commit->object.oid :
776 &new_branch_info->oid, NULL);
778 old_commit_oid = old_branch_info->commit ?
779 &old_branch_info->commit->object.oid :
780 the_hash_algo->empty_tree;
781 tree = parse_tree_indirect(old_commit_oid);
782 if (!tree)
783 die(_("unable to parse commit %s"),
784 oid_to_hex(old_commit_oid));
786 init_tree_desc(&trees[0], tree->buffer, tree->size);
787 parse_tree(new_tree);
788 tree = new_tree;
789 init_tree_desc(&trees[1], tree->buffer, tree->size);
791 ret = unpack_trees(2, trees, &topts);
792 clear_unpack_trees_porcelain(&topts);
793 if (ret == -1) {
795 * Unpack couldn't do a trivial merge; either
796 * give up or do a real merge, depending on
797 * whether the merge flag was used.
799 struct tree *work;
800 struct tree *old_tree;
801 struct merge_options o;
802 struct strbuf sb = STRBUF_INIT;
803 struct strbuf old_commit_shortname = STRBUF_INIT;
805 if (!opts->merge)
806 return 1;
809 * Without old_branch_info->commit, the below is the same as
810 * the two-tree unpack we already tried and failed.
812 if (!old_branch_info->commit)
813 return 1;
814 old_tree = get_commit_tree(old_branch_info->commit);
816 if (repo_index_has_changes(the_repository, old_tree, &sb))
817 die(_("cannot continue with staged changes in "
818 "the following files:\n%s"), sb.buf);
819 strbuf_release(&sb);
821 /* Do more real merge */
824 * We update the index fully, then write the
825 * tree from the index, then merge the new
826 * branch with the current tree, with the old
827 * branch as the base. Then we reset the index
828 * (but not the working tree) to the new
829 * branch, leaving the working tree as the
830 * merged version, but skipping unmerged
831 * entries in the index.
834 add_files_to_cache(NULL, NULL, 0);
835 init_merge_options(&o, the_repository);
836 o.verbosity = 0;
837 work = write_in_core_index_as_tree(the_repository);
839 ret = reset_tree(new_tree,
840 opts, 1,
841 writeout_error, new_branch_info);
842 if (ret)
843 return ret;
844 o.ancestor = old_branch_info->name;
845 if (!old_branch_info->name) {
846 strbuf_add_unique_abbrev(&old_commit_shortname,
847 &old_branch_info->commit->object.oid,
848 DEFAULT_ABBREV);
849 o.ancestor = old_commit_shortname.buf;
851 o.branch1 = new_branch_info->name;
852 o.branch2 = "local";
853 ret = merge_trees(&o,
854 new_tree,
855 work,
856 old_tree);
857 if (ret < 0)
858 exit(128);
859 ret = reset_tree(new_tree,
860 opts, 0,
861 writeout_error, new_branch_info);
862 strbuf_release(&o.obuf);
863 strbuf_release(&old_commit_shortname);
864 if (ret)
865 return ret;
869 if (!cache_tree_fully_valid(active_cache_tree))
870 cache_tree_update(&the_index, WRITE_TREE_SILENT | WRITE_TREE_REPAIR);
872 if (write_locked_index(&the_index, &lock_file, COMMIT_LOCK))
873 die(_("unable to write new index file"));
875 if (!opts->discard_changes && !opts->quiet && new_branch_info->commit)
876 show_local_changes(&new_branch_info->commit->object, &opts->diff_options);
878 return 0;
881 static void report_tracking(struct branch_info *new_branch_info)
883 struct strbuf sb = STRBUF_INIT;
884 struct branch *branch = branch_get(new_branch_info->name);
886 if (!format_tracking_info(branch, &sb, AHEAD_BEHIND_FULL))
887 return;
888 fputs(sb.buf, stdout);
889 strbuf_release(&sb);
892 static void update_refs_for_switch(const struct checkout_opts *opts,
893 struct branch_info *old_branch_info,
894 struct branch_info *new_branch_info)
896 struct strbuf msg = STRBUF_INIT;
897 const char *old_desc, *reflog_msg;
898 if (opts->new_branch) {
899 if (opts->new_orphan_branch) {
900 char *refname;
902 refname = mkpathdup("refs/heads/%s", opts->new_orphan_branch);
903 if (opts->new_branch_log &&
904 !should_autocreate_reflog(refname)) {
905 int ret;
906 struct strbuf err = STRBUF_INIT;
908 ret = safe_create_reflog(refname, &err);
909 if (ret) {
910 fprintf(stderr, _("Can not do reflog for '%s': %s\n"),
911 opts->new_orphan_branch, err.buf);
912 strbuf_release(&err);
913 free(refname);
914 return;
916 strbuf_release(&err);
918 free(refname);
920 else
921 create_branch(the_repository,
922 opts->new_branch, new_branch_info->name,
923 opts->new_branch_force ? 1 : 0,
924 opts->new_branch_force ? 1 : 0,
925 opts->new_branch_log,
926 opts->quiet,
927 opts->track,
929 free(new_branch_info->name);
930 free(new_branch_info->refname);
931 new_branch_info->name = xstrdup(opts->new_branch);
932 setup_branch_path(new_branch_info);
935 old_desc = old_branch_info->name;
936 if (!old_desc && old_branch_info->commit)
937 old_desc = oid_to_hex(&old_branch_info->commit->object.oid);
939 reflog_msg = getenv("GIT_REFLOG_ACTION");
940 if (!reflog_msg)
941 strbuf_addf(&msg, "checkout: moving from %s to %s",
942 old_desc ? old_desc : "(invalid)", new_branch_info->name);
943 else
944 strbuf_insertstr(&msg, 0, reflog_msg);
946 if (!strcmp(new_branch_info->name, "HEAD") && !new_branch_info->path && !opts->force_detach) {
947 /* Nothing to do. */
948 } else if (opts->force_detach || !new_branch_info->path) { /* No longer on any branch. */
949 update_ref(msg.buf, "HEAD", &new_branch_info->commit->object.oid, NULL,
950 REF_NO_DEREF, UPDATE_REFS_DIE_ON_ERR);
951 if (!opts->quiet) {
952 if (old_branch_info->path &&
953 advice_enabled(ADVICE_DETACHED_HEAD) && !opts->force_detach)
954 detach_advice(new_branch_info->name);
955 describe_detached_head(_("HEAD is now at"), new_branch_info->commit);
957 } else if (new_branch_info->path) { /* Switch branches. */
958 if (create_symref("HEAD", new_branch_info->path, msg.buf) < 0)
959 die(_("unable to update HEAD"));
960 if (!opts->quiet) {
961 if (old_branch_info->path && !strcmp(new_branch_info->path, old_branch_info->path)) {
962 if (opts->new_branch_force)
963 fprintf(stderr, _("Reset branch '%s'\n"),
964 new_branch_info->name);
965 else
966 fprintf(stderr, _("Already on '%s'\n"),
967 new_branch_info->name);
968 } else if (opts->new_branch) {
969 if (opts->branch_exists)
970 fprintf(stderr, _("Switched to and reset branch '%s'\n"), new_branch_info->name);
971 else
972 fprintf(stderr, _("Switched to a new branch '%s'\n"), new_branch_info->name);
973 } else {
974 fprintf(stderr, _("Switched to branch '%s'\n"),
975 new_branch_info->name);
978 if (old_branch_info->path && old_branch_info->name) {
979 if (!ref_exists(old_branch_info->path) && reflog_exists(old_branch_info->path))
980 delete_reflog(old_branch_info->path);
983 remove_branch_state(the_repository, !opts->quiet);
984 strbuf_release(&msg);
985 if (!opts->quiet &&
986 (new_branch_info->path || (!opts->force_detach && !strcmp(new_branch_info->name, "HEAD"))))
987 report_tracking(new_branch_info);
990 static int add_pending_uninteresting_ref(const char *refname,
991 const struct object_id *oid,
992 int flags, void *cb_data)
994 add_pending_oid(cb_data, refname, oid, UNINTERESTING);
995 return 0;
998 static void describe_one_orphan(struct strbuf *sb, struct commit *commit)
1000 strbuf_addstr(sb, " ");
1001 strbuf_add_unique_abbrev(sb, &commit->object.oid, DEFAULT_ABBREV);
1002 strbuf_addch(sb, ' ');
1003 if (!parse_commit(commit))
1004 pp_commit_easy(CMIT_FMT_ONELINE, commit, sb);
1005 strbuf_addch(sb, '\n');
1008 #define ORPHAN_CUTOFF 4
1009 static void suggest_reattach(struct commit *commit, struct rev_info *revs)
1011 struct commit *c, *last = NULL;
1012 struct strbuf sb = STRBUF_INIT;
1013 int lost = 0;
1014 while ((c = get_revision(revs)) != NULL) {
1015 if (lost < ORPHAN_CUTOFF)
1016 describe_one_orphan(&sb, c);
1017 last = c;
1018 lost++;
1020 if (ORPHAN_CUTOFF < lost) {
1021 int more = lost - ORPHAN_CUTOFF;
1022 if (more == 1)
1023 describe_one_orphan(&sb, last);
1024 else
1025 strbuf_addf(&sb, _(" ... and %d more.\n"), more);
1028 fprintf(stderr,
1030 /* The singular version */
1031 "Warning: you are leaving %d commit behind, "
1032 "not connected to\n"
1033 "any of your branches:\n\n"
1034 "%s\n",
1035 /* The plural version */
1036 "Warning: you are leaving %d commits behind, "
1037 "not connected to\n"
1038 "any of your branches:\n\n"
1039 "%s\n",
1040 /* Give ngettext() the count */
1041 lost),
1042 lost,
1043 sb.buf);
1044 strbuf_release(&sb);
1046 if (advice_enabled(ADVICE_DETACHED_HEAD))
1047 fprintf(stderr,
1049 /* The singular version */
1050 "If you want to keep it by creating a new branch, "
1051 "this may be a good time\nto do so with:\n\n"
1052 " git branch <new-branch-name> %s\n\n",
1053 /* The plural version */
1054 "If you want to keep them by creating a new branch, "
1055 "this may be a good time\nto do so with:\n\n"
1056 " git branch <new-branch-name> %s\n\n",
1057 /* Give ngettext() the count */
1058 lost),
1059 find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV));
1063 * We are about to leave commit that was at the tip of a detached
1064 * HEAD. If it is not reachable from any ref, this is the last chance
1065 * for the user to do so without resorting to reflog.
1067 static void orphaned_commit_warning(struct commit *old_commit, struct commit *new_commit)
1069 struct rev_info revs;
1070 struct object *object = &old_commit->object;
1072 repo_init_revisions(the_repository, &revs, NULL);
1073 setup_revisions(0, NULL, &revs, NULL);
1075 object->flags &= ~UNINTERESTING;
1076 add_pending_object(&revs, object, oid_to_hex(&object->oid));
1078 for_each_ref(add_pending_uninteresting_ref, &revs);
1079 if (new_commit)
1080 add_pending_oid(&revs, "HEAD",
1081 &new_commit->object.oid,
1082 UNINTERESTING);
1084 if (prepare_revision_walk(&revs))
1085 die(_("internal error in revision walk"));
1086 if (!(old_commit->object.flags & UNINTERESTING))
1087 suggest_reattach(old_commit, &revs);
1088 else
1089 describe_detached_head(_("Previous HEAD position was"), old_commit);
1091 /* Clean up objects used, as they will be reused. */
1092 repo_clear_commit_marks(the_repository, ALL_REV_FLAGS);
1093 release_revisions(&revs);
1096 static int switch_branches(const struct checkout_opts *opts,
1097 struct branch_info *new_branch_info)
1099 int ret = 0;
1100 struct branch_info old_branch_info = { 0 };
1101 struct object_id rev;
1102 int flag, writeout_error = 0;
1103 int do_merge = 1;
1105 trace2_cmd_mode("branch");
1107 memset(&old_branch_info, 0, sizeof(old_branch_info));
1108 old_branch_info.path = resolve_refdup("HEAD", 0, &rev, &flag);
1109 if (old_branch_info.path)
1110 old_branch_info.commit = lookup_commit_reference_gently(the_repository, &rev, 1);
1111 if (!(flag & REF_ISSYMREF))
1112 FREE_AND_NULL(old_branch_info.path);
1114 if (old_branch_info.path) {
1115 const char *const prefix = "refs/heads/";
1116 const char *p;
1117 if (skip_prefix(old_branch_info.path, prefix, &p))
1118 old_branch_info.name = xstrdup(p);
1121 if (opts->new_orphan_branch && opts->orphan_from_empty_tree) {
1122 if (new_branch_info->name)
1123 BUG("'switch --orphan' should never accept a commit as starting point");
1124 new_branch_info->commit = NULL;
1125 new_branch_info->name = xstrdup("(empty)");
1126 do_merge = 1;
1129 if (!new_branch_info->name) {
1130 new_branch_info->name = xstrdup("HEAD");
1131 new_branch_info->commit = old_branch_info.commit;
1132 if (!new_branch_info->commit)
1133 die(_("You are on a branch yet to be born"));
1134 parse_commit_or_die(new_branch_info->commit);
1136 if (opts->only_merge_on_switching_branches)
1137 do_merge = 0;
1140 if (do_merge) {
1141 ret = merge_working_tree(opts, &old_branch_info, new_branch_info, &writeout_error);
1142 if (ret) {
1143 branch_info_release(&old_branch_info);
1144 return ret;
1148 if (!opts->quiet && !old_branch_info.path && old_branch_info.commit && new_branch_info->commit != old_branch_info.commit)
1149 orphaned_commit_warning(old_branch_info.commit, new_branch_info->commit);
1151 update_refs_for_switch(opts, &old_branch_info, new_branch_info);
1153 ret = post_checkout_hook(old_branch_info.commit, new_branch_info->commit, 1);
1154 branch_info_release(&old_branch_info);
1156 return ret || writeout_error;
1159 static int git_checkout_config(const char *var, const char *value, void *cb)
1161 struct checkout_opts *opts = cb;
1163 if (!strcmp(var, "diff.ignoresubmodules")) {
1164 handle_ignore_submodules_arg(&opts->diff_options, value);
1165 return 0;
1167 if (!strcmp(var, "checkout.guess")) {
1168 opts->dwim_new_local_branch = git_config_bool(var, value);
1169 return 0;
1172 if (starts_with(var, "submodule."))
1173 return git_default_submodule_config(var, value, NULL);
1175 return git_xmerge_config(var, value, NULL);
1178 static void setup_new_branch_info_and_source_tree(
1179 struct branch_info *new_branch_info,
1180 struct checkout_opts *opts,
1181 struct object_id *rev,
1182 const char *arg)
1184 struct tree **source_tree = &opts->source_tree;
1185 struct object_id branch_rev;
1187 new_branch_info->name = xstrdup(arg);
1188 setup_branch_path(new_branch_info);
1190 if (!check_refname_format(new_branch_info->path, 0) &&
1191 !read_ref(new_branch_info->path, &branch_rev))
1192 oidcpy(rev, &branch_rev);
1193 else
1194 /* not an existing branch */
1195 FREE_AND_NULL(new_branch_info->path);
1197 new_branch_info->commit = lookup_commit_reference_gently(the_repository, rev, 1);
1198 if (!new_branch_info->commit) {
1199 /* not a commit */
1200 *source_tree = parse_tree_indirect(rev);
1201 } else {
1202 parse_commit_or_die(new_branch_info->commit);
1203 *source_tree = get_commit_tree(new_branch_info->commit);
1207 static const char *parse_remote_branch(const char *arg,
1208 struct object_id *rev,
1209 int could_be_checkout_paths)
1211 int num_matches = 0;
1212 const char *remote = unique_tracking_name(arg, rev, &num_matches);
1214 if (remote && could_be_checkout_paths) {
1215 die(_("'%s' could be both a local file and a tracking branch.\n"
1216 "Please use -- (and optionally --no-guess) to disambiguate"),
1217 arg);
1220 if (!remote && num_matches > 1) {
1221 if (advice_enabled(ADVICE_CHECKOUT_AMBIGUOUS_REMOTE_BRANCH_NAME)) {
1222 advise(_("If you meant to check out a remote tracking branch on, e.g. 'origin',\n"
1223 "you can do so by fully qualifying the name with the --track option:\n"
1224 "\n"
1225 " git checkout --track origin/<name>\n"
1226 "\n"
1227 "If you'd like to always have checkouts of an ambiguous <name> prefer\n"
1228 "one remote, e.g. the 'origin' remote, consider setting\n"
1229 "checkout.defaultRemote=origin in your config."));
1232 die(_("'%s' matched multiple (%d) remote tracking branches"),
1233 arg, num_matches);
1236 return remote;
1239 static int parse_branchname_arg(int argc, const char **argv,
1240 int dwim_new_local_branch_ok,
1241 struct branch_info *new_branch_info,
1242 struct checkout_opts *opts,
1243 struct object_id *rev)
1245 const char **new_branch = &opts->new_branch;
1246 int argcount = 0;
1247 const char *arg;
1248 int dash_dash_pos;
1249 int has_dash_dash = 0;
1250 int i;
1253 * case 1: git checkout <ref> -- [<paths>]
1255 * <ref> must be a valid tree, everything after the '--' must be
1256 * a path.
1258 * case 2: git checkout -- [<paths>]
1260 * everything after the '--' must be paths.
1262 * case 3: git checkout <something> [--]
1264 * (a) If <something> is a commit, that is to
1265 * switch to the branch or detach HEAD at it. As a special case,
1266 * if <something> is A...B (missing A or B means HEAD but you can
1267 * omit at most one side), and if there is a unique merge base
1268 * between A and B, A...B names that merge base.
1270 * (b) If <something> is _not_ a commit, either "--" is present
1271 * or <something> is not a path, no -t or -b was given, and
1272 * and there is a tracking branch whose name is <something>
1273 * in one and only one remote (or if the branch exists on the
1274 * remote named in checkout.defaultRemote), then this is a
1275 * short-hand to fork local <something> from that
1276 * remote-tracking branch.
1278 * (c) Otherwise, if "--" is present, treat it like case (1).
1280 * (d) Otherwise :
1281 * - if it's a reference, treat it like case (1)
1282 * - else if it's a path, treat it like case (2)
1283 * - else: fail.
1285 * case 4: git checkout <something> <paths>
1287 * The first argument must not be ambiguous.
1288 * - If it's *only* a reference, treat it like case (1).
1289 * - If it's only a path, treat it like case (2).
1290 * - else: fail.
1293 if (!argc)
1294 return 0;
1296 if (!opts->accept_pathspec) {
1297 if (argc > 1)
1298 die(_("only one reference expected"));
1299 has_dash_dash = 1; /* helps disambiguate */
1302 arg = argv[0];
1303 dash_dash_pos = -1;
1304 for (i = 0; i < argc; i++) {
1305 if (opts->accept_pathspec && !strcmp(argv[i], "--")) {
1306 dash_dash_pos = i;
1307 break;
1310 if (dash_dash_pos == 0)
1311 return 1; /* case (2) */
1312 else if (dash_dash_pos == 1)
1313 has_dash_dash = 1; /* case (3) or (1) */
1314 else if (dash_dash_pos >= 2)
1315 die(_("only one reference expected, %d given."), dash_dash_pos);
1316 opts->count_checkout_paths = !opts->quiet && !has_dash_dash;
1318 if (!strcmp(arg, "-"))
1319 arg = "@{-1}";
1321 if (get_oid_mb(arg, rev)) {
1323 * Either case (3) or (4), with <something> not being
1324 * a commit, or an attempt to use case (1) with an
1325 * invalid ref.
1327 * It's likely an error, but we need to find out if
1328 * we should auto-create the branch, case (3).(b).
1330 int recover_with_dwim = dwim_new_local_branch_ok;
1332 int could_be_checkout_paths = !has_dash_dash &&
1333 check_filename(opts->prefix, arg);
1335 if (!has_dash_dash && !no_wildcard(arg))
1336 recover_with_dwim = 0;
1339 * Accept "git checkout foo", "git checkout foo --"
1340 * and "git switch foo" as candidates for dwim.
1342 if (!(argc == 1 && !has_dash_dash) &&
1343 !(argc == 2 && has_dash_dash) &&
1344 opts->accept_pathspec)
1345 recover_with_dwim = 0;
1347 if (recover_with_dwim) {
1348 const char *remote = parse_remote_branch(arg, rev,
1349 could_be_checkout_paths);
1350 if (remote) {
1351 *new_branch = arg;
1352 arg = remote;
1353 /* DWIMmed to create local branch, case (3).(b) */
1354 } else {
1355 recover_with_dwim = 0;
1359 if (!recover_with_dwim) {
1360 if (has_dash_dash)
1361 die(_("invalid reference: %s"), arg);
1362 return argcount;
1366 /* we can't end up being in (2) anymore, eat the argument */
1367 argcount++;
1368 argv++;
1369 argc--;
1371 setup_new_branch_info_and_source_tree(new_branch_info, opts, rev, arg);
1373 if (!opts->source_tree) /* case (1): want a tree */
1374 die(_("reference is not a tree: %s"), arg);
1376 if (!has_dash_dash) { /* case (3).(d) -> (1) */
1378 * Do not complain the most common case
1379 * git checkout branch
1380 * even if there happen to be a file called 'branch';
1381 * it would be extremely annoying.
1383 if (argc)
1384 verify_non_filename(opts->prefix, arg);
1385 } else if (opts->accept_pathspec) {
1386 argcount++;
1387 argv++;
1388 argc--;
1391 return argcount;
1394 static int switch_unborn_to_new_branch(const struct checkout_opts *opts)
1396 int status;
1397 struct strbuf branch_ref = STRBUF_INIT;
1399 trace2_cmd_mode("unborn");
1401 if (!opts->new_branch)
1402 die(_("You are on a branch yet to be born"));
1403 strbuf_addf(&branch_ref, "refs/heads/%s", opts->new_branch);
1404 status = create_symref("HEAD", branch_ref.buf, "checkout -b");
1405 strbuf_release(&branch_ref);
1406 if (!opts->quiet)
1407 fprintf(stderr, _("Switched to a new branch '%s'\n"),
1408 opts->new_branch);
1409 return status;
1412 static void die_expecting_a_branch(const struct branch_info *branch_info)
1414 struct object_id oid;
1415 char *to_free;
1416 int code;
1418 if (dwim_ref(branch_info->name, strlen(branch_info->name), &oid, &to_free, 0) == 1) {
1419 const char *ref = to_free;
1421 if (skip_prefix(ref, "refs/tags/", &ref))
1422 code = die_message(_("a branch is expected, got tag '%s'"), ref);
1423 else if (skip_prefix(ref, "refs/remotes/", &ref))
1424 code = die_message(_("a branch is expected, got remote branch '%s'"), ref);
1425 else
1426 code = die_message(_("a branch is expected, got '%s'"), ref);
1428 else if (branch_info->commit)
1429 code = die_message(_("a branch is expected, got commit '%s'"), branch_info->name);
1430 else
1432 * This case should never happen because we already die() on
1433 * non-commit, but just in case.
1435 code = die_message(_("a branch is expected, got '%s'"), branch_info->name);
1437 if (advice_enabled(ADVICE_SUGGEST_DETACHING_HEAD))
1438 advise(_("If you want to detach HEAD at the commit, try again with the --detach option."));
1440 exit(code);
1443 static void die_if_some_operation_in_progress(void)
1445 struct wt_status_state state;
1447 memset(&state, 0, sizeof(state));
1448 wt_status_get_state(the_repository, &state, 0);
1450 if (state.merge_in_progress)
1451 die(_("cannot switch branch while merging\n"
1452 "Consider \"git merge --quit\" "
1453 "or \"git worktree add\"."));
1454 if (state.am_in_progress)
1455 die(_("cannot switch branch in the middle of an am session\n"
1456 "Consider \"git am --quit\" "
1457 "or \"git worktree add\"."));
1458 if (state.rebase_interactive_in_progress || state.rebase_in_progress)
1459 die(_("cannot switch branch while rebasing\n"
1460 "Consider \"git rebase --quit\" "
1461 "or \"git worktree add\"."));
1462 if (state.cherry_pick_in_progress)
1463 die(_("cannot switch branch while cherry-picking\n"
1464 "Consider \"git cherry-pick --quit\" "
1465 "or \"git worktree add\"."));
1466 if (state.revert_in_progress)
1467 die(_("cannot switch branch while reverting\n"
1468 "Consider \"git revert --quit\" "
1469 "or \"git worktree add\"."));
1470 if (state.bisect_in_progress)
1471 warning(_("you are switching branch while bisecting"));
1474 static int checkout_branch(struct checkout_opts *opts,
1475 struct branch_info *new_branch_info)
1477 if (opts->pathspec.nr)
1478 die(_("paths cannot be used with switching branches"));
1480 if (opts->patch_mode)
1481 die(_("'%s' cannot be used with switching branches"),
1482 "--patch");
1484 if (opts->overlay_mode != -1)
1485 die(_("'%s' cannot be used with switching branches"),
1486 "--[no]-overlay");
1488 if (opts->writeout_stage)
1489 die(_("'%s' cannot be used with switching branches"),
1490 "--ours/--theirs");
1492 if (opts->force && opts->merge)
1493 die(_("'%s' cannot be used with '%s'"), "-f", "-m");
1495 if (opts->discard_changes && opts->merge)
1496 die(_("'%s' cannot be used with '%s'"), "--discard-changes", "--merge");
1498 if (opts->force_detach && opts->new_branch)
1499 die(_("'%s' cannot be used with '%s'"),
1500 "--detach", "-b/-B/--orphan");
1502 if (opts->new_orphan_branch) {
1503 if (opts->track != BRANCH_TRACK_UNSPECIFIED)
1504 die(_("'%s' cannot be used with '%s'"), "--orphan", "-t");
1505 if (opts->orphan_from_empty_tree && new_branch_info->name)
1506 die(_("'%s' cannot take <start-point>"), "--orphan");
1507 } else if (opts->force_detach) {
1508 if (opts->track != BRANCH_TRACK_UNSPECIFIED)
1509 die(_("'%s' cannot be used with '%s'"), "--detach", "-t");
1510 } else if (opts->track == BRANCH_TRACK_UNSPECIFIED)
1511 opts->track = git_branch_track;
1513 if (new_branch_info->name && !new_branch_info->commit)
1514 die(_("Cannot switch branch to a non-commit '%s'"),
1515 new_branch_info->name);
1517 if (!opts->switch_branch_doing_nothing_is_ok &&
1518 !new_branch_info->name &&
1519 !opts->new_branch &&
1520 !opts->force_detach)
1521 die(_("missing branch or commit argument"));
1523 if (!opts->implicit_detach &&
1524 !opts->force_detach &&
1525 !opts->new_branch &&
1526 !opts->new_branch_force &&
1527 new_branch_info->name &&
1528 !new_branch_info->path)
1529 die_expecting_a_branch(new_branch_info);
1531 if (!opts->can_switch_when_in_progress)
1532 die_if_some_operation_in_progress();
1534 if (new_branch_info->path && !opts->force_detach && !opts->new_branch &&
1535 !opts->ignore_other_worktrees) {
1536 int flag;
1537 char *head_ref = resolve_refdup("HEAD", 0, NULL, &flag);
1538 if (head_ref &&
1539 (!(flag & REF_ISSYMREF) || strcmp(head_ref, new_branch_info->path)))
1540 die_if_checked_out(new_branch_info->path, 1);
1541 free(head_ref);
1544 if (!new_branch_info->commit && opts->new_branch) {
1545 struct object_id rev;
1546 int flag;
1548 if (!read_ref_full("HEAD", 0, &rev, &flag) &&
1549 (flag & REF_ISSYMREF) && is_null_oid(&rev))
1550 return switch_unborn_to_new_branch(opts);
1552 return switch_branches(opts, new_branch_info);
1555 static struct option *add_common_options(struct checkout_opts *opts,
1556 struct option *prevopts)
1558 struct option options[] = {
1559 OPT__QUIET(&opts->quiet, N_("suppress progress reporting")),
1560 OPT_CALLBACK_F(0, "recurse-submodules", NULL,
1561 "checkout", "control recursive updating of submodules",
1562 PARSE_OPT_OPTARG, option_parse_recurse_submodules_worktree_updater),
1563 OPT_BOOL(0, "progress", &opts->show_progress, N_("force progress reporting")),
1564 OPT_BOOL('m', "merge", &opts->merge, N_("perform a 3-way merge with the new branch")),
1565 OPT_STRING(0, "conflict", &opts->conflict_style, N_("style"),
1566 N_("conflict style (merge, diff3, or zdiff3)")),
1567 OPT_END()
1569 struct option *newopts = parse_options_concat(prevopts, options);
1570 free(prevopts);
1571 return newopts;
1574 static struct option *add_common_switch_branch_options(
1575 struct checkout_opts *opts, struct option *prevopts)
1577 struct option options[] = {
1578 OPT_BOOL('d', "detach", &opts->force_detach, N_("detach HEAD at named commit")),
1579 OPT_CALLBACK_F('t', "track", &opts->track, "(direct|inherit)",
1580 N_("set branch tracking configuration"),
1581 PARSE_OPT_OPTARG,
1582 parse_opt_tracking_mode),
1583 OPT__FORCE(&opts->force, N_("force checkout (throw away local modifications)"),
1584 PARSE_OPT_NOCOMPLETE),
1585 OPT_STRING(0, "orphan", &opts->new_orphan_branch, N_("new-branch"), N_("new unparented branch")),
1586 OPT_BOOL_F(0, "overwrite-ignore", &opts->overwrite_ignore,
1587 N_("update ignored files (default)"),
1588 PARSE_OPT_NOCOMPLETE),
1589 OPT_BOOL(0, "ignore-other-worktrees", &opts->ignore_other_worktrees,
1590 N_("do not check if another worktree is holding the given ref")),
1591 OPT_END()
1593 struct option *newopts = parse_options_concat(prevopts, options);
1594 free(prevopts);
1595 return newopts;
1598 static struct option *add_checkout_path_options(struct checkout_opts *opts,
1599 struct option *prevopts)
1601 struct option options[] = {
1602 OPT_SET_INT_F('2', "ours", &opts->writeout_stage,
1603 N_("checkout our version for unmerged files"),
1604 2, PARSE_OPT_NONEG),
1605 OPT_SET_INT_F('3', "theirs", &opts->writeout_stage,
1606 N_("checkout their version for unmerged files"),
1607 3, PARSE_OPT_NONEG),
1608 OPT_BOOL('p', "patch", &opts->patch_mode, N_("select hunks interactively")),
1609 OPT_BOOL(0, "ignore-skip-worktree-bits", &opts->ignore_skipworktree,
1610 N_("do not limit pathspecs to sparse entries only")),
1611 OPT_PATHSPEC_FROM_FILE(&opts->pathspec_from_file),
1612 OPT_PATHSPEC_FILE_NUL(&opts->pathspec_file_nul),
1613 OPT_END()
1615 struct option *newopts = parse_options_concat(prevopts, options);
1616 free(prevopts);
1617 return newopts;
1620 /* create-branch option (either b or c) */
1621 static char cb_option = 'b';
1623 static int checkout_main(int argc, const char **argv, const char *prefix,
1624 struct checkout_opts *opts, struct option *options,
1625 const char * const usagestr[],
1626 struct branch_info *new_branch_info)
1628 int parseopt_flags = 0;
1630 opts->overwrite_ignore = 1;
1631 opts->prefix = prefix;
1632 opts->show_progress = -1;
1634 git_config(git_checkout_config, opts);
1635 if (the_repository->gitdir) {
1636 prepare_repo_settings(the_repository);
1637 the_repository->settings.command_requires_full_index = 0;
1640 opts->track = BRANCH_TRACK_UNSPECIFIED;
1642 if (!opts->accept_pathspec && !opts->accept_ref)
1643 BUG("make up your mind, you need to take _something_");
1644 if (opts->accept_pathspec && opts->accept_ref)
1645 parseopt_flags = PARSE_OPT_KEEP_DASHDASH;
1647 argc = parse_options(argc, argv, prefix, options,
1648 usagestr, parseopt_flags);
1650 if (opts->show_progress < 0) {
1651 if (opts->quiet)
1652 opts->show_progress = 0;
1653 else
1654 opts->show_progress = isatty(2);
1657 if (opts->conflict_style) {
1658 opts->merge = 1; /* implied */
1659 git_xmerge_config("merge.conflictstyle", opts->conflict_style, NULL);
1661 if (opts->force) {
1662 opts->discard_changes = 1;
1663 opts->ignore_unmerged_opt = "--force";
1664 opts->ignore_unmerged = 1;
1667 if ((!!opts->new_branch + !!opts->new_branch_force + !!opts->new_orphan_branch) > 1)
1668 die(_("options '-%c', '-%c', and '%s' cannot be used together"),
1669 cb_option, toupper(cb_option), "--orphan");
1671 if (opts->overlay_mode == 1 && opts->patch_mode)
1672 die(_("options '%s' and '%s' cannot be used together"), "-p", "--overlay");
1674 if (opts->checkout_index >= 0 || opts->checkout_worktree >= 0) {
1675 if (opts->checkout_index < 0)
1676 opts->checkout_index = 0;
1677 if (opts->checkout_worktree < 0)
1678 opts->checkout_worktree = 0;
1679 } else {
1680 if (opts->checkout_index < 0)
1681 opts->checkout_index = -opts->checkout_index - 1;
1682 if (opts->checkout_worktree < 0)
1683 opts->checkout_worktree = -opts->checkout_worktree - 1;
1685 if (opts->checkout_index < 0 || opts->checkout_worktree < 0)
1686 BUG("these flags should be non-negative by now");
1688 * convenient shortcut: "git restore --staged [--worktree]" equals
1689 * "git restore --staged [--worktree] --source HEAD"
1691 if (!opts->from_treeish && opts->checkout_index)
1692 opts->from_treeish = "HEAD";
1695 * From here on, new_branch will contain the branch to be checked out,
1696 * and new_branch_force and new_orphan_branch will tell us which one of
1697 * -b/-B/-c/-C/--orphan is being used.
1699 if (opts->new_branch_force)
1700 opts->new_branch = opts->new_branch_force;
1702 if (opts->new_orphan_branch)
1703 opts->new_branch = opts->new_orphan_branch;
1705 /* --track without -c/-C/-b/-B/--orphan should DWIM */
1706 if (opts->track != BRANCH_TRACK_UNSPECIFIED && !opts->new_branch) {
1707 const char *argv0 = argv[0];
1708 if (!argc || !strcmp(argv0, "--"))
1709 die(_("--track needs a branch name"));
1710 skip_prefix(argv0, "refs/", &argv0);
1711 skip_prefix(argv0, "remotes/", &argv0);
1712 argv0 = strchr(argv0, '/');
1713 if (!argv0 || !argv0[1])
1714 die(_("missing branch name; try -%c"), cb_option);
1715 opts->new_branch = argv0 + 1;
1719 * Extract branch name from command line arguments, so
1720 * all that is left is pathspecs.
1722 * Handle
1724 * 1) git checkout <tree> -- [<paths>]
1725 * 2) git checkout -- [<paths>]
1726 * 3) git checkout <something> [<paths>]
1728 * including "last branch" syntax and DWIM-ery for names of
1729 * remote branches, erroring out for invalid or ambiguous cases.
1731 if (argc && opts->accept_ref) {
1732 struct object_id rev;
1733 int dwim_ok =
1734 !opts->patch_mode &&
1735 opts->dwim_new_local_branch &&
1736 opts->track == BRANCH_TRACK_UNSPECIFIED &&
1737 !opts->new_branch;
1738 int n = parse_branchname_arg(argc, argv, dwim_ok,
1739 new_branch_info, opts, &rev);
1740 argv += n;
1741 argc -= n;
1742 } else if (!opts->accept_ref && opts->from_treeish) {
1743 struct object_id rev;
1745 if (get_oid_mb(opts->from_treeish, &rev))
1746 die(_("could not resolve %s"), opts->from_treeish);
1748 setup_new_branch_info_and_source_tree(new_branch_info,
1749 opts, &rev,
1750 opts->from_treeish);
1752 if (!opts->source_tree)
1753 die(_("reference is not a tree: %s"), opts->from_treeish);
1756 if (argc) {
1757 parse_pathspec(&opts->pathspec, 0,
1758 opts->patch_mode ? PATHSPEC_PREFIX_ORIGIN : 0,
1759 prefix, argv);
1761 if (!opts->pathspec.nr)
1762 die(_("invalid path specification"));
1765 * Try to give more helpful suggestion.
1766 * new_branch && argc > 1 will be caught later.
1768 if (opts->new_branch && argc == 1 && !new_branch_info->commit)
1769 die(_("'%s' is not a commit and a branch '%s' cannot be created from it"),
1770 argv[0], opts->new_branch);
1772 if (opts->force_detach)
1773 die(_("git checkout: --detach does not take a path argument '%s'"),
1774 argv[0]);
1777 if (opts->pathspec_from_file) {
1778 if (opts->pathspec.nr)
1779 die(_("'%s' and pathspec arguments cannot be used together"), "--pathspec-from-file");
1781 if (opts->force_detach)
1782 die(_("options '%s' and '%s' cannot be used together"), "--pathspec-from-file", "--detach");
1784 if (opts->patch_mode)
1785 die(_("options '%s' and '%s' cannot be used together"), "--pathspec-from-file", "--patch");
1787 parse_pathspec_file(&opts->pathspec, 0,
1789 prefix, opts->pathspec_from_file, opts->pathspec_file_nul);
1790 } else if (opts->pathspec_file_nul) {
1791 die(_("the option '%s' requires '%s'"), "--pathspec-file-nul", "--pathspec-from-file");
1794 opts->pathspec.recursive = 1;
1796 if (opts->pathspec.nr) {
1797 if (1 < !!opts->writeout_stage + !!opts->force + !!opts->merge)
1798 die(_("git checkout: --ours/--theirs, --force and --merge are incompatible when\n"
1799 "checking out of the index."));
1800 } else {
1801 if (opts->accept_pathspec && !opts->empty_pathspec_ok &&
1802 !opts->patch_mode) /* patch mode is special */
1803 die(_("you must specify path(s) to restore"));
1806 if (opts->new_branch) {
1807 struct strbuf buf = STRBUF_INIT;
1809 if (opts->new_branch_force)
1810 opts->branch_exists = validate_branchname(opts->new_branch, &buf);
1811 else
1812 opts->branch_exists =
1813 validate_new_branchname(opts->new_branch, &buf, 0);
1814 strbuf_release(&buf);
1817 if (opts->patch_mode || opts->pathspec.nr)
1818 return checkout_paths(opts, new_branch_info);
1819 else
1820 return checkout_branch(opts, new_branch_info);
1823 int cmd_checkout(int argc, const char **argv, const char *prefix)
1825 struct checkout_opts opts;
1826 struct option *options;
1827 struct option checkout_options[] = {
1828 OPT_STRING('b', NULL, &opts.new_branch, N_("branch"),
1829 N_("create and checkout a new branch")),
1830 OPT_STRING('B', NULL, &opts.new_branch_force, N_("branch"),
1831 N_("create/reset and checkout a branch")),
1832 OPT_BOOL('l', NULL, &opts.new_branch_log, N_("create reflog for new branch")),
1833 OPT_BOOL(0, "guess", &opts.dwim_new_local_branch,
1834 N_("second guess 'git checkout <no-such-branch>' (default)")),
1835 OPT_BOOL(0, "overlay", &opts.overlay_mode, N_("use overlay mode (default)")),
1836 OPT_END()
1838 int ret;
1839 struct branch_info new_branch_info = { 0 };
1841 memset(&opts, 0, sizeof(opts));
1842 opts.dwim_new_local_branch = 1;
1843 opts.switch_branch_doing_nothing_is_ok = 1;
1844 opts.only_merge_on_switching_branches = 0;
1845 opts.accept_ref = 1;
1846 opts.accept_pathspec = 1;
1847 opts.implicit_detach = 1;
1848 opts.can_switch_when_in_progress = 1;
1849 opts.orphan_from_empty_tree = 0;
1850 opts.empty_pathspec_ok = 1;
1851 opts.overlay_mode = -1;
1852 opts.checkout_index = -2; /* default on */
1853 opts.checkout_worktree = -2; /* default on */
1855 if (argc == 3 && !strcmp(argv[1], "-b")) {
1857 * User ran 'git checkout -b <branch>' and expects
1858 * the same behavior as 'git switch -c <branch>'.
1860 opts.switch_branch_doing_nothing_is_ok = 0;
1861 opts.only_merge_on_switching_branches = 1;
1864 options = parse_options_dup(checkout_options);
1865 options = add_common_options(&opts, options);
1866 options = add_common_switch_branch_options(&opts, options);
1867 options = add_checkout_path_options(&opts, options);
1869 ret = checkout_main(argc, argv, prefix, &opts,
1870 options, checkout_usage, &new_branch_info);
1871 branch_info_release(&new_branch_info);
1872 clear_pathspec(&opts.pathspec);
1873 FREE_AND_NULL(options);
1874 return ret;
1877 int cmd_switch(int argc, const char **argv, const char *prefix)
1879 struct checkout_opts opts;
1880 struct option *options = NULL;
1881 struct option switch_options[] = {
1882 OPT_STRING('c', "create", &opts.new_branch, N_("branch"),
1883 N_("create and switch to a new branch")),
1884 OPT_STRING('C', "force-create", &opts.new_branch_force, N_("branch"),
1885 N_("create/reset and switch to a branch")),
1886 OPT_BOOL(0, "guess", &opts.dwim_new_local_branch,
1887 N_("second guess 'git switch <no-such-branch>'")),
1888 OPT_BOOL(0, "discard-changes", &opts.discard_changes,
1889 N_("throw away local modifications")),
1890 OPT_END()
1892 int ret;
1893 struct branch_info new_branch_info = { 0 };
1895 memset(&opts, 0, sizeof(opts));
1896 opts.dwim_new_local_branch = 1;
1897 opts.accept_ref = 1;
1898 opts.accept_pathspec = 0;
1899 opts.switch_branch_doing_nothing_is_ok = 0;
1900 opts.only_merge_on_switching_branches = 1;
1901 opts.implicit_detach = 0;
1902 opts.can_switch_when_in_progress = 0;
1903 opts.orphan_from_empty_tree = 1;
1904 opts.overlay_mode = -1;
1906 options = parse_options_dup(switch_options);
1907 options = add_common_options(&opts, options);
1908 options = add_common_switch_branch_options(&opts, options);
1910 cb_option = 'c';
1912 ret = checkout_main(argc, argv, prefix, &opts,
1913 options, switch_branch_usage, &new_branch_info);
1914 branch_info_release(&new_branch_info);
1915 FREE_AND_NULL(options);
1916 return ret;
1919 int cmd_restore(int argc, const char **argv, const char *prefix)
1921 struct checkout_opts opts;
1922 struct option *options;
1923 struct option restore_options[] = {
1924 OPT_STRING('s', "source", &opts.from_treeish, "<tree-ish>",
1925 N_("which tree-ish to checkout from")),
1926 OPT_BOOL('S', "staged", &opts.checkout_index,
1927 N_("restore the index")),
1928 OPT_BOOL('W', "worktree", &opts.checkout_worktree,
1929 N_("restore the working tree (default)")),
1930 OPT_BOOL(0, "ignore-unmerged", &opts.ignore_unmerged,
1931 N_("ignore unmerged entries")),
1932 OPT_BOOL(0, "overlay", &opts.overlay_mode, N_("use overlay mode")),
1933 OPT_END()
1935 int ret;
1936 struct branch_info new_branch_info = { 0 };
1938 memset(&opts, 0, sizeof(opts));
1939 opts.accept_ref = 0;
1940 opts.accept_pathspec = 1;
1941 opts.empty_pathspec_ok = 0;
1942 opts.overlay_mode = 0;
1943 opts.checkout_index = -1; /* default off */
1944 opts.checkout_worktree = -2; /* default on */
1945 opts.ignore_unmerged_opt = "--ignore-unmerged";
1947 options = parse_options_dup(restore_options);
1948 options = add_common_options(&opts, options);
1949 options = add_checkout_path_options(&opts, options);
1951 ret = checkout_main(argc, argv, prefix, &opts,
1952 options, restore_usage, &new_branch_info);
1953 branch_info_release(&new_branch_info);
1954 FREE_AND_NULL(options);
1955 return ret;