Always check `parse_tree*()`'s return value
[git.git] / builtin / checkout.c
blob9ab0901d6291f49a34bdb0c071a2c1c049fc4bf8
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 "merge-ll.h"
17 #include "lockfile.h"
18 #include "mem-pool.h"
19 #include "merge-recursive.h"
20 #include "object-name.h"
21 #include "object-store-ll.h"
22 #include "parse-options.h"
23 #include "path.h"
24 #include "preload-index.h"
25 #include "read-cache.h"
26 #include "refs.h"
27 #include "remote.h"
28 #include "resolve-undo.h"
29 #include "revision.h"
30 #include "run-command.h"
31 #include "setup.h"
32 #include "submodule.h"
33 #include "submodule-config.h"
34 #include "symlinks.h"
35 #include "trace2.h"
36 #include "tree.h"
37 #include "tree-walk.h"
38 #include "unpack-trees.h"
39 #include "wt-status.h"
40 #include "xdiff-interface.h"
41 #include "entry.h"
42 #include "parallel-checkout.h"
43 #include "add-interactive.h"
45 static const char * const checkout_usage[] = {
46 N_("git checkout [<options>] <branch>"),
47 N_("git checkout [<options>] [<branch>] -- <file>..."),
48 NULL,
51 static const char * const switch_branch_usage[] = {
52 N_("git switch [<options>] [<branch>]"),
53 NULL,
56 static const char * const restore_usage[] = {
57 N_("git restore [<options>] [--source=<branch>] <file>..."),
58 NULL,
61 struct checkout_opts {
62 int patch_mode;
63 int quiet;
64 int merge;
65 int force;
66 int force_detach;
67 int implicit_detach;
68 int writeout_stage;
69 int overwrite_ignore;
70 int ignore_skipworktree;
71 int ignore_other_worktrees;
72 int show_progress;
73 int count_checkout_paths;
74 int overlay_mode;
75 int dwim_new_local_branch;
76 int discard_changes;
77 int accept_ref;
78 int accept_pathspec;
79 int switch_branch_doing_nothing_is_ok;
80 int only_merge_on_switching_branches;
81 int can_switch_when_in_progress;
82 int orphan_from_empty_tree;
83 int empty_pathspec_ok;
84 int checkout_index;
85 int checkout_worktree;
86 const char *ignore_unmerged_opt;
87 int ignore_unmerged;
88 int pathspec_file_nul;
89 char *pathspec_from_file;
91 const char *new_branch;
92 const char *new_branch_force;
93 const char *new_orphan_branch;
94 int new_branch_log;
95 enum branch_track track;
96 struct diff_options diff_options;
97 char *conflict_style;
99 int branch_exists;
100 const char *prefix;
101 struct pathspec pathspec;
102 const char *from_treeish;
103 struct tree *source_tree;
106 struct branch_info {
107 char *name; /* The short name used */
108 char *path; /* The full name of a real branch */
109 struct commit *commit; /* The named commit */
110 char *refname; /* The full name of the ref being checked out. */
111 struct object_id oid; /* The object ID of the commit being checked out. */
113 * if not null the branch is detached because it's already
114 * checked out in this checkout
116 char *checkout;
119 static void branch_info_release(struct branch_info *info)
121 free(info->name);
122 free(info->path);
123 free(info->refname);
124 free(info->checkout);
127 static int post_checkout_hook(struct commit *old_commit, struct commit *new_commit,
128 int changed)
130 return run_hooks_l("post-checkout",
131 oid_to_hex(old_commit ? &old_commit->object.oid : null_oid()),
132 oid_to_hex(new_commit ? &new_commit->object.oid : null_oid()),
133 changed ? "1" : "0", NULL);
134 /* "new_commit" can be NULL when checking out from the index before
135 a commit exists. */
139 static int update_some(const struct object_id *oid, struct strbuf *base,
140 const char *pathname, unsigned mode, void *context UNUSED)
142 int len;
143 struct cache_entry *ce;
144 int pos;
146 if (S_ISDIR(mode))
147 return READ_TREE_RECURSIVE;
149 len = base->len + strlen(pathname);
150 ce = make_empty_cache_entry(&the_index, len);
151 oidcpy(&ce->oid, oid);
152 memcpy(ce->name, base->buf, base->len);
153 memcpy(ce->name + base->len, pathname, len - base->len);
154 ce->ce_flags = create_ce_flags(0) | CE_UPDATE;
155 ce->ce_namelen = len;
156 ce->ce_mode = create_ce_mode(mode);
159 * If the entry is the same as the current index, we can leave the old
160 * entry in place. Whether it is UPTODATE or not, checkout_entry will
161 * do the right thing.
163 pos = index_name_pos(&the_index, ce->name, ce->ce_namelen);
164 if (pos >= 0) {
165 struct cache_entry *old = the_index.cache[pos];
166 if (ce->ce_mode == old->ce_mode &&
167 !ce_intent_to_add(old) &&
168 oideq(&ce->oid, &old->oid)) {
169 old->ce_flags |= CE_UPDATE;
170 discard_cache_entry(ce);
171 return 0;
175 add_index_entry(&the_index, ce,
176 ADD_CACHE_OK_TO_ADD | ADD_CACHE_OK_TO_REPLACE);
177 return 0;
180 static int read_tree_some(struct tree *tree, const struct pathspec *pathspec)
182 read_tree(the_repository, tree,
183 pathspec, update_some, NULL);
185 /* update the index with the given tree's info
186 * for all args, expanding wildcards, and exit
187 * with any non-zero return code.
189 return 0;
192 static int skip_same_name(const struct cache_entry *ce, int pos)
194 while (++pos < the_index.cache_nr &&
195 !strcmp(the_index.cache[pos]->name, ce->name))
196 ; /* skip */
197 return pos;
200 static int check_stage(int stage, const struct cache_entry *ce, int pos,
201 int overlay_mode)
203 while (pos < the_index.cache_nr &&
204 !strcmp(the_index.cache[pos]->name, ce->name)) {
205 if (ce_stage(the_index.cache[pos]) == stage)
206 return 0;
207 pos++;
209 if (!overlay_mode)
210 return 0;
211 if (stage == 2)
212 return error(_("path '%s' does not have our version"), ce->name);
213 else
214 return error(_("path '%s' does not have their version"), ce->name);
217 static int check_stages(unsigned stages, const struct cache_entry *ce, int pos)
219 unsigned seen = 0;
220 const char *name = ce->name;
222 while (pos < the_index.cache_nr) {
223 ce = the_index.cache[pos];
224 if (strcmp(name, ce->name))
225 break;
226 seen |= (1 << ce_stage(ce));
227 pos++;
229 if ((stages & seen) != stages)
230 return error(_("path '%s' does not have all necessary versions"),
231 name);
232 return 0;
235 static int checkout_stage(int stage, const struct cache_entry *ce, int pos,
236 const struct checkout *state, int *nr_checkouts,
237 int overlay_mode)
239 while (pos < the_index.cache_nr &&
240 !strcmp(the_index.cache[pos]->name, ce->name)) {
241 if (ce_stage(the_index.cache[pos]) == stage)
242 return checkout_entry(the_index.cache[pos], state,
243 NULL, nr_checkouts);
244 pos++;
246 if (!overlay_mode) {
247 unlink_entry(ce, NULL);
248 return 0;
250 if (stage == 2)
251 return error(_("path '%s' does not have our version"), ce->name);
252 else
253 return error(_("path '%s' does not have their version"), ce->name);
256 static int checkout_merged(int pos, const struct checkout *state,
257 int *nr_checkouts, struct mem_pool *ce_mem_pool)
259 struct cache_entry *ce = the_index.cache[pos];
260 const char *path = ce->name;
261 mmfile_t ancestor, ours, theirs;
262 enum ll_merge_result merge_status;
263 int status;
264 struct object_id oid;
265 mmbuffer_t result_buf;
266 struct object_id threeway[3];
267 unsigned mode = 0;
268 struct ll_merge_options ll_opts;
269 int renormalize = 0;
271 memset(threeway, 0, sizeof(threeway));
272 while (pos < the_index.cache_nr) {
273 int stage;
274 stage = ce_stage(ce);
275 if (!stage || strcmp(path, ce->name))
276 break;
277 oidcpy(&threeway[stage - 1], &ce->oid);
278 if (stage == 2)
279 mode = create_ce_mode(ce->ce_mode);
280 pos++;
281 ce = the_index.cache[pos];
283 if (is_null_oid(&threeway[1]) || is_null_oid(&threeway[2]))
284 return error(_("path '%s' does not have necessary versions"), path);
286 read_mmblob(&ancestor, &threeway[0]);
287 read_mmblob(&ours, &threeway[1]);
288 read_mmblob(&theirs, &threeway[2]);
290 memset(&ll_opts, 0, sizeof(ll_opts));
291 git_config_get_bool("merge.renormalize", &renormalize);
292 ll_opts.renormalize = renormalize;
293 merge_status = ll_merge(&result_buf, path, &ancestor, "base",
294 &ours, "ours", &theirs, "theirs",
295 state->istate, &ll_opts);
296 free(ancestor.ptr);
297 free(ours.ptr);
298 free(theirs.ptr);
299 if (merge_status == LL_MERGE_BINARY_CONFLICT)
300 warning("Cannot merge binary files: %s (%s vs. %s)",
301 path, "ours", "theirs");
302 if (merge_status < 0 || !result_buf.ptr) {
303 free(result_buf.ptr);
304 return error(_("path '%s': cannot merge"), path);
308 * NEEDSWORK:
309 * There is absolutely no reason to write this as a blob object
310 * and create a phony cache entry. This hack is primarily to get
311 * to the write_entry() machinery that massages the contents to
312 * work-tree format and writes out which only allows it for a
313 * cache entry. The code in write_entry() needs to be refactored
314 * to allow us to feed a <buffer, size, mode> instead of a cache
315 * entry. Such a refactoring would help merge_recursive as well
316 * (it also writes the merge result to the object database even
317 * when it may contain conflicts).
319 if (write_object_file(result_buf.ptr, result_buf.size, OBJ_BLOB, &oid))
320 die(_("Unable to add merge result for '%s'"), path);
321 free(result_buf.ptr);
322 ce = make_transient_cache_entry(mode, &oid, path, 2, ce_mem_pool);
323 if (!ce)
324 die(_("make_cache_entry failed for path '%s'"), path);
325 status = checkout_entry(ce, state, NULL, nr_checkouts);
326 return status;
329 static void mark_ce_for_checkout_overlay(struct cache_entry *ce,
330 char *ps_matched,
331 const struct checkout_opts *opts)
333 ce->ce_flags &= ~CE_MATCHED;
334 if (!opts->ignore_skipworktree && ce_skip_worktree(ce))
335 return;
336 if (opts->source_tree && !(ce->ce_flags & CE_UPDATE))
338 * "git checkout tree-ish -- path", but this entry
339 * is in the original index but is not in tree-ish
340 * or does not match the pathspec; it will not be
341 * checked out to the working tree. We will not do
342 * anything to this entry at all.
344 return;
346 * Either this entry came from the tree-ish we are
347 * checking the paths out of, or we are checking out
348 * of the index.
350 * If it comes from the tree-ish, we already know it
351 * matches the pathspec and could just stamp
352 * CE_MATCHED to it from update_some(). But we still
353 * need ps_matched and read_tree (and
354 * eventually tree_entry_interesting) cannot fill
355 * ps_matched yet. Once it can, we can avoid calling
356 * match_pathspec() for _all_ entries when
357 * opts->source_tree != NULL.
359 if (ce_path_match(&the_index, ce, &opts->pathspec, ps_matched))
360 ce->ce_flags |= CE_MATCHED;
363 static void mark_ce_for_checkout_no_overlay(struct cache_entry *ce,
364 char *ps_matched,
365 const struct checkout_opts *opts)
367 ce->ce_flags &= ~CE_MATCHED;
368 if (!opts->ignore_skipworktree && ce_skip_worktree(ce))
369 return;
370 if (ce_path_match(&the_index, ce, &opts->pathspec, ps_matched)) {
371 ce->ce_flags |= CE_MATCHED;
372 if (opts->source_tree && !(ce->ce_flags & CE_UPDATE))
374 * In overlay mode, but the path is not in
375 * tree-ish, which means we should remove it
376 * from the index and the working tree.
378 ce->ce_flags |= CE_REMOVE | CE_WT_REMOVE;
382 static int checkout_worktree(const struct checkout_opts *opts,
383 const struct branch_info *info)
385 struct checkout state = CHECKOUT_INIT;
386 int nr_checkouts = 0, nr_unmerged = 0;
387 int errs = 0;
388 int pos;
389 int pc_workers, pc_threshold;
390 struct mem_pool ce_mem_pool;
392 state.force = 1;
393 state.refresh_cache = 1;
394 state.istate = &the_index;
396 mem_pool_init(&ce_mem_pool, 0);
397 get_parallel_checkout_configs(&pc_workers, &pc_threshold);
398 init_checkout_metadata(&state.meta, info->refname,
399 info->commit ? &info->commit->object.oid : &info->oid,
400 NULL);
402 enable_delayed_checkout(&state);
404 if (pc_workers > 1)
405 init_parallel_checkout();
407 for (pos = 0; pos < the_index.cache_nr; pos++) {
408 struct cache_entry *ce = the_index.cache[pos];
409 if (ce->ce_flags & CE_MATCHED) {
410 if (!ce_stage(ce)) {
411 errs |= checkout_entry(ce, &state,
412 NULL, &nr_checkouts);
413 continue;
415 if (opts->writeout_stage)
416 errs |= checkout_stage(opts->writeout_stage,
417 ce, pos,
418 &state,
419 &nr_checkouts, opts->overlay_mode);
420 else if (opts->merge)
421 errs |= checkout_merged(pos, &state,
422 &nr_unmerged,
423 &ce_mem_pool);
424 pos = skip_same_name(ce, pos) - 1;
427 if (pc_workers > 1)
428 errs |= run_parallel_checkout(&state, pc_workers, pc_threshold,
429 NULL, NULL);
430 mem_pool_discard(&ce_mem_pool, should_validate_cache_entries());
431 remove_marked_cache_entries(&the_index, 1);
432 remove_scheduled_dirs();
433 errs |= finish_delayed_checkout(&state, opts->show_progress);
435 if (opts->count_checkout_paths) {
436 if (nr_unmerged)
437 fprintf_ln(stderr, Q_("Recreated %d merge conflict",
438 "Recreated %d merge conflicts",
439 nr_unmerged),
440 nr_unmerged);
441 if (opts->source_tree)
442 fprintf_ln(stderr, Q_("Updated %d path from %s",
443 "Updated %d paths from %s",
444 nr_checkouts),
445 nr_checkouts,
446 repo_find_unique_abbrev(the_repository, &opts->source_tree->object.oid,
447 DEFAULT_ABBREV));
448 else if (!nr_unmerged || nr_checkouts)
449 fprintf_ln(stderr, Q_("Updated %d path from the index",
450 "Updated %d paths from the index",
451 nr_checkouts),
452 nr_checkouts);
455 return errs;
458 static int checkout_paths(const struct checkout_opts *opts,
459 const struct branch_info *new_branch_info)
461 int pos;
462 static char *ps_matched;
463 struct object_id rev;
464 struct commit *head;
465 int errs = 0;
466 struct lock_file lock_file = LOCK_INIT;
467 int checkout_index;
469 trace2_cmd_mode(opts->patch_mode ? "patch" : "path");
471 if (opts->track != BRANCH_TRACK_UNSPECIFIED)
472 die(_("'%s' cannot be used with updating paths"), "--track");
474 if (opts->new_branch_log)
475 die(_("'%s' cannot be used with updating paths"), "-l");
477 if (opts->ignore_unmerged && opts->patch_mode)
478 die(_("'%s' cannot be used with updating paths"),
479 opts->ignore_unmerged_opt);
481 if (opts->force_detach)
482 die(_("'%s' cannot be used with updating paths"), "--detach");
484 if (opts->merge && opts->patch_mode)
485 die(_("options '%s' and '%s' cannot be used together"), "--merge", "--patch");
487 if (opts->ignore_unmerged && opts->merge)
488 die(_("options '%s' and '%s' cannot be used together"),
489 opts->ignore_unmerged_opt, "-m");
491 if (opts->new_branch)
492 die(_("Cannot update paths and switch to branch '%s' at the same time."),
493 opts->new_branch);
495 if (!opts->checkout_worktree && !opts->checkout_index)
496 die(_("neither '%s' or '%s' is specified"),
497 "--staged", "--worktree");
499 if (!opts->checkout_worktree && !opts->from_treeish)
500 die(_("'%s' must be used when '%s' is not specified"),
501 "--worktree", "--source");
504 * Reject --staged option to the restore command when combined with
505 * merge-related options. Use the accept_ref flag to distinguish it
506 * from the checkout command, which does not accept --staged anyway.
508 * `restore --ours|--theirs --worktree --staged` could mean resolving
509 * conflicted paths to one side in both the worktree and the index,
510 * but does not currently.
512 * `restore --merge|--conflict=<style>` already recreates conflicts
513 * in both the worktree and the index, so adding --staged would be
514 * meaningless.
516 if (!opts->accept_ref && opts->checkout_index) {
517 if (opts->writeout_stage)
518 die(_("'%s' or '%s' cannot be used with %s"),
519 "--ours", "--theirs", "--staged");
521 if (opts->merge)
522 die(_("'%s' or '%s' cannot be used with %s"),
523 "--merge", "--conflict", "--staged");
527 * recreating unmerged index entries and writing out data from
528 * unmerged index entries would make no sense when checking out
529 * of a tree-ish.
531 if ((opts->merge || opts->writeout_stage) && opts->source_tree)
532 die(_("'%s', '%s', or '%s' cannot be used when checking out of a tree"),
533 "--merge", "--ours", "--theirs");
535 if (opts->patch_mode) {
536 enum add_p_mode patch_mode;
537 const char *rev = new_branch_info->name;
538 char rev_oid[GIT_MAX_HEXSZ + 1];
541 * Since rev can be in the form of `<a>...<b>` (which is not
542 * recognized by diff-index), we will always replace the name
543 * with the hex of the commit (whether it's in `...` form or
544 * not) for the run_add_interactive() machinery to work
545 * properly. However, there is special logic for the HEAD case
546 * so we mustn't replace that. Also, when we were given a
547 * tree-object, new_branch_info->commit would be NULL, but we
548 * do not have to do any replacement, either.
550 if (rev && new_branch_info->commit && strcmp(rev, "HEAD"))
551 rev = oid_to_hex_r(rev_oid, &new_branch_info->commit->object.oid);
553 if (opts->checkout_index && opts->checkout_worktree)
554 patch_mode = ADD_P_CHECKOUT;
555 else if (opts->checkout_index && !opts->checkout_worktree)
556 patch_mode = ADD_P_RESET;
557 else if (!opts->checkout_index && opts->checkout_worktree)
558 patch_mode = ADD_P_WORKTREE;
559 else
560 BUG("either flag must have been set, worktree=%d, index=%d",
561 opts->checkout_worktree, opts->checkout_index);
562 return !!run_add_p(the_repository, patch_mode, rev,
563 &opts->pathspec);
566 repo_hold_locked_index(the_repository, &lock_file, LOCK_DIE_ON_ERROR);
567 if (repo_read_index_preload(the_repository, &opts->pathspec, 0) < 0)
568 return error(_("index file corrupt"));
570 if (opts->source_tree)
571 read_tree_some(opts->source_tree, &opts->pathspec);
572 if (opts->merge)
573 unmerge_index(&the_index, &opts->pathspec, CE_MATCHED);
575 ps_matched = xcalloc(opts->pathspec.nr, 1);
578 * Make sure all pathspecs participated in locating the paths
579 * to be checked out.
581 for (pos = 0; pos < the_index.cache_nr; pos++)
582 if (opts->overlay_mode)
583 mark_ce_for_checkout_overlay(the_index.cache[pos],
584 ps_matched,
585 opts);
586 else
587 mark_ce_for_checkout_no_overlay(the_index.cache[pos],
588 ps_matched,
589 opts);
591 if (report_path_error(ps_matched, &opts->pathspec)) {
592 free(ps_matched);
593 return 1;
595 free(ps_matched);
597 /* Any unmerged paths? */
598 for (pos = 0; pos < the_index.cache_nr; pos++) {
599 const struct cache_entry *ce = the_index.cache[pos];
600 if (ce->ce_flags & CE_MATCHED) {
601 if (!ce_stage(ce))
602 continue;
603 if (opts->ignore_unmerged) {
604 if (!opts->quiet)
605 warning(_("path '%s' is unmerged"), ce->name);
606 } else if (opts->writeout_stage) {
607 errs |= check_stage(opts->writeout_stage, ce, pos, opts->overlay_mode);
608 } else if (opts->merge) {
609 errs |= check_stages((1<<2) | (1<<3), ce, pos);
610 } else {
611 errs = 1;
612 error(_("path '%s' is unmerged"), ce->name);
614 pos = skip_same_name(ce, pos) - 1;
617 if (errs)
618 return 1;
620 /* Now we are committed to check them out */
621 if (opts->checkout_worktree)
622 errs |= checkout_worktree(opts, new_branch_info);
623 else
624 remove_marked_cache_entries(&the_index, 1);
627 * Allow updating the index when checking out from the index.
628 * This is to save new stat info.
630 if (opts->checkout_worktree && !opts->checkout_index && !opts->source_tree)
631 checkout_index = 1;
632 else
633 checkout_index = opts->checkout_index;
635 if (checkout_index) {
636 if (write_locked_index(&the_index, &lock_file, COMMIT_LOCK))
637 die(_("unable to write new index file"));
638 } else {
640 * NEEDSWORK: if --worktree is not specified, we
641 * should save stat info of checked out files in the
642 * index to avoid the next (potentially costly)
643 * refresh. But it's a bit tricker to do...
645 rollback_lock_file(&lock_file);
648 read_ref_full("HEAD", 0, &rev, NULL);
649 head = lookup_commit_reference_gently(the_repository, &rev, 1);
651 errs |= post_checkout_hook(head, head, 0);
652 return errs;
655 static void show_local_changes(struct object *head,
656 const struct diff_options *opts)
658 struct rev_info rev;
659 /* I think we want full paths, even if we're in a subdirectory. */
660 repo_init_revisions(the_repository, &rev, NULL);
661 rev.diffopt.flags = opts->flags;
662 rev.diffopt.output_format |= DIFF_FORMAT_NAME_STATUS;
663 rev.diffopt.flags.recursive = 1;
664 diff_setup_done(&rev.diffopt);
665 add_pending_object(&rev, head, NULL);
666 run_diff_index(&rev, 0);
667 release_revisions(&rev);
670 static void describe_detached_head(const char *msg, struct commit *commit)
672 struct strbuf sb = STRBUF_INIT;
674 if (!repo_parse_commit(the_repository, commit))
675 pp_commit_easy(CMIT_FMT_ONELINE, commit, &sb);
676 if (print_sha1_ellipsis()) {
677 fprintf(stderr, "%s %s... %s\n", msg,
678 repo_find_unique_abbrev(the_repository, &commit->object.oid, DEFAULT_ABBREV),
679 sb.buf);
680 } else {
681 fprintf(stderr, "%s %s %s\n", msg,
682 repo_find_unique_abbrev(the_repository, &commit->object.oid, DEFAULT_ABBREV),
683 sb.buf);
685 strbuf_release(&sb);
688 static int reset_tree(struct tree *tree, const struct checkout_opts *o,
689 int worktree, int *writeout_error,
690 struct branch_info *info)
692 struct unpack_trees_options opts;
693 struct tree_desc tree_desc;
695 memset(&opts, 0, sizeof(opts));
696 opts.head_idx = -1;
697 opts.update = worktree;
698 opts.skip_unmerged = !worktree;
699 opts.reset = o->force ? UNPACK_RESET_OVERWRITE_UNTRACKED :
700 UNPACK_RESET_PROTECT_UNTRACKED;
701 opts.preserve_ignored = (!o->force && !o->overwrite_ignore);
702 opts.merge = 1;
703 opts.fn = oneway_merge;
704 opts.verbose_update = o->show_progress;
705 opts.src_index = &the_index;
706 opts.dst_index = &the_index;
707 init_checkout_metadata(&opts.meta, info->refname,
708 info->commit ? &info->commit->object.oid : null_oid(),
709 NULL);
710 if (parse_tree(tree) < 0)
711 return 128;
712 init_tree_desc(&tree_desc, tree->buffer, tree->size);
713 switch (unpack_trees(1, &tree_desc, &opts)) {
714 case -2:
715 *writeout_error = 1;
717 * We return 0 nevertheless, as the index is all right
718 * and more importantly we have made best efforts to
719 * update paths in the work tree, and we cannot revert
720 * them.
722 /* fallthrough */
723 case 0:
724 return 0;
725 default:
726 return 128;
730 static void setup_branch_path(struct branch_info *branch)
732 struct strbuf buf = STRBUF_INIT;
735 * If this is a ref, resolve it; otherwise, look up the OID for our
736 * expression. Failure here is okay.
738 if (!repo_dwim_ref(the_repository, branch->name, strlen(branch->name),
739 &branch->oid, &branch->refname, 0))
740 repo_get_oid_committish(the_repository, branch->name, &branch->oid);
742 strbuf_branchname(&buf, branch->name, INTERPRET_BRANCH_LOCAL);
743 if (strcmp(buf.buf, branch->name)) {
744 free(branch->name);
745 branch->name = xstrdup(buf.buf);
747 strbuf_splice(&buf, 0, 0, "refs/heads/", 11);
748 free(branch->path);
749 branch->path = strbuf_detach(&buf, NULL);
752 static void init_topts(struct unpack_trees_options *topts, int merge,
753 int show_progress, int overwrite_ignore,
754 struct commit *old_commit)
756 memset(topts, 0, sizeof(*topts));
757 topts->head_idx = -1;
758 topts->src_index = &the_index;
759 topts->dst_index = &the_index;
761 setup_unpack_trees_porcelain(topts, "checkout");
763 topts->initial_checkout = is_index_unborn(&the_index);
764 topts->update = 1;
765 topts->merge = 1;
766 topts->quiet = merge && old_commit;
767 topts->verbose_update = show_progress;
768 topts->fn = twoway_merge;
769 topts->preserve_ignored = !overwrite_ignore;
772 static int merge_working_tree(const struct checkout_opts *opts,
773 struct branch_info *old_branch_info,
774 struct branch_info *new_branch_info,
775 int *writeout_error)
777 int ret;
778 struct lock_file lock_file = LOCK_INIT;
779 struct tree *new_tree;
781 repo_hold_locked_index(the_repository, &lock_file, LOCK_DIE_ON_ERROR);
782 if (repo_read_index_preload(the_repository, NULL, 0) < 0)
783 return error(_("index file corrupt"));
785 resolve_undo_clear_index(&the_index);
786 if (opts->new_orphan_branch && opts->orphan_from_empty_tree) {
787 if (new_branch_info->commit)
788 BUG("'switch --orphan' should never accept a commit as starting point");
789 new_tree = parse_tree_indirect(the_hash_algo->empty_tree);
790 if (!new_tree)
791 BUG("unable to read empty tree");
792 } else {
793 new_tree = repo_get_commit_tree(the_repository,
794 new_branch_info->commit);
795 if (!new_tree)
796 return error(_("unable to read tree (%s)"),
797 oid_to_hex(&new_branch_info->commit->object.oid));
799 if (opts->discard_changes) {
800 ret = reset_tree(new_tree, opts, 1, writeout_error, new_branch_info);
801 if (ret)
802 return ret;
803 } else {
804 struct tree_desc trees[2];
805 struct tree *tree;
806 struct unpack_trees_options topts;
807 const struct object_id *old_commit_oid;
809 refresh_index(&the_index, REFRESH_QUIET, NULL, NULL, NULL);
811 if (unmerged_index(&the_index)) {
812 error(_("you need to resolve your current index first"));
813 return 1;
816 /* 2-way merge to the new branch */
817 init_topts(&topts, opts->merge, opts->show_progress,
818 opts->overwrite_ignore, old_branch_info->commit);
819 init_checkout_metadata(&topts.meta, new_branch_info->refname,
820 new_branch_info->commit ?
821 &new_branch_info->commit->object.oid :
822 &new_branch_info->oid, NULL);
824 old_commit_oid = old_branch_info->commit ?
825 &old_branch_info->commit->object.oid :
826 the_hash_algo->empty_tree;
827 tree = parse_tree_indirect(old_commit_oid);
828 if (!tree)
829 die(_("unable to parse commit %s"),
830 oid_to_hex(old_commit_oid));
832 init_tree_desc(&trees[0], tree->buffer, tree->size);
833 if (parse_tree(new_tree) < 0)
834 exit(128);
835 tree = new_tree;
836 init_tree_desc(&trees[1], tree->buffer, tree->size);
838 ret = unpack_trees(2, trees, &topts);
839 clear_unpack_trees_porcelain(&topts);
840 if (ret == -1) {
842 * Unpack couldn't do a trivial merge; either
843 * give up or do a real merge, depending on
844 * whether the merge flag was used.
846 struct tree *work;
847 struct tree *old_tree;
848 struct merge_options o;
849 struct strbuf sb = STRBUF_INIT;
850 struct strbuf old_commit_shortname = STRBUF_INIT;
852 if (!opts->merge)
853 return 1;
856 * Without old_branch_info->commit, the below is the same as
857 * the two-tree unpack we already tried and failed.
859 if (!old_branch_info->commit)
860 return 1;
861 old_tree = repo_get_commit_tree(the_repository,
862 old_branch_info->commit);
864 if (repo_index_has_changes(the_repository, old_tree, &sb))
865 die(_("cannot continue with staged changes in "
866 "the following files:\n%s"), sb.buf);
867 strbuf_release(&sb);
869 /* Do more real merge */
872 * We update the index fully, then write the
873 * tree from the index, then merge the new
874 * branch with the current tree, with the old
875 * branch as the base. Then we reset the index
876 * (but not the working tree) to the new
877 * branch, leaving the working tree as the
878 * merged version, but skipping unmerged
879 * entries in the index.
882 add_files_to_cache(the_repository, NULL, NULL, 0, 0);
883 init_merge_options(&o, the_repository);
884 o.verbosity = 0;
885 work = write_in_core_index_as_tree(the_repository);
887 ret = reset_tree(new_tree,
888 opts, 1,
889 writeout_error, new_branch_info);
890 if (ret)
891 return ret;
892 o.ancestor = old_branch_info->name;
893 if (!old_branch_info->name) {
894 strbuf_add_unique_abbrev(&old_commit_shortname,
895 &old_branch_info->commit->object.oid,
896 DEFAULT_ABBREV);
897 o.ancestor = old_commit_shortname.buf;
899 o.branch1 = new_branch_info->name;
900 o.branch2 = "local";
901 ret = merge_trees(&o,
902 new_tree,
903 work,
904 old_tree);
905 if (ret < 0)
906 exit(128);
907 ret = reset_tree(new_tree,
908 opts, 0,
909 writeout_error, new_branch_info);
910 strbuf_release(&o.obuf);
911 strbuf_release(&old_commit_shortname);
912 if (ret)
913 return ret;
917 if (!cache_tree_fully_valid(the_index.cache_tree))
918 cache_tree_update(&the_index, WRITE_TREE_SILENT | WRITE_TREE_REPAIR);
920 if (write_locked_index(&the_index, &lock_file, COMMIT_LOCK))
921 die(_("unable to write new index file"));
923 if (!opts->discard_changes && !opts->quiet && new_branch_info->commit)
924 show_local_changes(&new_branch_info->commit->object, &opts->diff_options);
926 return 0;
929 static void report_tracking(struct branch_info *new_branch_info)
931 struct strbuf sb = STRBUF_INIT;
932 struct branch *branch = branch_get(new_branch_info->name);
934 if (!format_tracking_info(branch, &sb, AHEAD_BEHIND_FULL, 1))
935 return;
936 fputs(sb.buf, stdout);
937 strbuf_release(&sb);
940 static void update_refs_for_switch(const struct checkout_opts *opts,
941 struct branch_info *old_branch_info,
942 struct branch_info *new_branch_info)
944 struct strbuf msg = STRBUF_INIT;
945 const char *old_desc, *reflog_msg;
946 if (opts->new_branch) {
947 if (opts->new_orphan_branch) {
948 char *refname;
950 refname = mkpathdup("refs/heads/%s", opts->new_orphan_branch);
951 if (opts->new_branch_log &&
952 !should_autocreate_reflog(refname)) {
953 int ret;
954 struct strbuf err = STRBUF_INIT;
956 ret = safe_create_reflog(refname, &err);
957 if (ret) {
958 fprintf(stderr, _("Can not do reflog for '%s': %s\n"),
959 opts->new_orphan_branch, err.buf);
960 strbuf_release(&err);
961 free(refname);
962 return;
964 strbuf_release(&err);
966 free(refname);
968 else
969 create_branch(the_repository,
970 opts->new_branch, new_branch_info->name,
971 opts->new_branch_force ? 1 : 0,
972 opts->new_branch_force ? 1 : 0,
973 opts->new_branch_log,
974 opts->quiet,
975 opts->track,
977 free(new_branch_info->name);
978 free(new_branch_info->refname);
979 new_branch_info->name = xstrdup(opts->new_branch);
980 setup_branch_path(new_branch_info);
983 old_desc = old_branch_info->name;
984 if (!old_desc && old_branch_info->commit)
985 old_desc = oid_to_hex(&old_branch_info->commit->object.oid);
987 reflog_msg = getenv("GIT_REFLOG_ACTION");
988 if (!reflog_msg)
989 strbuf_addf(&msg, "checkout: moving from %s to %s",
990 old_desc ? old_desc : "(invalid)", new_branch_info->name);
991 else
992 strbuf_insertstr(&msg, 0, reflog_msg);
994 if (!strcmp(new_branch_info->name, "HEAD") && !new_branch_info->path && !opts->force_detach) {
995 /* Nothing to do. */
996 } else if (opts->force_detach || !new_branch_info->path) { /* No longer on any branch. */
997 update_ref(msg.buf, "HEAD", &new_branch_info->commit->object.oid, NULL,
998 REF_NO_DEREF, UPDATE_REFS_DIE_ON_ERR);
999 if (!opts->quiet) {
1000 if (old_branch_info->path &&
1001 advice_enabled(ADVICE_DETACHED_HEAD) && !opts->force_detach)
1002 detach_advice(new_branch_info->name);
1003 describe_detached_head(_("HEAD is now at"), new_branch_info->commit);
1005 } else if (new_branch_info->path) { /* Switch branches. */
1006 if (create_symref("HEAD", new_branch_info->path, msg.buf) < 0)
1007 die(_("unable to update HEAD"));
1008 if (!opts->quiet) {
1009 if (old_branch_info->path && !strcmp(new_branch_info->path, old_branch_info->path)) {
1010 if (opts->new_branch_force)
1011 fprintf(stderr, _("Reset branch '%s'\n"),
1012 new_branch_info->name);
1013 else
1014 fprintf(stderr, _("Already on '%s'\n"),
1015 new_branch_info->name);
1016 } else if (opts->new_branch) {
1017 if (opts->branch_exists)
1018 fprintf(stderr, _("Switched to and reset branch '%s'\n"), new_branch_info->name);
1019 else
1020 fprintf(stderr, _("Switched to a new branch '%s'\n"), new_branch_info->name);
1021 } else {
1022 fprintf(stderr, _("Switched to branch '%s'\n"),
1023 new_branch_info->name);
1026 if (old_branch_info->path && old_branch_info->name) {
1027 if (!ref_exists(old_branch_info->path) && reflog_exists(old_branch_info->path))
1028 delete_reflog(old_branch_info->path);
1031 remove_branch_state(the_repository, !opts->quiet);
1032 strbuf_release(&msg);
1033 if (!opts->quiet &&
1034 (new_branch_info->path || (!opts->force_detach && !strcmp(new_branch_info->name, "HEAD"))))
1035 report_tracking(new_branch_info);
1038 static int add_pending_uninteresting_ref(const char *refname,
1039 const struct object_id *oid,
1040 int flags UNUSED, void *cb_data)
1042 add_pending_oid(cb_data, refname, oid, UNINTERESTING);
1043 return 0;
1046 static void describe_one_orphan(struct strbuf *sb, struct commit *commit)
1048 strbuf_addstr(sb, " ");
1049 strbuf_add_unique_abbrev(sb, &commit->object.oid, DEFAULT_ABBREV);
1050 strbuf_addch(sb, ' ');
1051 if (!repo_parse_commit(the_repository, commit))
1052 pp_commit_easy(CMIT_FMT_ONELINE, commit, sb);
1053 strbuf_addch(sb, '\n');
1056 #define ORPHAN_CUTOFF 4
1057 static void suggest_reattach(struct commit *commit, struct rev_info *revs)
1059 struct commit *c, *last = NULL;
1060 struct strbuf sb = STRBUF_INIT;
1061 int lost = 0;
1062 while ((c = get_revision(revs)) != NULL) {
1063 if (lost < ORPHAN_CUTOFF)
1064 describe_one_orphan(&sb, c);
1065 last = c;
1066 lost++;
1068 if (ORPHAN_CUTOFF < lost) {
1069 int more = lost - ORPHAN_CUTOFF;
1070 if (more == 1)
1071 describe_one_orphan(&sb, last);
1072 else
1073 strbuf_addf(&sb, _(" ... and %d more.\n"), more);
1076 fprintf(stderr,
1078 /* The singular version */
1079 "Warning: you are leaving %d commit behind, "
1080 "not connected to\n"
1081 "any of your branches:\n\n"
1082 "%s\n",
1083 /* The plural version */
1084 "Warning: you are leaving %d commits behind, "
1085 "not connected to\n"
1086 "any of your branches:\n\n"
1087 "%s\n",
1088 /* Give ngettext() the count */
1089 lost),
1090 lost,
1091 sb.buf);
1092 strbuf_release(&sb);
1094 if (advice_enabled(ADVICE_DETACHED_HEAD))
1095 fprintf(stderr,
1097 /* The singular version */
1098 "If you want to keep it by creating a new branch, "
1099 "this may be a good time\nto do so with:\n\n"
1100 " git branch <new-branch-name> %s\n\n",
1101 /* The plural version */
1102 "If you want to keep them by creating a new branch, "
1103 "this may be a good time\nto do so with:\n\n"
1104 " git branch <new-branch-name> %s\n\n",
1105 /* Give ngettext() the count */
1106 lost),
1107 repo_find_unique_abbrev(the_repository, &commit->object.oid, DEFAULT_ABBREV));
1111 * We are about to leave commit that was at the tip of a detached
1112 * HEAD. If it is not reachable from any ref, this is the last chance
1113 * for the user to do so without resorting to reflog.
1115 static void orphaned_commit_warning(struct commit *old_commit, struct commit *new_commit)
1117 struct rev_info revs;
1118 struct object *object = &old_commit->object;
1120 repo_init_revisions(the_repository, &revs, NULL);
1121 setup_revisions(0, NULL, &revs, NULL);
1123 object->flags &= ~UNINTERESTING;
1124 add_pending_object(&revs, object, oid_to_hex(&object->oid));
1126 for_each_ref(add_pending_uninteresting_ref, &revs);
1127 if (new_commit)
1128 add_pending_oid(&revs, "HEAD",
1129 &new_commit->object.oid,
1130 UNINTERESTING);
1132 if (prepare_revision_walk(&revs))
1133 die(_("internal error in revision walk"));
1134 if (!(old_commit->object.flags & UNINTERESTING))
1135 suggest_reattach(old_commit, &revs);
1136 else
1137 describe_detached_head(_("Previous HEAD position was"), old_commit);
1139 /* Clean up objects used, as they will be reused. */
1140 repo_clear_commit_marks(the_repository, ALL_REV_FLAGS);
1141 release_revisions(&revs);
1144 static int switch_branches(const struct checkout_opts *opts,
1145 struct branch_info *new_branch_info)
1147 int ret = 0;
1148 struct branch_info old_branch_info = { 0 };
1149 struct object_id rev;
1150 int flag, writeout_error = 0;
1151 int do_merge = 1;
1153 trace2_cmd_mode("branch");
1155 memset(&old_branch_info, 0, sizeof(old_branch_info));
1156 old_branch_info.path = resolve_refdup("HEAD", 0, &rev, &flag);
1157 if (old_branch_info.path)
1158 old_branch_info.commit = lookup_commit_reference_gently(the_repository, &rev, 1);
1159 if (!(flag & REF_ISSYMREF))
1160 FREE_AND_NULL(old_branch_info.path);
1162 if (old_branch_info.path) {
1163 const char *const prefix = "refs/heads/";
1164 const char *p;
1165 if (skip_prefix(old_branch_info.path, prefix, &p))
1166 old_branch_info.name = xstrdup(p);
1169 if (opts->new_orphan_branch && opts->orphan_from_empty_tree) {
1170 if (new_branch_info->name)
1171 BUG("'switch --orphan' should never accept a commit as starting point");
1172 new_branch_info->commit = NULL;
1173 new_branch_info->name = xstrdup("(empty)");
1174 do_merge = 1;
1177 if (!new_branch_info->name) {
1178 new_branch_info->name = xstrdup("HEAD");
1179 new_branch_info->commit = old_branch_info.commit;
1180 if (!new_branch_info->commit)
1181 die(_("You are on a branch yet to be born"));
1182 parse_commit_or_die(new_branch_info->commit);
1184 if (opts->only_merge_on_switching_branches)
1185 do_merge = 0;
1188 if (do_merge) {
1189 ret = merge_working_tree(opts, &old_branch_info, new_branch_info, &writeout_error);
1190 if (ret) {
1191 branch_info_release(&old_branch_info);
1192 return ret;
1196 if (!opts->quiet && !old_branch_info.path && old_branch_info.commit && new_branch_info->commit != old_branch_info.commit)
1197 orphaned_commit_warning(old_branch_info.commit, new_branch_info->commit);
1199 update_refs_for_switch(opts, &old_branch_info, new_branch_info);
1201 ret = post_checkout_hook(old_branch_info.commit, new_branch_info->commit, 1);
1202 branch_info_release(&old_branch_info);
1204 return ret || writeout_error;
1207 static int git_checkout_config(const char *var, const char *value,
1208 const struct config_context *ctx, void *cb)
1210 struct checkout_opts *opts = cb;
1212 if (!strcmp(var, "diff.ignoresubmodules")) {
1213 handle_ignore_submodules_arg(&opts->diff_options, value);
1214 return 0;
1216 if (!strcmp(var, "checkout.guess")) {
1217 opts->dwim_new_local_branch = git_config_bool(var, value);
1218 return 0;
1221 if (starts_with(var, "submodule."))
1222 return git_default_submodule_config(var, value, NULL);
1224 return git_xmerge_config(var, value, ctx, NULL);
1227 static void setup_new_branch_info_and_source_tree(
1228 struct branch_info *new_branch_info,
1229 struct checkout_opts *opts,
1230 struct object_id *rev,
1231 const char *arg)
1233 struct tree **source_tree = &opts->source_tree;
1234 struct object_id branch_rev;
1236 new_branch_info->name = xstrdup(arg);
1237 setup_branch_path(new_branch_info);
1239 if (!check_refname_format(new_branch_info->path, 0) &&
1240 !read_ref(new_branch_info->path, &branch_rev))
1241 oidcpy(rev, &branch_rev);
1242 else
1243 /* not an existing branch */
1244 FREE_AND_NULL(new_branch_info->path);
1246 new_branch_info->commit = lookup_commit_reference_gently(the_repository, rev, 1);
1247 if (!new_branch_info->commit) {
1248 /* not a commit */
1249 *source_tree = parse_tree_indirect(rev);
1250 if (!*source_tree)
1251 die(_("unable to read tree (%s)"), oid_to_hex(rev));
1252 } else {
1253 parse_commit_or_die(new_branch_info->commit);
1254 *source_tree = repo_get_commit_tree(the_repository,
1255 new_branch_info->commit);
1256 if (!*source_tree)
1257 die(_("unable to read tree (%s)"),
1258 oid_to_hex(&new_branch_info->commit->object.oid));
1262 static const char *parse_remote_branch(const char *arg,
1263 struct object_id *rev,
1264 int could_be_checkout_paths)
1266 int num_matches = 0;
1267 const char *remote = unique_tracking_name(arg, rev, &num_matches);
1269 if (remote && could_be_checkout_paths) {
1270 die(_("'%s' could be both a local file and a tracking branch.\n"
1271 "Please use -- (and optionally --no-guess) to disambiguate"),
1272 arg);
1275 if (!remote && num_matches > 1) {
1276 if (advice_enabled(ADVICE_CHECKOUT_AMBIGUOUS_REMOTE_BRANCH_NAME)) {
1277 advise(_("If you meant to check out a remote tracking branch on, e.g. 'origin',\n"
1278 "you can do so by fully qualifying the name with the --track option:\n"
1279 "\n"
1280 " git checkout --track origin/<name>\n"
1281 "\n"
1282 "If you'd like to always have checkouts of an ambiguous <name> prefer\n"
1283 "one remote, e.g. the 'origin' remote, consider setting\n"
1284 "checkout.defaultRemote=origin in your config."));
1287 die(_("'%s' matched multiple (%d) remote tracking branches"),
1288 arg, num_matches);
1291 return remote;
1294 static int parse_branchname_arg(int argc, const char **argv,
1295 int dwim_new_local_branch_ok,
1296 struct branch_info *new_branch_info,
1297 struct checkout_opts *opts,
1298 struct object_id *rev)
1300 const char **new_branch = &opts->new_branch;
1301 int argcount = 0;
1302 const char *arg;
1303 int dash_dash_pos;
1304 int has_dash_dash = 0;
1305 int i;
1308 * case 1: git checkout <ref> -- [<paths>]
1310 * <ref> must be a valid tree, everything after the '--' must be
1311 * a path.
1313 * case 2: git checkout -- [<paths>]
1315 * everything after the '--' must be paths.
1317 * case 3: git checkout <something> [--]
1319 * (a) If <something> is a commit, that is to
1320 * switch to the branch or detach HEAD at it. As a special case,
1321 * if <something> is A...B (missing A or B means HEAD but you can
1322 * omit at most one side), and if there is a unique merge base
1323 * between A and B, A...B names that merge base.
1325 * (b) If <something> is _not_ a commit, either "--" is present
1326 * or <something> is not a path, no -t or -b was given,
1327 * and there is a tracking branch whose name is <something>
1328 * in one and only one remote (or if the branch exists on the
1329 * remote named in checkout.defaultRemote), then this is a
1330 * short-hand to fork local <something> from that
1331 * remote-tracking branch.
1333 * (c) Otherwise, if "--" is present, treat it like case (1).
1335 * (d) Otherwise :
1336 * - if it's a reference, treat it like case (1)
1337 * - else if it's a path, treat it like case (2)
1338 * - else: fail.
1340 * case 4: git checkout <something> <paths>
1342 * The first argument must not be ambiguous.
1343 * - If it's *only* a reference, treat it like case (1).
1344 * - If it's only a path, treat it like case (2).
1345 * - else: fail.
1348 if (!argc)
1349 return 0;
1351 if (!opts->accept_pathspec) {
1352 if (argc > 1)
1353 die(_("only one reference expected"));
1354 has_dash_dash = 1; /* helps disambiguate */
1357 arg = argv[0];
1358 dash_dash_pos = -1;
1359 for (i = 0; i < argc; i++) {
1360 if (opts->accept_pathspec && !strcmp(argv[i], "--")) {
1361 dash_dash_pos = i;
1362 break;
1365 if (dash_dash_pos == 0)
1366 return 1; /* case (2) */
1367 else if (dash_dash_pos == 1)
1368 has_dash_dash = 1; /* case (3) or (1) */
1369 else if (dash_dash_pos >= 2)
1370 die(_("only one reference expected, %d given."), dash_dash_pos);
1371 opts->count_checkout_paths = !opts->quiet && !has_dash_dash;
1373 if (!strcmp(arg, "-"))
1374 arg = "@{-1}";
1376 if (repo_get_oid_mb(the_repository, arg, rev)) {
1378 * Either case (3) or (4), with <something> not being
1379 * a commit, or an attempt to use case (1) with an
1380 * invalid ref.
1382 * It's likely an error, but we need to find out if
1383 * we should auto-create the branch, case (3).(b).
1385 int recover_with_dwim = dwim_new_local_branch_ok;
1387 int could_be_checkout_paths = !has_dash_dash &&
1388 check_filename(opts->prefix, arg);
1390 if (!has_dash_dash && !no_wildcard(arg))
1391 recover_with_dwim = 0;
1394 * Accept "git checkout foo", "git checkout foo --"
1395 * and "git switch foo" as candidates for dwim.
1397 if (!(argc == 1 && !has_dash_dash) &&
1398 !(argc == 2 && has_dash_dash) &&
1399 opts->accept_pathspec)
1400 recover_with_dwim = 0;
1402 if (recover_with_dwim) {
1403 const char *remote = parse_remote_branch(arg, rev,
1404 could_be_checkout_paths);
1405 if (remote) {
1406 *new_branch = arg;
1407 arg = remote;
1408 /* DWIMmed to create local branch, case (3).(b) */
1409 } else {
1410 recover_with_dwim = 0;
1414 if (!recover_with_dwim) {
1415 if (has_dash_dash)
1416 die(_("invalid reference: %s"), arg);
1417 return argcount;
1421 /* we can't end up being in (2) anymore, eat the argument */
1422 argcount++;
1423 argv++;
1424 argc--;
1426 setup_new_branch_info_and_source_tree(new_branch_info, opts, rev, arg);
1428 if (!opts->source_tree) /* case (1): want a tree */
1429 die(_("reference is not a tree: %s"), arg);
1431 if (!has_dash_dash) { /* case (3).(d) -> (1) */
1433 * Do not complain the most common case
1434 * git checkout branch
1435 * even if there happen to be a file called 'branch';
1436 * it would be extremely annoying.
1438 if (argc)
1439 verify_non_filename(opts->prefix, arg);
1440 } else if (opts->accept_pathspec) {
1441 argcount++;
1442 argv++;
1443 argc--;
1446 return argcount;
1449 static int switch_unborn_to_new_branch(const struct checkout_opts *opts)
1451 int status;
1452 struct strbuf branch_ref = STRBUF_INIT;
1454 trace2_cmd_mode("unborn");
1456 if (!opts->new_branch)
1457 die(_("You are on a branch yet to be born"));
1458 strbuf_addf(&branch_ref, "refs/heads/%s", opts->new_branch);
1459 status = create_symref("HEAD", branch_ref.buf, "checkout -b");
1460 strbuf_release(&branch_ref);
1461 if (!opts->quiet)
1462 fprintf(stderr, _("Switched to a new branch '%s'\n"),
1463 opts->new_branch);
1464 return status;
1467 static void die_expecting_a_branch(const struct branch_info *branch_info)
1469 struct object_id oid;
1470 char *to_free;
1471 int code;
1473 if (repo_dwim_ref(the_repository, branch_info->name,
1474 strlen(branch_info->name), &oid, &to_free, 0) == 1) {
1475 const char *ref = to_free;
1477 if (skip_prefix(ref, "refs/tags/", &ref))
1478 code = die_message(_("a branch is expected, got tag '%s'"), ref);
1479 else if (skip_prefix(ref, "refs/remotes/", &ref))
1480 code = die_message(_("a branch is expected, got remote branch '%s'"), ref);
1481 else
1482 code = die_message(_("a branch is expected, got '%s'"), ref);
1484 else if (branch_info->commit)
1485 code = die_message(_("a branch is expected, got commit '%s'"), branch_info->name);
1486 else
1488 * This case should never happen because we already die() on
1489 * non-commit, but just in case.
1491 code = die_message(_("a branch is expected, got '%s'"), branch_info->name);
1493 if (advice_enabled(ADVICE_SUGGEST_DETACHING_HEAD))
1494 advise(_("If you want to detach HEAD at the commit, try again with the --detach option."));
1496 exit(code);
1499 static void die_if_some_operation_in_progress(void)
1501 struct wt_status_state state;
1503 memset(&state, 0, sizeof(state));
1504 wt_status_get_state(the_repository, &state, 0);
1506 if (state.merge_in_progress)
1507 die(_("cannot switch branch while merging\n"
1508 "Consider \"git merge --quit\" "
1509 "or \"git worktree add\"."));
1510 if (state.am_in_progress)
1511 die(_("cannot switch branch in the middle of an am session\n"
1512 "Consider \"git am --quit\" "
1513 "or \"git worktree add\"."));
1514 if (state.rebase_interactive_in_progress || state.rebase_in_progress)
1515 die(_("cannot switch branch while rebasing\n"
1516 "Consider \"git rebase --quit\" "
1517 "or \"git worktree add\"."));
1518 if (state.cherry_pick_in_progress)
1519 die(_("cannot switch branch while cherry-picking\n"
1520 "Consider \"git cherry-pick --quit\" "
1521 "or \"git worktree add\"."));
1522 if (state.revert_in_progress)
1523 die(_("cannot switch branch while reverting\n"
1524 "Consider \"git revert --quit\" "
1525 "or \"git worktree add\"."));
1526 if (state.bisect_in_progress)
1527 warning(_("you are switching branch while bisecting"));
1529 wt_status_state_free_buffers(&state);
1532 static int checkout_branch(struct checkout_opts *opts,
1533 struct branch_info *new_branch_info)
1535 if (opts->pathspec.nr)
1536 die(_("paths cannot be used with switching branches"));
1538 if (opts->patch_mode)
1539 die(_("'%s' cannot be used with switching branches"),
1540 "--patch");
1542 if (opts->overlay_mode != -1)
1543 die(_("'%s' cannot be used with switching branches"),
1544 "--[no]-overlay");
1546 if (opts->writeout_stage)
1547 die(_("'%s' cannot be used with switching branches"),
1548 "--ours/--theirs");
1550 if (opts->force && opts->merge)
1551 die(_("'%s' cannot be used with '%s'"), "-f", "-m");
1553 if (opts->discard_changes && opts->merge)
1554 die(_("'%s' cannot be used with '%s'"), "--discard-changes", "--merge");
1556 if (opts->force_detach && opts->new_branch)
1557 die(_("'%s' cannot be used with '%s'"),
1558 "--detach", "-b/-B/--orphan");
1560 if (opts->new_orphan_branch) {
1561 if (opts->track != BRANCH_TRACK_UNSPECIFIED)
1562 die(_("'%s' cannot be used with '%s'"), "--orphan", "-t");
1563 if (opts->orphan_from_empty_tree && new_branch_info->name)
1564 die(_("'%s' cannot take <start-point>"), "--orphan");
1565 } else if (opts->force_detach) {
1566 if (opts->track != BRANCH_TRACK_UNSPECIFIED)
1567 die(_("'%s' cannot be used with '%s'"), "--detach", "-t");
1568 } else if (opts->track == BRANCH_TRACK_UNSPECIFIED)
1569 opts->track = git_branch_track;
1571 if (new_branch_info->name && !new_branch_info->commit)
1572 die(_("Cannot switch branch to a non-commit '%s'"),
1573 new_branch_info->name);
1575 if (!opts->switch_branch_doing_nothing_is_ok &&
1576 !new_branch_info->name &&
1577 !opts->new_branch &&
1578 !opts->force_detach)
1579 die(_("missing branch or commit argument"));
1581 if (!opts->implicit_detach &&
1582 !opts->force_detach &&
1583 !opts->new_branch &&
1584 !opts->new_branch_force &&
1585 new_branch_info->name &&
1586 !new_branch_info->path)
1587 die_expecting_a_branch(new_branch_info);
1589 if (!opts->can_switch_when_in_progress)
1590 die_if_some_operation_in_progress();
1592 if (new_branch_info->path && !opts->force_detach && !opts->new_branch &&
1593 !opts->ignore_other_worktrees) {
1594 int flag;
1595 char *head_ref = resolve_refdup("HEAD", 0, NULL, &flag);
1596 if (head_ref &&
1597 (!(flag & REF_ISSYMREF) || strcmp(head_ref, new_branch_info->path)))
1598 die_if_checked_out(new_branch_info->path, 1);
1599 free(head_ref);
1602 if (!new_branch_info->commit && opts->new_branch) {
1603 struct object_id rev;
1604 int flag;
1606 if (!read_ref_full("HEAD", 0, &rev, &flag) &&
1607 (flag & REF_ISSYMREF) && is_null_oid(&rev))
1608 return switch_unborn_to_new_branch(opts);
1610 return switch_branches(opts, new_branch_info);
1613 static struct option *add_common_options(struct checkout_opts *opts,
1614 struct option *prevopts)
1616 struct option options[] = {
1617 OPT__QUIET(&opts->quiet, N_("suppress progress reporting")),
1618 OPT_CALLBACK_F(0, "recurse-submodules", NULL,
1619 "checkout", "control recursive updating of submodules",
1620 PARSE_OPT_OPTARG, option_parse_recurse_submodules_worktree_updater),
1621 OPT_BOOL(0, "progress", &opts->show_progress, N_("force progress reporting")),
1622 OPT_BOOL('m', "merge", &opts->merge, N_("perform a 3-way merge with the new branch")),
1623 OPT_STRING(0, "conflict", &opts->conflict_style, N_("style"),
1624 N_("conflict style (merge, diff3, or zdiff3)")),
1625 OPT_END()
1627 struct option *newopts = parse_options_concat(prevopts, options);
1628 free(prevopts);
1629 return newopts;
1632 static struct option *add_common_switch_branch_options(
1633 struct checkout_opts *opts, struct option *prevopts)
1635 struct option options[] = {
1636 OPT_BOOL('d', "detach", &opts->force_detach, N_("detach HEAD at named commit")),
1637 OPT_CALLBACK_F('t', "track", &opts->track, "(direct|inherit)",
1638 N_("set branch tracking configuration"),
1639 PARSE_OPT_OPTARG,
1640 parse_opt_tracking_mode),
1641 OPT__FORCE(&opts->force, N_("force checkout (throw away local modifications)"),
1642 PARSE_OPT_NOCOMPLETE),
1643 OPT_STRING(0, "orphan", &opts->new_orphan_branch, N_("new-branch"), N_("new unparented branch")),
1644 OPT_BOOL_F(0, "overwrite-ignore", &opts->overwrite_ignore,
1645 N_("update ignored files (default)"),
1646 PARSE_OPT_NOCOMPLETE),
1647 OPT_BOOL(0, "ignore-other-worktrees", &opts->ignore_other_worktrees,
1648 N_("do not check if another worktree is holding the given ref")),
1649 OPT_END()
1651 struct option *newopts = parse_options_concat(prevopts, options);
1652 free(prevopts);
1653 return newopts;
1656 static struct option *add_checkout_path_options(struct checkout_opts *opts,
1657 struct option *prevopts)
1659 struct option options[] = {
1660 OPT_SET_INT_F('2', "ours", &opts->writeout_stage,
1661 N_("checkout our version for unmerged files"),
1662 2, PARSE_OPT_NONEG),
1663 OPT_SET_INT_F('3', "theirs", &opts->writeout_stage,
1664 N_("checkout their version for unmerged files"),
1665 3, PARSE_OPT_NONEG),
1666 OPT_BOOL('p', "patch", &opts->patch_mode, N_("select hunks interactively")),
1667 OPT_BOOL(0, "ignore-skip-worktree-bits", &opts->ignore_skipworktree,
1668 N_("do not limit pathspecs to sparse entries only")),
1669 OPT_PATHSPEC_FROM_FILE(&opts->pathspec_from_file),
1670 OPT_PATHSPEC_FILE_NUL(&opts->pathspec_file_nul),
1671 OPT_END()
1673 struct option *newopts = parse_options_concat(prevopts, options);
1674 free(prevopts);
1675 return newopts;
1678 /* create-branch option (either b or c) */
1679 static char cb_option = 'b';
1681 static int checkout_main(int argc, const char **argv, const char *prefix,
1682 struct checkout_opts *opts, struct option *options,
1683 const char * const usagestr[],
1684 struct branch_info *new_branch_info)
1686 int parseopt_flags = 0;
1688 opts->overwrite_ignore = 1;
1689 opts->prefix = prefix;
1690 opts->show_progress = -1;
1692 git_config(git_checkout_config, opts);
1693 if (the_repository->gitdir) {
1694 prepare_repo_settings(the_repository);
1695 the_repository->settings.command_requires_full_index = 0;
1698 opts->track = BRANCH_TRACK_UNSPECIFIED;
1700 if (!opts->accept_pathspec && !opts->accept_ref)
1701 BUG("make up your mind, you need to take _something_");
1702 if (opts->accept_pathspec && opts->accept_ref)
1703 parseopt_flags = PARSE_OPT_KEEP_DASHDASH;
1705 argc = parse_options(argc, argv, prefix, options,
1706 usagestr, parseopt_flags);
1708 if (opts->show_progress < 0) {
1709 if (opts->quiet)
1710 opts->show_progress = 0;
1711 else
1712 opts->show_progress = isatty(2);
1715 if (opts->conflict_style) {
1716 struct key_value_info kvi = KVI_INIT;
1717 struct config_context ctx = {
1718 .kvi = &kvi,
1720 opts->merge = 1; /* implied */
1721 git_xmerge_config("merge.conflictstyle", opts->conflict_style,
1722 &ctx, NULL);
1724 if (opts->force) {
1725 opts->discard_changes = 1;
1726 opts->ignore_unmerged_opt = "--force";
1727 opts->ignore_unmerged = 1;
1730 if ((!!opts->new_branch + !!opts->new_branch_force + !!opts->new_orphan_branch) > 1)
1731 die(_("options '-%c', '-%c', and '%s' cannot be used together"),
1732 cb_option, toupper(cb_option), "--orphan");
1734 if (opts->overlay_mode == 1 && opts->patch_mode)
1735 die(_("options '%s' and '%s' cannot be used together"), "-p", "--overlay");
1737 if (opts->checkout_index >= 0 || opts->checkout_worktree >= 0) {
1738 if (opts->checkout_index < 0)
1739 opts->checkout_index = 0;
1740 if (opts->checkout_worktree < 0)
1741 opts->checkout_worktree = 0;
1742 } else {
1743 if (opts->checkout_index < 0)
1744 opts->checkout_index = -opts->checkout_index - 1;
1745 if (opts->checkout_worktree < 0)
1746 opts->checkout_worktree = -opts->checkout_worktree - 1;
1748 if (opts->checkout_index < 0 || opts->checkout_worktree < 0)
1749 BUG("these flags should be non-negative by now");
1751 * convenient shortcut: "git restore --staged [--worktree]" equals
1752 * "git restore --staged [--worktree] --source HEAD"
1754 if (!opts->from_treeish && opts->checkout_index)
1755 opts->from_treeish = "HEAD";
1758 * From here on, new_branch will contain the branch to be checked out,
1759 * and new_branch_force and new_orphan_branch will tell us which one of
1760 * -b/-B/-c/-C/--orphan is being used.
1762 if (opts->new_branch_force)
1763 opts->new_branch = opts->new_branch_force;
1765 if (opts->new_orphan_branch)
1766 opts->new_branch = opts->new_orphan_branch;
1768 /* --track without -c/-C/-b/-B/--orphan should DWIM */
1769 if (opts->track != BRANCH_TRACK_UNSPECIFIED && !opts->new_branch) {
1770 const char *argv0 = argv[0];
1771 if (!argc || !strcmp(argv0, "--"))
1772 die(_("--track needs a branch name"));
1773 skip_prefix(argv0, "refs/", &argv0);
1774 skip_prefix(argv0, "remotes/", &argv0);
1775 argv0 = strchr(argv0, '/');
1776 if (!argv0 || !argv0[1])
1777 die(_("missing branch name; try -%c"), cb_option);
1778 opts->new_branch = argv0 + 1;
1782 * Extract branch name from command line arguments, so
1783 * all that is left is pathspecs.
1785 * Handle
1787 * 1) git checkout <tree> -- [<paths>]
1788 * 2) git checkout -- [<paths>]
1789 * 3) git checkout <something> [<paths>]
1791 * including "last branch" syntax and DWIM-ery for names of
1792 * remote branches, erroring out for invalid or ambiguous cases.
1794 if (argc && opts->accept_ref) {
1795 struct object_id rev;
1796 int dwim_ok =
1797 !opts->patch_mode &&
1798 opts->dwim_new_local_branch &&
1799 opts->track == BRANCH_TRACK_UNSPECIFIED &&
1800 !opts->new_branch;
1801 int n = parse_branchname_arg(argc, argv, dwim_ok,
1802 new_branch_info, opts, &rev);
1803 argv += n;
1804 argc -= n;
1805 } else if (!opts->accept_ref && opts->from_treeish) {
1806 struct object_id rev;
1808 if (repo_get_oid_mb(the_repository, opts->from_treeish, &rev))
1809 die(_("could not resolve %s"), opts->from_treeish);
1811 setup_new_branch_info_and_source_tree(new_branch_info,
1812 opts, &rev,
1813 opts->from_treeish);
1815 if (!opts->source_tree)
1816 die(_("reference is not a tree: %s"), opts->from_treeish);
1819 if (argc) {
1820 parse_pathspec(&opts->pathspec, 0,
1821 opts->patch_mode ? PATHSPEC_PREFIX_ORIGIN : 0,
1822 prefix, argv);
1824 if (!opts->pathspec.nr)
1825 die(_("invalid path specification"));
1828 * Try to give more helpful suggestion.
1829 * new_branch && argc > 1 will be caught later.
1831 if (opts->new_branch && argc == 1 && !new_branch_info->commit)
1832 die(_("'%s' is not a commit and a branch '%s' cannot be created from it"),
1833 argv[0], opts->new_branch);
1835 if (opts->force_detach)
1836 die(_("git checkout: --detach does not take a path argument '%s'"),
1837 argv[0]);
1840 if (opts->pathspec_from_file) {
1841 if (opts->pathspec.nr)
1842 die(_("'%s' and pathspec arguments cannot be used together"), "--pathspec-from-file");
1844 if (opts->force_detach)
1845 die(_("options '%s' and '%s' cannot be used together"), "--pathspec-from-file", "--detach");
1847 if (opts->patch_mode)
1848 die(_("options '%s' and '%s' cannot be used together"), "--pathspec-from-file", "--patch");
1850 parse_pathspec_file(&opts->pathspec, 0,
1852 prefix, opts->pathspec_from_file, opts->pathspec_file_nul);
1853 } else if (opts->pathspec_file_nul) {
1854 die(_("the option '%s' requires '%s'"), "--pathspec-file-nul", "--pathspec-from-file");
1857 opts->pathspec.recursive = 1;
1859 if (opts->pathspec.nr) {
1860 if (1 < !!opts->writeout_stage + !!opts->force + !!opts->merge)
1861 die(_("git checkout: --ours/--theirs, --force and --merge are incompatible when\n"
1862 "checking out of the index."));
1863 } else {
1864 if (opts->accept_pathspec && !opts->empty_pathspec_ok &&
1865 !opts->patch_mode) /* patch mode is special */
1866 die(_("you must specify path(s) to restore"));
1869 if (opts->new_branch) {
1870 struct strbuf buf = STRBUF_INIT;
1872 if (opts->new_branch_force)
1873 opts->branch_exists = validate_branchname(opts->new_branch, &buf);
1874 else
1875 opts->branch_exists =
1876 validate_new_branchname(opts->new_branch, &buf, 0);
1877 strbuf_release(&buf);
1880 if (opts->patch_mode || opts->pathspec.nr)
1881 return checkout_paths(opts, new_branch_info);
1882 else
1883 return checkout_branch(opts, new_branch_info);
1886 int cmd_checkout(int argc, const char **argv, const char *prefix)
1888 struct checkout_opts opts;
1889 struct option *options;
1890 struct option checkout_options[] = {
1891 OPT_STRING('b', NULL, &opts.new_branch, N_("branch"),
1892 N_("create and checkout a new branch")),
1893 OPT_STRING('B', NULL, &opts.new_branch_force, N_("branch"),
1894 N_("create/reset and checkout a branch")),
1895 OPT_BOOL('l', NULL, &opts.new_branch_log, N_("create reflog for new branch")),
1896 OPT_BOOL(0, "guess", &opts.dwim_new_local_branch,
1897 N_("second guess 'git checkout <no-such-branch>' (default)")),
1898 OPT_BOOL(0, "overlay", &opts.overlay_mode, N_("use overlay mode (default)")),
1899 OPT_END()
1901 int ret;
1902 struct branch_info new_branch_info = { 0 };
1904 memset(&opts, 0, sizeof(opts));
1905 opts.dwim_new_local_branch = 1;
1906 opts.switch_branch_doing_nothing_is_ok = 1;
1907 opts.only_merge_on_switching_branches = 0;
1908 opts.accept_ref = 1;
1909 opts.accept_pathspec = 1;
1910 opts.implicit_detach = 1;
1911 opts.can_switch_when_in_progress = 1;
1912 opts.orphan_from_empty_tree = 0;
1913 opts.empty_pathspec_ok = 1;
1914 opts.overlay_mode = -1;
1915 opts.checkout_index = -2; /* default on */
1916 opts.checkout_worktree = -2; /* default on */
1918 if (argc == 3 && !strcmp(argv[1], "-b")) {
1920 * User ran 'git checkout -b <branch>' and expects
1921 * the same behavior as 'git switch -c <branch>'.
1923 opts.switch_branch_doing_nothing_is_ok = 0;
1924 opts.only_merge_on_switching_branches = 1;
1927 options = parse_options_dup(checkout_options);
1928 options = add_common_options(&opts, options);
1929 options = add_common_switch_branch_options(&opts, options);
1930 options = add_checkout_path_options(&opts, options);
1932 ret = checkout_main(argc, argv, prefix, &opts,
1933 options, checkout_usage, &new_branch_info);
1934 branch_info_release(&new_branch_info);
1935 clear_pathspec(&opts.pathspec);
1936 free(opts.pathspec_from_file);
1937 FREE_AND_NULL(options);
1938 return ret;
1941 int cmd_switch(int argc, const char **argv, const char *prefix)
1943 struct checkout_opts opts;
1944 struct option *options = NULL;
1945 struct option switch_options[] = {
1946 OPT_STRING('c', "create", &opts.new_branch, N_("branch"),
1947 N_("create and switch to a new branch")),
1948 OPT_STRING('C', "force-create", &opts.new_branch_force, N_("branch"),
1949 N_("create/reset and switch to a branch")),
1950 OPT_BOOL(0, "guess", &opts.dwim_new_local_branch,
1951 N_("second guess 'git switch <no-such-branch>'")),
1952 OPT_BOOL(0, "discard-changes", &opts.discard_changes,
1953 N_("throw away local modifications")),
1954 OPT_END()
1956 int ret;
1957 struct branch_info new_branch_info = { 0 };
1959 memset(&opts, 0, sizeof(opts));
1960 opts.dwim_new_local_branch = 1;
1961 opts.accept_ref = 1;
1962 opts.accept_pathspec = 0;
1963 opts.switch_branch_doing_nothing_is_ok = 0;
1964 opts.only_merge_on_switching_branches = 1;
1965 opts.implicit_detach = 0;
1966 opts.can_switch_when_in_progress = 0;
1967 opts.orphan_from_empty_tree = 1;
1968 opts.overlay_mode = -1;
1970 options = parse_options_dup(switch_options);
1971 options = add_common_options(&opts, options);
1972 options = add_common_switch_branch_options(&opts, options);
1974 cb_option = 'c';
1976 ret = checkout_main(argc, argv, prefix, &opts,
1977 options, switch_branch_usage, &new_branch_info);
1978 branch_info_release(&new_branch_info);
1979 FREE_AND_NULL(options);
1980 return ret;
1983 int cmd_restore(int argc, const char **argv, const char *prefix)
1985 struct checkout_opts opts;
1986 struct option *options;
1987 struct option restore_options[] = {
1988 OPT_STRING('s', "source", &opts.from_treeish, "<tree-ish>",
1989 N_("which tree-ish to checkout from")),
1990 OPT_BOOL('S', "staged", &opts.checkout_index,
1991 N_("restore the index")),
1992 OPT_BOOL('W', "worktree", &opts.checkout_worktree,
1993 N_("restore the working tree (default)")),
1994 OPT_BOOL(0, "ignore-unmerged", &opts.ignore_unmerged,
1995 N_("ignore unmerged entries")),
1996 OPT_BOOL(0, "overlay", &opts.overlay_mode, N_("use overlay mode")),
1997 OPT_END()
1999 int ret;
2000 struct branch_info new_branch_info = { 0 };
2002 memset(&opts, 0, sizeof(opts));
2003 opts.accept_ref = 0;
2004 opts.accept_pathspec = 1;
2005 opts.empty_pathspec_ok = 0;
2006 opts.overlay_mode = 0;
2007 opts.checkout_index = -1; /* default off */
2008 opts.checkout_worktree = -2; /* default on */
2009 opts.ignore_unmerged_opt = "--ignore-unmerged";
2011 options = parse_options_dup(restore_options);
2012 options = add_common_options(&opts, options);
2013 options = add_checkout_path_options(&opts, options);
2015 ret = checkout_main(argc, argv, prefix, &opts,
2016 options, restore_usage, &new_branch_info);
2017 branch_info_release(&new_branch_info);
2018 FREE_AND_NULL(options);
2019 return ret;