banned.h: mark `strtok()` and `strtok_r()` as banned
[git/debian.git] / builtin / checkout.c
blob38a8cd6a965210b3959043c3e228a3d84ba93ab1
1 #define USE_THE_INDEX_VARIABLE
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 "environment.h"
13 #include "gettext.h"
14 #include "hex.h"
15 #include "hook.h"
16 #include "ll-merge.h"
17 #include "lockfile.h"
18 #include "merge-recursive.h"
19 #include "object-store.h"
20 #include "parse-options.h"
21 #include "refs.h"
22 #include "remote.h"
23 #include "resolve-undo.h"
24 #include "revision.h"
25 #include "run-command.h"
26 #include "setup.h"
27 #include "submodule.h"
28 #include "submodule-config.h"
29 #include "tree.h"
30 #include "tree-walk.h"
31 #include "unpack-trees.h"
32 #include "wt-status.h"
33 #include "xdiff-interface.h"
34 #include "entry.h"
35 #include "parallel-checkout.h"
36 #include "add-interactive.h"
38 static const char * const checkout_usage[] = {
39 N_("git checkout [<options>] <branch>"),
40 N_("git checkout [<options>] [<branch>] -- <file>..."),
41 NULL,
44 static const char * const switch_branch_usage[] = {
45 N_("git switch [<options>] [<branch>]"),
46 NULL,
49 static const char * const restore_usage[] = {
50 N_("git restore [<options>] [--source=<branch>] <file>..."),
51 NULL,
54 struct checkout_opts {
55 int patch_mode;
56 int quiet;
57 int merge;
58 int force;
59 int force_detach;
60 int implicit_detach;
61 int writeout_stage;
62 int overwrite_ignore;
63 int ignore_skipworktree;
64 int ignore_other_worktrees;
65 int show_progress;
66 int count_checkout_paths;
67 int overlay_mode;
68 int dwim_new_local_branch;
69 int discard_changes;
70 int accept_ref;
71 int accept_pathspec;
72 int switch_branch_doing_nothing_is_ok;
73 int only_merge_on_switching_branches;
74 int can_switch_when_in_progress;
75 int orphan_from_empty_tree;
76 int empty_pathspec_ok;
77 int checkout_index;
78 int checkout_worktree;
79 const char *ignore_unmerged_opt;
80 int ignore_unmerged;
81 int pathspec_file_nul;
82 char *pathspec_from_file;
84 const char *new_branch;
85 const char *new_branch_force;
86 const char *new_orphan_branch;
87 int new_branch_log;
88 enum branch_track track;
89 struct diff_options diff_options;
90 char *conflict_style;
92 int branch_exists;
93 const char *prefix;
94 struct pathspec pathspec;
95 const char *from_treeish;
96 struct tree *source_tree;
99 struct branch_info {
100 char *name; /* The short name used */
101 char *path; /* The full name of a real branch */
102 struct commit *commit; /* The named commit */
103 char *refname; /* The full name of the ref being checked out. */
104 struct object_id oid; /* The object ID of the commit being checked out. */
106 * if not null the branch is detached because it's already
107 * checked out in this checkout
109 char *checkout;
112 static void branch_info_release(struct branch_info *info)
114 free(info->name);
115 free(info->path);
116 free(info->refname);
117 free(info->checkout);
120 static int post_checkout_hook(struct commit *old_commit, struct commit *new_commit,
121 int changed)
123 return run_hooks_l("post-checkout",
124 oid_to_hex(old_commit ? &old_commit->object.oid : null_oid()),
125 oid_to_hex(new_commit ? &new_commit->object.oid : null_oid()),
126 changed ? "1" : "0", NULL);
127 /* "new_commit" can be NULL when checking out from the index before
128 a commit exists. */
132 static int update_some(const struct object_id *oid, struct strbuf *base,
133 const char *pathname, unsigned mode, void *context UNUSED)
135 int len;
136 struct cache_entry *ce;
137 int pos;
139 if (S_ISDIR(mode))
140 return READ_TREE_RECURSIVE;
142 len = base->len + strlen(pathname);
143 ce = make_empty_cache_entry(&the_index, len);
144 oidcpy(&ce->oid, oid);
145 memcpy(ce->name, base->buf, base->len);
146 memcpy(ce->name + base->len, pathname, len - base->len);
147 ce->ce_flags = create_ce_flags(0) | CE_UPDATE;
148 ce->ce_namelen = len;
149 ce->ce_mode = create_ce_mode(mode);
152 * If the entry is the same as the current index, we can leave the old
153 * entry in place. Whether it is UPTODATE or not, checkout_entry will
154 * do the right thing.
156 pos = index_name_pos(&the_index, ce->name, ce->ce_namelen);
157 if (pos >= 0) {
158 struct cache_entry *old = the_index.cache[pos];
159 if (ce->ce_mode == old->ce_mode &&
160 !ce_intent_to_add(old) &&
161 oideq(&ce->oid, &old->oid)) {
162 old->ce_flags |= CE_UPDATE;
163 discard_cache_entry(ce);
164 return 0;
168 add_index_entry(&the_index, ce,
169 ADD_CACHE_OK_TO_ADD | ADD_CACHE_OK_TO_REPLACE);
170 return 0;
173 static int read_tree_some(struct tree *tree, const struct pathspec *pathspec)
175 read_tree(the_repository, tree,
176 pathspec, update_some, NULL);
178 /* update the index with the given tree's info
179 * for all args, expanding wildcards, and exit
180 * with any non-zero return code.
182 return 0;
185 static int skip_same_name(const struct cache_entry *ce, int pos)
187 while (++pos < the_index.cache_nr &&
188 !strcmp(the_index.cache[pos]->name, ce->name))
189 ; /* skip */
190 return pos;
193 static int check_stage(int stage, const struct cache_entry *ce, int pos,
194 int overlay_mode)
196 while (pos < the_index.cache_nr &&
197 !strcmp(the_index.cache[pos]->name, ce->name)) {
198 if (ce_stage(the_index.cache[pos]) == stage)
199 return 0;
200 pos++;
202 if (!overlay_mode)
203 return 0;
204 if (stage == 2)
205 return error(_("path '%s' does not have our version"), ce->name);
206 else
207 return error(_("path '%s' does not have their version"), ce->name);
210 static int check_stages(unsigned stages, const struct cache_entry *ce, int pos)
212 unsigned seen = 0;
213 const char *name = ce->name;
215 while (pos < the_index.cache_nr) {
216 ce = the_index.cache[pos];
217 if (strcmp(name, ce->name))
218 break;
219 seen |= (1 << ce_stage(ce));
220 pos++;
222 if ((stages & seen) != stages)
223 return error(_("path '%s' does not have all necessary versions"),
224 name);
225 return 0;
228 static int checkout_stage(int stage, const struct cache_entry *ce, int pos,
229 const struct checkout *state, int *nr_checkouts,
230 int overlay_mode)
232 while (pos < the_index.cache_nr &&
233 !strcmp(the_index.cache[pos]->name, ce->name)) {
234 if (ce_stage(the_index.cache[pos]) == stage)
235 return checkout_entry(the_index.cache[pos], state,
236 NULL, nr_checkouts);
237 pos++;
239 if (!overlay_mode) {
240 unlink_entry(ce, NULL);
241 return 0;
243 if (stage == 2)
244 return error(_("path '%s' does not have our version"), ce->name);
245 else
246 return error(_("path '%s' does not have their version"), ce->name);
249 static int checkout_merged(int pos, const struct checkout *state,
250 int *nr_checkouts, struct mem_pool *ce_mem_pool)
252 struct cache_entry *ce = the_index.cache[pos];
253 const char *path = ce->name;
254 mmfile_t ancestor, ours, theirs;
255 enum ll_merge_result merge_status;
256 int status;
257 struct object_id oid;
258 mmbuffer_t result_buf;
259 struct object_id threeway[3];
260 unsigned mode = 0;
261 struct ll_merge_options ll_opts;
262 int renormalize = 0;
264 memset(threeway, 0, sizeof(threeway));
265 while (pos < the_index.cache_nr) {
266 int stage;
267 stage = ce_stage(ce);
268 if (!stage || strcmp(path, ce->name))
269 break;
270 oidcpy(&threeway[stage - 1], &ce->oid);
271 if (stage == 2)
272 mode = create_ce_mode(ce->ce_mode);
273 pos++;
274 ce = the_index.cache[pos];
276 if (is_null_oid(&threeway[1]) || is_null_oid(&threeway[2]))
277 return error(_("path '%s' does not have necessary versions"), path);
279 read_mmblob(&ancestor, &threeway[0]);
280 read_mmblob(&ours, &threeway[1]);
281 read_mmblob(&theirs, &threeway[2]);
283 memset(&ll_opts, 0, sizeof(ll_opts));
284 git_config_get_bool("merge.renormalize", &renormalize);
285 ll_opts.renormalize = renormalize;
286 merge_status = ll_merge(&result_buf, path, &ancestor, "base",
287 &ours, "ours", &theirs, "theirs",
288 state->istate, &ll_opts);
289 free(ancestor.ptr);
290 free(ours.ptr);
291 free(theirs.ptr);
292 if (merge_status == LL_MERGE_BINARY_CONFLICT)
293 warning("Cannot merge binary files: %s (%s vs. %s)",
294 path, "ours", "theirs");
295 if (merge_status < 0 || !result_buf.ptr) {
296 free(result_buf.ptr);
297 return error(_("path '%s': cannot merge"), path);
301 * NEEDSWORK:
302 * There is absolutely no reason to write this as a blob object
303 * and create a phony cache entry. This hack is primarily to get
304 * to the write_entry() machinery that massages the contents to
305 * work-tree format and writes out which only allows it for a
306 * cache entry. The code in write_entry() needs to be refactored
307 * to allow us to feed a <buffer, size, mode> instead of a cache
308 * entry. Such a refactoring would help merge_recursive as well
309 * (it also writes the merge result to the object database even
310 * when it may contain conflicts).
312 if (write_object_file(result_buf.ptr, result_buf.size, OBJ_BLOB, &oid))
313 die(_("Unable to add merge result for '%s'"), path);
314 free(result_buf.ptr);
315 ce = make_transient_cache_entry(mode, &oid, path, 2, ce_mem_pool);
316 if (!ce)
317 die(_("make_cache_entry failed for path '%s'"), path);
318 status = checkout_entry(ce, state, NULL, nr_checkouts);
319 return status;
322 static void mark_ce_for_checkout_overlay(struct cache_entry *ce,
323 char *ps_matched,
324 const struct checkout_opts *opts)
326 ce->ce_flags &= ~CE_MATCHED;
327 if (!opts->ignore_skipworktree && ce_skip_worktree(ce))
328 return;
329 if (opts->source_tree && !(ce->ce_flags & CE_UPDATE))
331 * "git checkout tree-ish -- path", but this entry
332 * is in the original index but is not in tree-ish
333 * or does not match the pathspec; it will not be
334 * checked out to the working tree. We will not do
335 * anything to this entry at all.
337 return;
339 * Either this entry came from the tree-ish we are
340 * checking the paths out of, or we are checking out
341 * of the index.
343 * If it comes from the tree-ish, we already know it
344 * matches the pathspec and could just stamp
345 * CE_MATCHED to it from update_some(). But we still
346 * need ps_matched and read_tree (and
347 * eventually tree_entry_interesting) cannot fill
348 * ps_matched yet. Once it can, we can avoid calling
349 * match_pathspec() for _all_ entries when
350 * opts->source_tree != NULL.
352 if (ce_path_match(&the_index, ce, &opts->pathspec, ps_matched))
353 ce->ce_flags |= CE_MATCHED;
356 static void mark_ce_for_checkout_no_overlay(struct cache_entry *ce,
357 char *ps_matched,
358 const struct checkout_opts *opts)
360 ce->ce_flags &= ~CE_MATCHED;
361 if (!opts->ignore_skipworktree && ce_skip_worktree(ce))
362 return;
363 if (ce_path_match(&the_index, ce, &opts->pathspec, ps_matched)) {
364 ce->ce_flags |= CE_MATCHED;
365 if (opts->source_tree && !(ce->ce_flags & CE_UPDATE))
367 * In overlay mode, but the path is not in
368 * tree-ish, which means we should remove it
369 * from the index and the working tree.
371 ce->ce_flags |= CE_REMOVE | CE_WT_REMOVE;
375 static int checkout_worktree(const struct checkout_opts *opts,
376 const struct branch_info *info)
378 struct checkout state = CHECKOUT_INIT;
379 int nr_checkouts = 0, nr_unmerged = 0;
380 int errs = 0;
381 int pos;
382 int pc_workers, pc_threshold;
383 struct mem_pool ce_mem_pool;
385 state.force = 1;
386 state.refresh_cache = 1;
387 state.istate = &the_index;
389 mem_pool_init(&ce_mem_pool, 0);
390 get_parallel_checkout_configs(&pc_workers, &pc_threshold);
391 init_checkout_metadata(&state.meta, info->refname,
392 info->commit ? &info->commit->object.oid : &info->oid,
393 NULL);
395 enable_delayed_checkout(&state);
397 if (pc_workers > 1)
398 init_parallel_checkout();
400 for (pos = 0; pos < the_index.cache_nr; pos++) {
401 struct cache_entry *ce = the_index.cache[pos];
402 if (ce->ce_flags & CE_MATCHED) {
403 if (!ce_stage(ce)) {
404 errs |= checkout_entry(ce, &state,
405 NULL, &nr_checkouts);
406 continue;
408 if (opts->writeout_stage)
409 errs |= checkout_stage(opts->writeout_stage,
410 ce, pos,
411 &state,
412 &nr_checkouts, opts->overlay_mode);
413 else if (opts->merge)
414 errs |= checkout_merged(pos, &state,
415 &nr_unmerged,
416 &ce_mem_pool);
417 pos = skip_same_name(ce, pos) - 1;
420 if (pc_workers > 1)
421 errs |= run_parallel_checkout(&state, pc_workers, pc_threshold,
422 NULL, NULL);
423 mem_pool_discard(&ce_mem_pool, should_validate_cache_entries());
424 remove_marked_cache_entries(&the_index, 1);
425 remove_scheduled_dirs();
426 errs |= finish_delayed_checkout(&state, opts->show_progress);
428 if (opts->count_checkout_paths) {
429 if (nr_unmerged)
430 fprintf_ln(stderr, Q_("Recreated %d merge conflict",
431 "Recreated %d merge conflicts",
432 nr_unmerged),
433 nr_unmerged);
434 if (opts->source_tree)
435 fprintf_ln(stderr, Q_("Updated %d path from %s",
436 "Updated %d paths from %s",
437 nr_checkouts),
438 nr_checkouts,
439 repo_find_unique_abbrev(the_repository, &opts->source_tree->object.oid,
440 DEFAULT_ABBREV));
441 else if (!nr_unmerged || nr_checkouts)
442 fprintf_ln(stderr, Q_("Updated %d path from the index",
443 "Updated %d paths from the index",
444 nr_checkouts),
445 nr_checkouts);
448 return errs;
451 static int checkout_paths(const struct checkout_opts *opts,
452 const struct branch_info *new_branch_info)
454 int pos;
455 static char *ps_matched;
456 struct object_id rev;
457 struct commit *head;
458 int errs = 0;
459 struct lock_file lock_file = LOCK_INIT;
460 int checkout_index;
462 trace2_cmd_mode(opts->patch_mode ? "patch" : "path");
464 if (opts->track != BRANCH_TRACK_UNSPECIFIED)
465 die(_("'%s' cannot be used with updating paths"), "--track");
467 if (opts->new_branch_log)
468 die(_("'%s' cannot be used with updating paths"), "-l");
470 if (opts->ignore_unmerged && opts->patch_mode)
471 die(_("'%s' cannot be used with updating paths"),
472 opts->ignore_unmerged_opt);
474 if (opts->force_detach)
475 die(_("'%s' cannot be used with updating paths"), "--detach");
477 if (opts->merge && opts->patch_mode)
478 die(_("options '%s' and '%s' cannot be used together"), "--merge", "--patch");
480 if (opts->ignore_unmerged && opts->merge)
481 die(_("options '%s' and '%s' cannot be used together"),
482 opts->ignore_unmerged_opt, "-m");
484 if (opts->new_branch)
485 die(_("Cannot update paths and switch to branch '%s' at the same time."),
486 opts->new_branch);
488 if (!opts->checkout_worktree && !opts->checkout_index)
489 die(_("neither '%s' or '%s' is specified"),
490 "--staged", "--worktree");
492 if (!opts->checkout_worktree && !opts->from_treeish)
493 die(_("'%s' must be used when '%s' is not specified"),
494 "--worktree", "--source");
497 * Reject --staged option to the restore command when combined with
498 * merge-related options. Use the accept_ref flag to distinguish it
499 * from the checkout command, which does not accept --staged anyway.
501 * `restore --ours|--theirs --worktree --staged` could mean resolving
502 * conflicted paths to one side in both the worktree and the index,
503 * but does not currently.
505 * `restore --merge|--conflict=<style>` already recreates conflicts
506 * in both the worktree and the index, so adding --staged would be
507 * meaningless.
509 if (!opts->accept_ref && opts->checkout_index) {
510 if (opts->writeout_stage)
511 die(_("'%s' or '%s' cannot be used with %s"),
512 "--ours", "--theirs", "--staged");
514 if (opts->merge)
515 die(_("'%s' or '%s' cannot be used with %s"),
516 "--merge", "--conflict", "--staged");
519 if (opts->patch_mode) {
520 enum add_p_mode patch_mode;
521 const char *rev = new_branch_info->name;
522 char rev_oid[GIT_MAX_HEXSZ + 1];
525 * Since rev can be in the form of `<a>...<b>` (which is not
526 * recognized by diff-index), we will always replace the name
527 * with the hex of the commit (whether it's in `...` form or
528 * not) for the run_add_interactive() machinery to work
529 * properly. However, there is special logic for the HEAD case
530 * so we mustn't replace that. Also, when we were given a
531 * tree-object, new_branch_info->commit would be NULL, but we
532 * do not have to do any replacement, either.
534 if (rev && new_branch_info->commit && strcmp(rev, "HEAD"))
535 rev = oid_to_hex_r(rev_oid, &new_branch_info->commit->object.oid);
537 if (opts->checkout_index && opts->checkout_worktree)
538 patch_mode = ADD_P_CHECKOUT;
539 else if (opts->checkout_index && !opts->checkout_worktree)
540 patch_mode = ADD_P_RESET;
541 else if (!opts->checkout_index && opts->checkout_worktree)
542 patch_mode = ADD_P_WORKTREE;
543 else
544 BUG("either flag must have been set, worktree=%d, index=%d",
545 opts->checkout_worktree, opts->checkout_index);
546 return !!run_add_p(the_repository, patch_mode, rev,
547 &opts->pathspec);
550 repo_hold_locked_index(the_repository, &lock_file, LOCK_DIE_ON_ERROR);
551 if (repo_read_index_preload(the_repository, &opts->pathspec, 0) < 0)
552 return error(_("index file corrupt"));
554 if (opts->source_tree)
555 read_tree_some(opts->source_tree, &opts->pathspec);
557 ps_matched = xcalloc(opts->pathspec.nr, 1);
560 * Make sure all pathspecs participated in locating the paths
561 * to be checked out.
563 for (pos = 0; pos < the_index.cache_nr; pos++)
564 if (opts->overlay_mode)
565 mark_ce_for_checkout_overlay(the_index.cache[pos],
566 ps_matched,
567 opts);
568 else
569 mark_ce_for_checkout_no_overlay(the_index.cache[pos],
570 ps_matched,
571 opts);
573 if (report_path_error(ps_matched, &opts->pathspec)) {
574 free(ps_matched);
575 return 1;
577 free(ps_matched);
579 /* "checkout -m path" to recreate conflicted state */
580 if (opts->merge)
581 unmerge_marked_index(&the_index);
583 /* Any unmerged paths? */
584 for (pos = 0; pos < the_index.cache_nr; pos++) {
585 const struct cache_entry *ce = the_index.cache[pos];
586 if (ce->ce_flags & CE_MATCHED) {
587 if (!ce_stage(ce))
588 continue;
589 if (opts->ignore_unmerged) {
590 if (!opts->quiet)
591 warning(_("path '%s' is unmerged"), ce->name);
592 } else if (opts->writeout_stage) {
593 errs |= check_stage(opts->writeout_stage, ce, pos, opts->overlay_mode);
594 } else if (opts->merge) {
595 errs |= check_stages((1<<2) | (1<<3), ce, pos);
596 } else {
597 errs = 1;
598 error(_("path '%s' is unmerged"), ce->name);
600 pos = skip_same_name(ce, pos) - 1;
603 if (errs)
604 return 1;
606 /* Now we are committed to check them out */
607 if (opts->checkout_worktree)
608 errs |= checkout_worktree(opts, new_branch_info);
609 else
610 remove_marked_cache_entries(&the_index, 1);
613 * Allow updating the index when checking out from the index.
614 * This is to save new stat info.
616 if (opts->checkout_worktree && !opts->checkout_index && !opts->source_tree)
617 checkout_index = 1;
618 else
619 checkout_index = opts->checkout_index;
621 if (checkout_index) {
622 if (write_locked_index(&the_index, &lock_file, COMMIT_LOCK))
623 die(_("unable to write new index file"));
624 } else {
626 * NEEDSWORK: if --worktree is not specified, we
627 * should save stat info of checked out files in the
628 * index to avoid the next (potentially costly)
629 * refresh. But it's a bit tricker to do...
631 rollback_lock_file(&lock_file);
634 read_ref_full("HEAD", 0, &rev, NULL);
635 head = lookup_commit_reference_gently(the_repository, &rev, 1);
637 errs |= post_checkout_hook(head, head, 0);
638 return errs;
641 static void show_local_changes(struct object *head,
642 const struct diff_options *opts)
644 struct rev_info rev;
645 /* I think we want full paths, even if we're in a subdirectory. */
646 repo_init_revisions(the_repository, &rev, NULL);
647 rev.diffopt.flags = opts->flags;
648 rev.diffopt.output_format |= DIFF_FORMAT_NAME_STATUS;
649 rev.diffopt.flags.recursive = 1;
650 diff_setup_done(&rev.diffopt);
651 add_pending_object(&rev, head, NULL);
652 run_diff_index(&rev, 0);
653 release_revisions(&rev);
656 static void describe_detached_head(const char *msg, struct commit *commit)
658 struct strbuf sb = STRBUF_INIT;
660 if (!repo_parse_commit(the_repository, commit))
661 pp_commit_easy(CMIT_FMT_ONELINE, commit, &sb);
662 if (print_sha1_ellipsis()) {
663 fprintf(stderr, "%s %s... %s\n", msg,
664 repo_find_unique_abbrev(the_repository, &commit->object.oid, DEFAULT_ABBREV),
665 sb.buf);
666 } else {
667 fprintf(stderr, "%s %s %s\n", msg,
668 repo_find_unique_abbrev(the_repository, &commit->object.oid, DEFAULT_ABBREV),
669 sb.buf);
671 strbuf_release(&sb);
674 static int reset_tree(struct tree *tree, const struct checkout_opts *o,
675 int worktree, int *writeout_error,
676 struct branch_info *info)
678 struct unpack_trees_options opts;
679 struct tree_desc tree_desc;
681 memset(&opts, 0, sizeof(opts));
682 opts.head_idx = -1;
683 opts.update = worktree;
684 opts.skip_unmerged = !worktree;
685 opts.reset = o->force ? UNPACK_RESET_OVERWRITE_UNTRACKED :
686 UNPACK_RESET_PROTECT_UNTRACKED;
687 opts.preserve_ignored = (!o->force && !o->overwrite_ignore);
688 opts.merge = 1;
689 opts.fn = oneway_merge;
690 opts.verbose_update = o->show_progress;
691 opts.src_index = &the_index;
692 opts.dst_index = &the_index;
693 init_checkout_metadata(&opts.meta, info->refname,
694 info->commit ? &info->commit->object.oid : null_oid(),
695 NULL);
696 parse_tree(tree);
697 init_tree_desc(&tree_desc, tree->buffer, tree->size);
698 switch (unpack_trees(1, &tree_desc, &opts)) {
699 case -2:
700 *writeout_error = 1;
702 * We return 0 nevertheless, as the index is all right
703 * and more importantly we have made best efforts to
704 * update paths in the work tree, and we cannot revert
705 * them.
707 /* fallthrough */
708 case 0:
709 return 0;
710 default:
711 return 128;
715 static void setup_branch_path(struct branch_info *branch)
717 struct strbuf buf = STRBUF_INIT;
720 * If this is a ref, resolve it; otherwise, look up the OID for our
721 * expression. Failure here is okay.
723 if (!repo_dwim_ref(the_repository, branch->name, strlen(branch->name),
724 &branch->oid, &branch->refname, 0))
725 repo_get_oid_committish(the_repository, branch->name, &branch->oid);
727 strbuf_branchname(&buf, branch->name, INTERPRET_BRANCH_LOCAL);
728 if (strcmp(buf.buf, branch->name)) {
729 free(branch->name);
730 branch->name = xstrdup(buf.buf);
732 strbuf_splice(&buf, 0, 0, "refs/heads/", 11);
733 free(branch->path);
734 branch->path = strbuf_detach(&buf, NULL);
737 static void init_topts(struct unpack_trees_options *topts, int merge,
738 int show_progress, int overwrite_ignore,
739 struct commit *old_commit)
741 memset(topts, 0, sizeof(*topts));
742 topts->head_idx = -1;
743 topts->src_index = &the_index;
744 topts->dst_index = &the_index;
746 setup_unpack_trees_porcelain(topts, "checkout");
748 topts->initial_checkout = is_index_unborn(&the_index);
749 topts->update = 1;
750 topts->merge = 1;
751 topts->quiet = merge && old_commit;
752 topts->verbose_update = show_progress;
753 topts->fn = twoway_merge;
754 topts->preserve_ignored = !overwrite_ignore;
757 static int merge_working_tree(const struct checkout_opts *opts,
758 struct branch_info *old_branch_info,
759 struct branch_info *new_branch_info,
760 int *writeout_error)
762 int ret;
763 struct lock_file lock_file = LOCK_INIT;
764 struct tree *new_tree;
766 repo_hold_locked_index(the_repository, &lock_file, LOCK_DIE_ON_ERROR);
767 if (repo_read_index_preload(the_repository, NULL, 0) < 0)
768 return error(_("index file corrupt"));
770 resolve_undo_clear_index(&the_index);
771 if (opts->new_orphan_branch && opts->orphan_from_empty_tree) {
772 if (new_branch_info->commit)
773 BUG("'switch --orphan' should never accept a commit as starting point");
774 new_tree = parse_tree_indirect(the_hash_algo->empty_tree);
775 } else
776 new_tree = repo_get_commit_tree(the_repository,
777 new_branch_info->commit);
778 if (opts->discard_changes) {
779 ret = reset_tree(new_tree, opts, 1, writeout_error, new_branch_info);
780 if (ret)
781 return ret;
782 } else {
783 struct tree_desc trees[2];
784 struct tree *tree;
785 struct unpack_trees_options topts;
786 const struct object_id *old_commit_oid;
788 refresh_index(&the_index, REFRESH_QUIET, NULL, NULL, NULL);
790 if (unmerged_index(&the_index)) {
791 error(_("you need to resolve your current index first"));
792 return 1;
795 /* 2-way merge to the new branch */
796 init_topts(&topts, opts->merge, opts->show_progress,
797 opts->overwrite_ignore, old_branch_info->commit);
798 init_checkout_metadata(&topts.meta, new_branch_info->refname,
799 new_branch_info->commit ?
800 &new_branch_info->commit->object.oid :
801 &new_branch_info->oid, NULL);
803 old_commit_oid = old_branch_info->commit ?
804 &old_branch_info->commit->object.oid :
805 the_hash_algo->empty_tree;
806 tree = parse_tree_indirect(old_commit_oid);
807 if (!tree)
808 die(_("unable to parse commit %s"),
809 oid_to_hex(old_commit_oid));
811 init_tree_desc(&trees[0], tree->buffer, tree->size);
812 parse_tree(new_tree);
813 tree = new_tree;
814 init_tree_desc(&trees[1], tree->buffer, tree->size);
816 ret = unpack_trees(2, trees, &topts);
817 clear_unpack_trees_porcelain(&topts);
818 if (ret == -1) {
820 * Unpack couldn't do a trivial merge; either
821 * give up or do a real merge, depending on
822 * whether the merge flag was used.
824 struct tree *work;
825 struct tree *old_tree;
826 struct merge_options o;
827 struct strbuf sb = STRBUF_INIT;
828 struct strbuf old_commit_shortname = STRBUF_INIT;
830 if (!opts->merge)
831 return 1;
834 * Without old_branch_info->commit, the below is the same as
835 * the two-tree unpack we already tried and failed.
837 if (!old_branch_info->commit)
838 return 1;
839 old_tree = repo_get_commit_tree(the_repository,
840 old_branch_info->commit);
842 if (repo_index_has_changes(the_repository, old_tree, &sb))
843 die(_("cannot continue with staged changes in "
844 "the following files:\n%s"), sb.buf);
845 strbuf_release(&sb);
847 /* Do more real merge */
850 * We update the index fully, then write the
851 * tree from the index, then merge the new
852 * branch with the current tree, with the old
853 * branch as the base. Then we reset the index
854 * (but not the working tree) to the new
855 * branch, leaving the working tree as the
856 * merged version, but skipping unmerged
857 * entries in the index.
860 add_files_to_cache(NULL, NULL, 0);
861 init_merge_options(&o, the_repository);
862 o.verbosity = 0;
863 work = write_in_core_index_as_tree(the_repository);
865 ret = reset_tree(new_tree,
866 opts, 1,
867 writeout_error, new_branch_info);
868 if (ret)
869 return ret;
870 o.ancestor = old_branch_info->name;
871 if (!old_branch_info->name) {
872 strbuf_add_unique_abbrev(&old_commit_shortname,
873 &old_branch_info->commit->object.oid,
874 DEFAULT_ABBREV);
875 o.ancestor = old_commit_shortname.buf;
877 o.branch1 = new_branch_info->name;
878 o.branch2 = "local";
879 ret = merge_trees(&o,
880 new_tree,
881 work,
882 old_tree);
883 if (ret < 0)
884 exit(128);
885 ret = reset_tree(new_tree,
886 opts, 0,
887 writeout_error, new_branch_info);
888 strbuf_release(&o.obuf);
889 strbuf_release(&old_commit_shortname);
890 if (ret)
891 return ret;
895 if (!cache_tree_fully_valid(the_index.cache_tree))
896 cache_tree_update(&the_index, WRITE_TREE_SILENT | WRITE_TREE_REPAIR);
898 if (write_locked_index(&the_index, &lock_file, COMMIT_LOCK))
899 die(_("unable to write new index file"));
901 if (!opts->discard_changes && !opts->quiet && new_branch_info->commit)
902 show_local_changes(&new_branch_info->commit->object, &opts->diff_options);
904 return 0;
907 static void report_tracking(struct branch_info *new_branch_info)
909 struct strbuf sb = STRBUF_INIT;
910 struct branch *branch = branch_get(new_branch_info->name);
912 if (!format_tracking_info(branch, &sb, AHEAD_BEHIND_FULL))
913 return;
914 fputs(sb.buf, stdout);
915 strbuf_release(&sb);
918 static void update_refs_for_switch(const struct checkout_opts *opts,
919 struct branch_info *old_branch_info,
920 struct branch_info *new_branch_info)
922 struct strbuf msg = STRBUF_INIT;
923 const char *old_desc, *reflog_msg;
924 if (opts->new_branch) {
925 if (opts->new_orphan_branch) {
926 char *refname;
928 refname = mkpathdup("refs/heads/%s", opts->new_orphan_branch);
929 if (opts->new_branch_log &&
930 !should_autocreate_reflog(refname)) {
931 int ret;
932 struct strbuf err = STRBUF_INIT;
934 ret = safe_create_reflog(refname, &err);
935 if (ret) {
936 fprintf(stderr, _("Can not do reflog for '%s': %s\n"),
937 opts->new_orphan_branch, err.buf);
938 strbuf_release(&err);
939 free(refname);
940 return;
942 strbuf_release(&err);
944 free(refname);
946 else
947 create_branch(the_repository,
948 opts->new_branch, new_branch_info->name,
949 opts->new_branch_force ? 1 : 0,
950 opts->new_branch_force ? 1 : 0,
951 opts->new_branch_log,
952 opts->quiet,
953 opts->track,
955 free(new_branch_info->name);
956 free(new_branch_info->refname);
957 new_branch_info->name = xstrdup(opts->new_branch);
958 setup_branch_path(new_branch_info);
961 old_desc = old_branch_info->name;
962 if (!old_desc && old_branch_info->commit)
963 old_desc = oid_to_hex(&old_branch_info->commit->object.oid);
965 reflog_msg = getenv("GIT_REFLOG_ACTION");
966 if (!reflog_msg)
967 strbuf_addf(&msg, "checkout: moving from %s to %s",
968 old_desc ? old_desc : "(invalid)", new_branch_info->name);
969 else
970 strbuf_insertstr(&msg, 0, reflog_msg);
972 if (!strcmp(new_branch_info->name, "HEAD") && !new_branch_info->path && !opts->force_detach) {
973 /* Nothing to do. */
974 } else if (opts->force_detach || !new_branch_info->path) { /* No longer on any branch. */
975 update_ref(msg.buf, "HEAD", &new_branch_info->commit->object.oid, NULL,
976 REF_NO_DEREF, UPDATE_REFS_DIE_ON_ERR);
977 if (!opts->quiet) {
978 if (old_branch_info->path &&
979 advice_enabled(ADVICE_DETACHED_HEAD) && !opts->force_detach)
980 detach_advice(new_branch_info->name);
981 describe_detached_head(_("HEAD is now at"), new_branch_info->commit);
983 } else if (new_branch_info->path) { /* Switch branches. */
984 if (create_symref("HEAD", new_branch_info->path, msg.buf) < 0)
985 die(_("unable to update HEAD"));
986 if (!opts->quiet) {
987 if (old_branch_info->path && !strcmp(new_branch_info->path, old_branch_info->path)) {
988 if (opts->new_branch_force)
989 fprintf(stderr, _("Reset branch '%s'\n"),
990 new_branch_info->name);
991 else
992 fprintf(stderr, _("Already on '%s'\n"),
993 new_branch_info->name);
994 } else if (opts->new_branch) {
995 if (opts->branch_exists)
996 fprintf(stderr, _("Switched to and reset branch '%s'\n"), new_branch_info->name);
997 else
998 fprintf(stderr, _("Switched to a new branch '%s'\n"), new_branch_info->name);
999 } else {
1000 fprintf(stderr, _("Switched to branch '%s'\n"),
1001 new_branch_info->name);
1004 if (old_branch_info->path && old_branch_info->name) {
1005 if (!ref_exists(old_branch_info->path) && reflog_exists(old_branch_info->path))
1006 delete_reflog(old_branch_info->path);
1009 remove_branch_state(the_repository, !opts->quiet);
1010 strbuf_release(&msg);
1011 if (!opts->quiet &&
1012 (new_branch_info->path || (!opts->force_detach && !strcmp(new_branch_info->name, "HEAD"))))
1013 report_tracking(new_branch_info);
1016 static int add_pending_uninteresting_ref(const char *refname,
1017 const struct object_id *oid,
1018 int flags UNUSED, void *cb_data)
1020 add_pending_oid(cb_data, refname, oid, UNINTERESTING);
1021 return 0;
1024 static void describe_one_orphan(struct strbuf *sb, struct commit *commit)
1026 strbuf_addstr(sb, " ");
1027 strbuf_add_unique_abbrev(sb, &commit->object.oid, DEFAULT_ABBREV);
1028 strbuf_addch(sb, ' ');
1029 if (!repo_parse_commit(the_repository, commit))
1030 pp_commit_easy(CMIT_FMT_ONELINE, commit, sb);
1031 strbuf_addch(sb, '\n');
1034 #define ORPHAN_CUTOFF 4
1035 static void suggest_reattach(struct commit *commit, struct rev_info *revs)
1037 struct commit *c, *last = NULL;
1038 struct strbuf sb = STRBUF_INIT;
1039 int lost = 0;
1040 while ((c = get_revision(revs)) != NULL) {
1041 if (lost < ORPHAN_CUTOFF)
1042 describe_one_orphan(&sb, c);
1043 last = c;
1044 lost++;
1046 if (ORPHAN_CUTOFF < lost) {
1047 int more = lost - ORPHAN_CUTOFF;
1048 if (more == 1)
1049 describe_one_orphan(&sb, last);
1050 else
1051 strbuf_addf(&sb, _(" ... and %d more.\n"), more);
1054 fprintf(stderr,
1056 /* The singular version */
1057 "Warning: you are leaving %d commit behind, "
1058 "not connected to\n"
1059 "any of your branches:\n\n"
1060 "%s\n",
1061 /* The plural version */
1062 "Warning: you are leaving %d commits behind, "
1063 "not connected to\n"
1064 "any of your branches:\n\n"
1065 "%s\n",
1066 /* Give ngettext() the count */
1067 lost),
1068 lost,
1069 sb.buf);
1070 strbuf_release(&sb);
1072 if (advice_enabled(ADVICE_DETACHED_HEAD))
1073 fprintf(stderr,
1075 /* The singular version */
1076 "If you want to keep it by creating a new branch, "
1077 "this may be a good time\nto do so with:\n\n"
1078 " git branch <new-branch-name> %s\n\n",
1079 /* The plural version */
1080 "If you want to keep them by creating a new branch, "
1081 "this may be a good time\nto do so with:\n\n"
1082 " git branch <new-branch-name> %s\n\n",
1083 /* Give ngettext() the count */
1084 lost),
1085 repo_find_unique_abbrev(the_repository, &commit->object.oid, DEFAULT_ABBREV));
1089 * We are about to leave commit that was at the tip of a detached
1090 * HEAD. If it is not reachable from any ref, this is the last chance
1091 * for the user to do so without resorting to reflog.
1093 static void orphaned_commit_warning(struct commit *old_commit, struct commit *new_commit)
1095 struct rev_info revs;
1096 struct object *object = &old_commit->object;
1098 repo_init_revisions(the_repository, &revs, NULL);
1099 setup_revisions(0, NULL, &revs, NULL);
1101 object->flags &= ~UNINTERESTING;
1102 add_pending_object(&revs, object, oid_to_hex(&object->oid));
1104 for_each_ref(add_pending_uninteresting_ref, &revs);
1105 if (new_commit)
1106 add_pending_oid(&revs, "HEAD",
1107 &new_commit->object.oid,
1108 UNINTERESTING);
1110 if (prepare_revision_walk(&revs))
1111 die(_("internal error in revision walk"));
1112 if (!(old_commit->object.flags & UNINTERESTING))
1113 suggest_reattach(old_commit, &revs);
1114 else
1115 describe_detached_head(_("Previous HEAD position was"), old_commit);
1117 /* Clean up objects used, as they will be reused. */
1118 repo_clear_commit_marks(the_repository, ALL_REV_FLAGS);
1119 release_revisions(&revs);
1122 static int switch_branches(const struct checkout_opts *opts,
1123 struct branch_info *new_branch_info)
1125 int ret = 0;
1126 struct branch_info old_branch_info = { 0 };
1127 struct object_id rev;
1128 int flag, writeout_error = 0;
1129 int do_merge = 1;
1131 trace2_cmd_mode("branch");
1133 memset(&old_branch_info, 0, sizeof(old_branch_info));
1134 old_branch_info.path = resolve_refdup("HEAD", 0, &rev, &flag);
1135 if (old_branch_info.path)
1136 old_branch_info.commit = lookup_commit_reference_gently(the_repository, &rev, 1);
1137 if (!(flag & REF_ISSYMREF))
1138 FREE_AND_NULL(old_branch_info.path);
1140 if (old_branch_info.path) {
1141 const char *const prefix = "refs/heads/";
1142 const char *p;
1143 if (skip_prefix(old_branch_info.path, prefix, &p))
1144 old_branch_info.name = xstrdup(p);
1147 if (opts->new_orphan_branch && opts->orphan_from_empty_tree) {
1148 if (new_branch_info->name)
1149 BUG("'switch --orphan' should never accept a commit as starting point");
1150 new_branch_info->commit = NULL;
1151 new_branch_info->name = xstrdup("(empty)");
1152 do_merge = 1;
1155 if (!new_branch_info->name) {
1156 new_branch_info->name = xstrdup("HEAD");
1157 new_branch_info->commit = old_branch_info.commit;
1158 if (!new_branch_info->commit)
1159 die(_("You are on a branch yet to be born"));
1160 parse_commit_or_die(new_branch_info->commit);
1162 if (opts->only_merge_on_switching_branches)
1163 do_merge = 0;
1166 if (do_merge) {
1167 ret = merge_working_tree(opts, &old_branch_info, new_branch_info, &writeout_error);
1168 if (ret) {
1169 branch_info_release(&old_branch_info);
1170 return ret;
1174 if (!opts->quiet && !old_branch_info.path && old_branch_info.commit && new_branch_info->commit != old_branch_info.commit)
1175 orphaned_commit_warning(old_branch_info.commit, new_branch_info->commit);
1177 update_refs_for_switch(opts, &old_branch_info, new_branch_info);
1179 ret = post_checkout_hook(old_branch_info.commit, new_branch_info->commit, 1);
1180 branch_info_release(&old_branch_info);
1182 return ret || writeout_error;
1185 static int git_checkout_config(const char *var, const char *value, void *cb)
1187 struct checkout_opts *opts = cb;
1189 if (!strcmp(var, "diff.ignoresubmodules")) {
1190 handle_ignore_submodules_arg(&opts->diff_options, value);
1191 return 0;
1193 if (!strcmp(var, "checkout.guess")) {
1194 opts->dwim_new_local_branch = git_config_bool(var, value);
1195 return 0;
1198 if (starts_with(var, "submodule."))
1199 return git_default_submodule_config(var, value, NULL);
1201 return git_xmerge_config(var, value, NULL);
1204 static void setup_new_branch_info_and_source_tree(
1205 struct branch_info *new_branch_info,
1206 struct checkout_opts *opts,
1207 struct object_id *rev,
1208 const char *arg)
1210 struct tree **source_tree = &opts->source_tree;
1211 struct object_id branch_rev;
1213 new_branch_info->name = xstrdup(arg);
1214 setup_branch_path(new_branch_info);
1216 if (!check_refname_format(new_branch_info->path, 0) &&
1217 !read_ref(new_branch_info->path, &branch_rev))
1218 oidcpy(rev, &branch_rev);
1219 else
1220 /* not an existing branch */
1221 FREE_AND_NULL(new_branch_info->path);
1223 new_branch_info->commit = lookup_commit_reference_gently(the_repository, rev, 1);
1224 if (!new_branch_info->commit) {
1225 /* not a commit */
1226 *source_tree = parse_tree_indirect(rev);
1227 } else {
1228 parse_commit_or_die(new_branch_info->commit);
1229 *source_tree = repo_get_commit_tree(the_repository,
1230 new_branch_info->commit);
1234 static const char *parse_remote_branch(const char *arg,
1235 struct object_id *rev,
1236 int could_be_checkout_paths)
1238 int num_matches = 0;
1239 const char *remote = unique_tracking_name(arg, rev, &num_matches);
1241 if (remote && could_be_checkout_paths) {
1242 die(_("'%s' could be both a local file and a tracking branch.\n"
1243 "Please use -- (and optionally --no-guess) to disambiguate"),
1244 arg);
1247 if (!remote && num_matches > 1) {
1248 if (advice_enabled(ADVICE_CHECKOUT_AMBIGUOUS_REMOTE_BRANCH_NAME)) {
1249 advise(_("If you meant to check out a remote tracking branch on, e.g. 'origin',\n"
1250 "you can do so by fully qualifying the name with the --track option:\n"
1251 "\n"
1252 " git checkout --track origin/<name>\n"
1253 "\n"
1254 "If you'd like to always have checkouts of an ambiguous <name> prefer\n"
1255 "one remote, e.g. the 'origin' remote, consider setting\n"
1256 "checkout.defaultRemote=origin in your config."));
1259 die(_("'%s' matched multiple (%d) remote tracking branches"),
1260 arg, num_matches);
1263 return remote;
1266 static int parse_branchname_arg(int argc, const char **argv,
1267 int dwim_new_local_branch_ok,
1268 struct branch_info *new_branch_info,
1269 struct checkout_opts *opts,
1270 struct object_id *rev)
1272 const char **new_branch = &opts->new_branch;
1273 int argcount = 0;
1274 const char *arg;
1275 int dash_dash_pos;
1276 int has_dash_dash = 0;
1277 int i;
1280 * case 1: git checkout <ref> -- [<paths>]
1282 * <ref> must be a valid tree, everything after the '--' must be
1283 * a path.
1285 * case 2: git checkout -- [<paths>]
1287 * everything after the '--' must be paths.
1289 * case 3: git checkout <something> [--]
1291 * (a) If <something> is a commit, that is to
1292 * switch to the branch or detach HEAD at it. As a special case,
1293 * if <something> is A...B (missing A or B means HEAD but you can
1294 * omit at most one side), and if there is a unique merge base
1295 * between A and B, A...B names that merge base.
1297 * (b) If <something> is _not_ a commit, either "--" is present
1298 * or <something> is not a path, no -t or -b was given,
1299 * and there is a tracking branch whose name is <something>
1300 * in one and only one remote (or if the branch exists on the
1301 * remote named in checkout.defaultRemote), then this is a
1302 * short-hand to fork local <something> from that
1303 * remote-tracking branch.
1305 * (c) Otherwise, if "--" is present, treat it like case (1).
1307 * (d) Otherwise :
1308 * - if it's a reference, treat it like case (1)
1309 * - else if it's a path, treat it like case (2)
1310 * - else: fail.
1312 * case 4: git checkout <something> <paths>
1314 * The first argument must not be ambiguous.
1315 * - If it's *only* a reference, treat it like case (1).
1316 * - If it's only a path, treat it like case (2).
1317 * - else: fail.
1320 if (!argc)
1321 return 0;
1323 if (!opts->accept_pathspec) {
1324 if (argc > 1)
1325 die(_("only one reference expected"));
1326 has_dash_dash = 1; /* helps disambiguate */
1329 arg = argv[0];
1330 dash_dash_pos = -1;
1331 for (i = 0; i < argc; i++) {
1332 if (opts->accept_pathspec && !strcmp(argv[i], "--")) {
1333 dash_dash_pos = i;
1334 break;
1337 if (dash_dash_pos == 0)
1338 return 1; /* case (2) */
1339 else if (dash_dash_pos == 1)
1340 has_dash_dash = 1; /* case (3) or (1) */
1341 else if (dash_dash_pos >= 2)
1342 die(_("only one reference expected, %d given."), dash_dash_pos);
1343 opts->count_checkout_paths = !opts->quiet && !has_dash_dash;
1345 if (!strcmp(arg, "-"))
1346 arg = "@{-1}";
1348 if (repo_get_oid_mb(the_repository, arg, rev)) {
1350 * Either case (3) or (4), with <something> not being
1351 * a commit, or an attempt to use case (1) with an
1352 * invalid ref.
1354 * It's likely an error, but we need to find out if
1355 * we should auto-create the branch, case (3).(b).
1357 int recover_with_dwim = dwim_new_local_branch_ok;
1359 int could_be_checkout_paths = !has_dash_dash &&
1360 check_filename(opts->prefix, arg);
1362 if (!has_dash_dash && !no_wildcard(arg))
1363 recover_with_dwim = 0;
1366 * Accept "git checkout foo", "git checkout foo --"
1367 * and "git switch foo" as candidates for dwim.
1369 if (!(argc == 1 && !has_dash_dash) &&
1370 !(argc == 2 && has_dash_dash) &&
1371 opts->accept_pathspec)
1372 recover_with_dwim = 0;
1374 if (recover_with_dwim) {
1375 const char *remote = parse_remote_branch(arg, rev,
1376 could_be_checkout_paths);
1377 if (remote) {
1378 *new_branch = arg;
1379 arg = remote;
1380 /* DWIMmed to create local branch, case (3).(b) */
1381 } else {
1382 recover_with_dwim = 0;
1386 if (!recover_with_dwim) {
1387 if (has_dash_dash)
1388 die(_("invalid reference: %s"), arg);
1389 return argcount;
1393 /* we can't end up being in (2) anymore, eat the argument */
1394 argcount++;
1395 argv++;
1396 argc--;
1398 setup_new_branch_info_and_source_tree(new_branch_info, opts, rev, arg);
1400 if (!opts->source_tree) /* case (1): want a tree */
1401 die(_("reference is not a tree: %s"), arg);
1403 if (!has_dash_dash) { /* case (3).(d) -> (1) */
1405 * Do not complain the most common case
1406 * git checkout branch
1407 * even if there happen to be a file called 'branch';
1408 * it would be extremely annoying.
1410 if (argc)
1411 verify_non_filename(opts->prefix, arg);
1412 } else if (opts->accept_pathspec) {
1413 argcount++;
1414 argv++;
1415 argc--;
1418 return argcount;
1421 static int switch_unborn_to_new_branch(const struct checkout_opts *opts)
1423 int status;
1424 struct strbuf branch_ref = STRBUF_INIT;
1426 trace2_cmd_mode("unborn");
1428 if (!opts->new_branch)
1429 die(_("You are on a branch yet to be born"));
1430 strbuf_addf(&branch_ref, "refs/heads/%s", opts->new_branch);
1431 status = create_symref("HEAD", branch_ref.buf, "checkout -b");
1432 strbuf_release(&branch_ref);
1433 if (!opts->quiet)
1434 fprintf(stderr, _("Switched to a new branch '%s'\n"),
1435 opts->new_branch);
1436 return status;
1439 static void die_expecting_a_branch(const struct branch_info *branch_info)
1441 struct object_id oid;
1442 char *to_free;
1443 int code;
1445 if (repo_dwim_ref(the_repository, branch_info->name,
1446 strlen(branch_info->name), &oid, &to_free, 0) == 1) {
1447 const char *ref = to_free;
1449 if (skip_prefix(ref, "refs/tags/", &ref))
1450 code = die_message(_("a branch is expected, got tag '%s'"), ref);
1451 else if (skip_prefix(ref, "refs/remotes/", &ref))
1452 code = die_message(_("a branch is expected, got remote branch '%s'"), ref);
1453 else
1454 code = die_message(_("a branch is expected, got '%s'"), ref);
1456 else if (branch_info->commit)
1457 code = die_message(_("a branch is expected, got commit '%s'"), branch_info->name);
1458 else
1460 * This case should never happen because we already die() on
1461 * non-commit, but just in case.
1463 code = die_message(_("a branch is expected, got '%s'"), branch_info->name);
1465 if (advice_enabled(ADVICE_SUGGEST_DETACHING_HEAD))
1466 advise(_("If you want to detach HEAD at the commit, try again with the --detach option."));
1468 exit(code);
1471 static void die_if_some_operation_in_progress(void)
1473 struct wt_status_state state;
1475 memset(&state, 0, sizeof(state));
1476 wt_status_get_state(the_repository, &state, 0);
1478 if (state.merge_in_progress)
1479 die(_("cannot switch branch while merging\n"
1480 "Consider \"git merge --quit\" "
1481 "or \"git worktree add\"."));
1482 if (state.am_in_progress)
1483 die(_("cannot switch branch in the middle of an am session\n"
1484 "Consider \"git am --quit\" "
1485 "or \"git worktree add\"."));
1486 if (state.rebase_interactive_in_progress || state.rebase_in_progress)
1487 die(_("cannot switch branch while rebasing\n"
1488 "Consider \"git rebase --quit\" "
1489 "or \"git worktree add\"."));
1490 if (state.cherry_pick_in_progress)
1491 die(_("cannot switch branch while cherry-picking\n"
1492 "Consider \"git cherry-pick --quit\" "
1493 "or \"git worktree add\"."));
1494 if (state.revert_in_progress)
1495 die(_("cannot switch branch while reverting\n"
1496 "Consider \"git revert --quit\" "
1497 "or \"git worktree add\"."));
1498 if (state.bisect_in_progress)
1499 warning(_("you are switching branch while bisecting"));
1501 wt_status_state_free_buffers(&state);
1504 static int checkout_branch(struct checkout_opts *opts,
1505 struct branch_info *new_branch_info)
1507 if (opts->pathspec.nr)
1508 die(_("paths cannot be used with switching branches"));
1510 if (opts->patch_mode)
1511 die(_("'%s' cannot be used with switching branches"),
1512 "--patch");
1514 if (opts->overlay_mode != -1)
1515 die(_("'%s' cannot be used with switching branches"),
1516 "--[no]-overlay");
1518 if (opts->writeout_stage)
1519 die(_("'%s' cannot be used with switching branches"),
1520 "--ours/--theirs");
1522 if (opts->force && opts->merge)
1523 die(_("'%s' cannot be used with '%s'"), "-f", "-m");
1525 if (opts->discard_changes && opts->merge)
1526 die(_("'%s' cannot be used with '%s'"), "--discard-changes", "--merge");
1528 if (opts->force_detach && opts->new_branch)
1529 die(_("'%s' cannot be used with '%s'"),
1530 "--detach", "-b/-B/--orphan");
1532 if (opts->new_orphan_branch) {
1533 if (opts->track != BRANCH_TRACK_UNSPECIFIED)
1534 die(_("'%s' cannot be used with '%s'"), "--orphan", "-t");
1535 if (opts->orphan_from_empty_tree && new_branch_info->name)
1536 die(_("'%s' cannot take <start-point>"), "--orphan");
1537 } else if (opts->force_detach) {
1538 if (opts->track != BRANCH_TRACK_UNSPECIFIED)
1539 die(_("'%s' cannot be used with '%s'"), "--detach", "-t");
1540 } else if (opts->track == BRANCH_TRACK_UNSPECIFIED)
1541 opts->track = git_branch_track;
1543 if (new_branch_info->name && !new_branch_info->commit)
1544 die(_("Cannot switch branch to a non-commit '%s'"),
1545 new_branch_info->name);
1547 if (!opts->switch_branch_doing_nothing_is_ok &&
1548 !new_branch_info->name &&
1549 !opts->new_branch &&
1550 !opts->force_detach)
1551 die(_("missing branch or commit argument"));
1553 if (!opts->implicit_detach &&
1554 !opts->force_detach &&
1555 !opts->new_branch &&
1556 !opts->new_branch_force &&
1557 new_branch_info->name &&
1558 !new_branch_info->path)
1559 die_expecting_a_branch(new_branch_info);
1561 if (!opts->can_switch_when_in_progress)
1562 die_if_some_operation_in_progress();
1564 if (new_branch_info->path && !opts->force_detach && !opts->new_branch &&
1565 !opts->ignore_other_worktrees) {
1566 int flag;
1567 char *head_ref = resolve_refdup("HEAD", 0, NULL, &flag);
1568 if (head_ref &&
1569 (!(flag & REF_ISSYMREF) || strcmp(head_ref, new_branch_info->path)))
1570 die_if_checked_out(new_branch_info->path, 1);
1571 free(head_ref);
1574 if (!new_branch_info->commit && opts->new_branch) {
1575 struct object_id rev;
1576 int flag;
1578 if (!read_ref_full("HEAD", 0, &rev, &flag) &&
1579 (flag & REF_ISSYMREF) && is_null_oid(&rev))
1580 return switch_unborn_to_new_branch(opts);
1582 return switch_branches(opts, new_branch_info);
1585 static struct option *add_common_options(struct checkout_opts *opts,
1586 struct option *prevopts)
1588 struct option options[] = {
1589 OPT__QUIET(&opts->quiet, N_("suppress progress reporting")),
1590 OPT_CALLBACK_F(0, "recurse-submodules", NULL,
1591 "checkout", "control recursive updating of submodules",
1592 PARSE_OPT_OPTARG, option_parse_recurse_submodules_worktree_updater),
1593 OPT_BOOL(0, "progress", &opts->show_progress, N_("force progress reporting")),
1594 OPT_BOOL('m', "merge", &opts->merge, N_("perform a 3-way merge with the new branch")),
1595 OPT_STRING(0, "conflict", &opts->conflict_style, N_("style"),
1596 N_("conflict style (merge, diff3, or zdiff3)")),
1597 OPT_END()
1599 struct option *newopts = parse_options_concat(prevopts, options);
1600 free(prevopts);
1601 return newopts;
1604 static struct option *add_common_switch_branch_options(
1605 struct checkout_opts *opts, struct option *prevopts)
1607 struct option options[] = {
1608 OPT_BOOL('d', "detach", &opts->force_detach, N_("detach HEAD at named commit")),
1609 OPT_CALLBACK_F('t', "track", &opts->track, "(direct|inherit)",
1610 N_("set branch tracking configuration"),
1611 PARSE_OPT_OPTARG,
1612 parse_opt_tracking_mode),
1613 OPT__FORCE(&opts->force, N_("force checkout (throw away local modifications)"),
1614 PARSE_OPT_NOCOMPLETE),
1615 OPT_STRING(0, "orphan", &opts->new_orphan_branch, N_("new-branch"), N_("new unparented branch")),
1616 OPT_BOOL_F(0, "overwrite-ignore", &opts->overwrite_ignore,
1617 N_("update ignored files (default)"),
1618 PARSE_OPT_NOCOMPLETE),
1619 OPT_BOOL(0, "ignore-other-worktrees", &opts->ignore_other_worktrees,
1620 N_("do not check if another worktree is holding the given ref")),
1621 OPT_END()
1623 struct option *newopts = parse_options_concat(prevopts, options);
1624 free(prevopts);
1625 return newopts;
1628 static struct option *add_checkout_path_options(struct checkout_opts *opts,
1629 struct option *prevopts)
1631 struct option options[] = {
1632 OPT_SET_INT_F('2', "ours", &opts->writeout_stage,
1633 N_("checkout our version for unmerged files"),
1634 2, PARSE_OPT_NONEG),
1635 OPT_SET_INT_F('3', "theirs", &opts->writeout_stage,
1636 N_("checkout their version for unmerged files"),
1637 3, PARSE_OPT_NONEG),
1638 OPT_BOOL('p', "patch", &opts->patch_mode, N_("select hunks interactively")),
1639 OPT_BOOL(0, "ignore-skip-worktree-bits", &opts->ignore_skipworktree,
1640 N_("do not limit pathspecs to sparse entries only")),
1641 OPT_PATHSPEC_FROM_FILE(&opts->pathspec_from_file),
1642 OPT_PATHSPEC_FILE_NUL(&opts->pathspec_file_nul),
1643 OPT_END()
1645 struct option *newopts = parse_options_concat(prevopts, options);
1646 free(prevopts);
1647 return newopts;
1650 /* create-branch option (either b or c) */
1651 static char cb_option = 'b';
1653 static int checkout_main(int argc, const char **argv, const char *prefix,
1654 struct checkout_opts *opts, struct option *options,
1655 const char * const usagestr[],
1656 struct branch_info *new_branch_info)
1658 int parseopt_flags = 0;
1660 opts->overwrite_ignore = 1;
1661 opts->prefix = prefix;
1662 opts->show_progress = -1;
1664 git_config(git_checkout_config, opts);
1665 if (the_repository->gitdir) {
1666 prepare_repo_settings(the_repository);
1667 the_repository->settings.command_requires_full_index = 0;
1670 opts->track = BRANCH_TRACK_UNSPECIFIED;
1672 if (!opts->accept_pathspec && !opts->accept_ref)
1673 BUG("make up your mind, you need to take _something_");
1674 if (opts->accept_pathspec && opts->accept_ref)
1675 parseopt_flags = PARSE_OPT_KEEP_DASHDASH;
1677 argc = parse_options(argc, argv, prefix, options,
1678 usagestr, parseopt_flags);
1680 if (opts->show_progress < 0) {
1681 if (opts->quiet)
1682 opts->show_progress = 0;
1683 else
1684 opts->show_progress = isatty(2);
1687 if (opts->conflict_style) {
1688 opts->merge = 1; /* implied */
1689 git_xmerge_config("merge.conflictstyle", opts->conflict_style, NULL);
1691 if (opts->force) {
1692 opts->discard_changes = 1;
1693 opts->ignore_unmerged_opt = "--force";
1694 opts->ignore_unmerged = 1;
1697 if ((!!opts->new_branch + !!opts->new_branch_force + !!opts->new_orphan_branch) > 1)
1698 die(_("options '-%c', '-%c', and '%s' cannot be used together"),
1699 cb_option, toupper(cb_option), "--orphan");
1701 if (opts->overlay_mode == 1 && opts->patch_mode)
1702 die(_("options '%s' and '%s' cannot be used together"), "-p", "--overlay");
1704 if (opts->checkout_index >= 0 || opts->checkout_worktree >= 0) {
1705 if (opts->checkout_index < 0)
1706 opts->checkout_index = 0;
1707 if (opts->checkout_worktree < 0)
1708 opts->checkout_worktree = 0;
1709 } else {
1710 if (opts->checkout_index < 0)
1711 opts->checkout_index = -opts->checkout_index - 1;
1712 if (opts->checkout_worktree < 0)
1713 opts->checkout_worktree = -opts->checkout_worktree - 1;
1715 if (opts->checkout_index < 0 || opts->checkout_worktree < 0)
1716 BUG("these flags should be non-negative by now");
1718 * convenient shortcut: "git restore --staged [--worktree]" equals
1719 * "git restore --staged [--worktree] --source HEAD"
1721 if (!opts->from_treeish && opts->checkout_index)
1722 opts->from_treeish = "HEAD";
1725 * From here on, new_branch will contain the branch to be checked out,
1726 * and new_branch_force and new_orphan_branch will tell us which one of
1727 * -b/-B/-c/-C/--orphan is being used.
1729 if (opts->new_branch_force)
1730 opts->new_branch = opts->new_branch_force;
1732 if (opts->new_orphan_branch)
1733 opts->new_branch = opts->new_orphan_branch;
1735 /* --track without -c/-C/-b/-B/--orphan should DWIM */
1736 if (opts->track != BRANCH_TRACK_UNSPECIFIED && !opts->new_branch) {
1737 const char *argv0 = argv[0];
1738 if (!argc || !strcmp(argv0, "--"))
1739 die(_("--track needs a branch name"));
1740 skip_prefix(argv0, "refs/", &argv0);
1741 skip_prefix(argv0, "remotes/", &argv0);
1742 argv0 = strchr(argv0, '/');
1743 if (!argv0 || !argv0[1])
1744 die(_("missing branch name; try -%c"), cb_option);
1745 opts->new_branch = argv0 + 1;
1749 * Extract branch name from command line arguments, so
1750 * all that is left is pathspecs.
1752 * Handle
1754 * 1) git checkout <tree> -- [<paths>]
1755 * 2) git checkout -- [<paths>]
1756 * 3) git checkout <something> [<paths>]
1758 * including "last branch" syntax and DWIM-ery for names of
1759 * remote branches, erroring out for invalid or ambiguous cases.
1761 if (argc && opts->accept_ref) {
1762 struct object_id rev;
1763 int dwim_ok =
1764 !opts->patch_mode &&
1765 opts->dwim_new_local_branch &&
1766 opts->track == BRANCH_TRACK_UNSPECIFIED &&
1767 !opts->new_branch;
1768 int n = parse_branchname_arg(argc, argv, dwim_ok,
1769 new_branch_info, opts, &rev);
1770 argv += n;
1771 argc -= n;
1772 } else if (!opts->accept_ref && opts->from_treeish) {
1773 struct object_id rev;
1775 if (repo_get_oid_mb(the_repository, opts->from_treeish, &rev))
1776 die(_("could not resolve %s"), opts->from_treeish);
1778 setup_new_branch_info_and_source_tree(new_branch_info,
1779 opts, &rev,
1780 opts->from_treeish);
1782 if (!opts->source_tree)
1783 die(_("reference is not a tree: %s"), opts->from_treeish);
1786 if (argc) {
1787 parse_pathspec(&opts->pathspec, 0,
1788 opts->patch_mode ? PATHSPEC_PREFIX_ORIGIN : 0,
1789 prefix, argv);
1791 if (!opts->pathspec.nr)
1792 die(_("invalid path specification"));
1795 * Try to give more helpful suggestion.
1796 * new_branch && argc > 1 will be caught later.
1798 if (opts->new_branch && argc == 1 && !new_branch_info->commit)
1799 die(_("'%s' is not a commit and a branch '%s' cannot be created from it"),
1800 argv[0], opts->new_branch);
1802 if (opts->force_detach)
1803 die(_("git checkout: --detach does not take a path argument '%s'"),
1804 argv[0]);
1807 if (opts->pathspec_from_file) {
1808 if (opts->pathspec.nr)
1809 die(_("'%s' and pathspec arguments cannot be used together"), "--pathspec-from-file");
1811 if (opts->force_detach)
1812 die(_("options '%s' and '%s' cannot be used together"), "--pathspec-from-file", "--detach");
1814 if (opts->patch_mode)
1815 die(_("options '%s' and '%s' cannot be used together"), "--pathspec-from-file", "--patch");
1817 parse_pathspec_file(&opts->pathspec, 0,
1819 prefix, opts->pathspec_from_file, opts->pathspec_file_nul);
1820 } else if (opts->pathspec_file_nul) {
1821 die(_("the option '%s' requires '%s'"), "--pathspec-file-nul", "--pathspec-from-file");
1824 opts->pathspec.recursive = 1;
1826 if (opts->pathspec.nr) {
1827 if (1 < !!opts->writeout_stage + !!opts->force + !!opts->merge)
1828 die(_("git checkout: --ours/--theirs, --force and --merge are incompatible when\n"
1829 "checking out of the index."));
1830 } else {
1831 if (opts->accept_pathspec && !opts->empty_pathspec_ok &&
1832 !opts->patch_mode) /* patch mode is special */
1833 die(_("you must specify path(s) to restore"));
1836 if (opts->new_branch) {
1837 struct strbuf buf = STRBUF_INIT;
1839 if (opts->new_branch_force)
1840 opts->branch_exists = validate_branchname(opts->new_branch, &buf);
1841 else
1842 opts->branch_exists =
1843 validate_new_branchname(opts->new_branch, &buf, 0);
1844 strbuf_release(&buf);
1847 if (opts->patch_mode || opts->pathspec.nr)
1848 return checkout_paths(opts, new_branch_info);
1849 else
1850 return checkout_branch(opts, new_branch_info);
1853 int cmd_checkout(int argc, const char **argv, const char *prefix)
1855 struct checkout_opts opts;
1856 struct option *options;
1857 struct option checkout_options[] = {
1858 OPT_STRING('b', NULL, &opts.new_branch, N_("branch"),
1859 N_("create and checkout a new branch")),
1860 OPT_STRING('B', NULL, &opts.new_branch_force, N_("branch"),
1861 N_("create/reset and checkout a branch")),
1862 OPT_BOOL('l', NULL, &opts.new_branch_log, N_("create reflog for new branch")),
1863 OPT_BOOL(0, "guess", &opts.dwim_new_local_branch,
1864 N_("second guess 'git checkout <no-such-branch>' (default)")),
1865 OPT_BOOL(0, "overlay", &opts.overlay_mode, N_("use overlay mode (default)")),
1866 OPT_END()
1868 int ret;
1869 struct branch_info new_branch_info = { 0 };
1871 memset(&opts, 0, sizeof(opts));
1872 opts.dwim_new_local_branch = 1;
1873 opts.switch_branch_doing_nothing_is_ok = 1;
1874 opts.only_merge_on_switching_branches = 0;
1875 opts.accept_ref = 1;
1876 opts.accept_pathspec = 1;
1877 opts.implicit_detach = 1;
1878 opts.can_switch_when_in_progress = 1;
1879 opts.orphan_from_empty_tree = 0;
1880 opts.empty_pathspec_ok = 1;
1881 opts.overlay_mode = -1;
1882 opts.checkout_index = -2; /* default on */
1883 opts.checkout_worktree = -2; /* default on */
1885 if (argc == 3 && !strcmp(argv[1], "-b")) {
1887 * User ran 'git checkout -b <branch>' and expects
1888 * the same behavior as 'git switch -c <branch>'.
1890 opts.switch_branch_doing_nothing_is_ok = 0;
1891 opts.only_merge_on_switching_branches = 1;
1894 options = parse_options_dup(checkout_options);
1895 options = add_common_options(&opts, options);
1896 options = add_common_switch_branch_options(&opts, options);
1897 options = add_checkout_path_options(&opts, options);
1899 ret = checkout_main(argc, argv, prefix, &opts,
1900 options, checkout_usage, &new_branch_info);
1901 branch_info_release(&new_branch_info);
1902 clear_pathspec(&opts.pathspec);
1903 free(opts.pathspec_from_file);
1904 FREE_AND_NULL(options);
1905 return ret;
1908 int cmd_switch(int argc, const char **argv, const char *prefix)
1910 struct checkout_opts opts;
1911 struct option *options = NULL;
1912 struct option switch_options[] = {
1913 OPT_STRING('c', "create", &opts.new_branch, N_("branch"),
1914 N_("create and switch to a new branch")),
1915 OPT_STRING('C', "force-create", &opts.new_branch_force, N_("branch"),
1916 N_("create/reset and switch to a branch")),
1917 OPT_BOOL(0, "guess", &opts.dwim_new_local_branch,
1918 N_("second guess 'git switch <no-such-branch>'")),
1919 OPT_BOOL(0, "discard-changes", &opts.discard_changes,
1920 N_("throw away local modifications")),
1921 OPT_END()
1923 int ret;
1924 struct branch_info new_branch_info = { 0 };
1926 memset(&opts, 0, sizeof(opts));
1927 opts.dwim_new_local_branch = 1;
1928 opts.accept_ref = 1;
1929 opts.accept_pathspec = 0;
1930 opts.switch_branch_doing_nothing_is_ok = 0;
1931 opts.only_merge_on_switching_branches = 1;
1932 opts.implicit_detach = 0;
1933 opts.can_switch_when_in_progress = 0;
1934 opts.orphan_from_empty_tree = 1;
1935 opts.overlay_mode = -1;
1937 options = parse_options_dup(switch_options);
1938 options = add_common_options(&opts, options);
1939 options = add_common_switch_branch_options(&opts, options);
1941 cb_option = 'c';
1943 ret = checkout_main(argc, argv, prefix, &opts,
1944 options, switch_branch_usage, &new_branch_info);
1945 branch_info_release(&new_branch_info);
1946 FREE_AND_NULL(options);
1947 return ret;
1950 int cmd_restore(int argc, const char **argv, const char *prefix)
1952 struct checkout_opts opts;
1953 struct option *options;
1954 struct option restore_options[] = {
1955 OPT_STRING('s', "source", &opts.from_treeish, "<tree-ish>",
1956 N_("which tree-ish to checkout from")),
1957 OPT_BOOL('S', "staged", &opts.checkout_index,
1958 N_("restore the index")),
1959 OPT_BOOL('W', "worktree", &opts.checkout_worktree,
1960 N_("restore the working tree (default)")),
1961 OPT_BOOL(0, "ignore-unmerged", &opts.ignore_unmerged,
1962 N_("ignore unmerged entries")),
1963 OPT_BOOL(0, "overlay", &opts.overlay_mode, N_("use overlay mode")),
1964 OPT_END()
1966 int ret;
1967 struct branch_info new_branch_info = { 0 };
1969 memset(&opts, 0, sizeof(opts));
1970 opts.accept_ref = 0;
1971 opts.accept_pathspec = 1;
1972 opts.empty_pathspec_ok = 0;
1973 opts.overlay_mode = 0;
1974 opts.checkout_index = -1; /* default off */
1975 opts.checkout_worktree = -2; /* default on */
1976 opts.ignore_unmerged_opt = "--ignore-unmerged";
1978 options = parse_options_dup(restore_options);
1979 options = add_common_options(&opts, options);
1980 options = add_checkout_path_options(&opts, options);
1982 ret = checkout_main(argc, argv, prefix, &opts,
1983 options, restore_usage, &new_branch_info);
1984 branch_info_release(&new_branch_info);
1985 FREE_AND_NULL(options);
1986 return ret;