checkout: retire --ignore-other-worktrees in favor of --force
[git/mingw/j6t.git] / builtin / checkout.c
blob01c7c30d54f475ab50fc2cae7f9d33e94b0f2a98
1 #include "builtin.h"
2 #include "lockfile.h"
3 #include "parse-options.h"
4 #include "refs.h"
5 #include "commit.h"
6 #include "tree.h"
7 #include "tree-walk.h"
8 #include "cache-tree.h"
9 #include "unpack-trees.h"
10 #include "dir.h"
11 #include "run-command.h"
12 #include "merge-recursive.h"
13 #include "branch.h"
14 #include "diff.h"
15 #include "revision.h"
16 #include "remote.h"
17 #include "blob.h"
18 #include "xdiff-interface.h"
19 #include "ll-merge.h"
20 #include "resolve-undo.h"
21 #include "submodule.h"
23 static const char * const checkout_usage[] = {
24 N_("git checkout [options] <branch>"),
25 N_("git checkout [options] [<branch>] -- <file>..."),
26 NULL,
29 struct checkout_opts {
30 int patch_mode;
31 int quiet;
32 int merge;
33 int force;
34 int force_detach;
35 int writeout_stage;
36 int overwrite_ignore;
37 int ignore_skipworktree;
39 const char *new_branch;
40 const char *new_branch_force;
41 const char *new_orphan_branch;
42 int new_branch_log;
43 enum branch_track track;
44 struct diff_options diff_options;
46 int branch_exists;
47 const char *prefix;
48 struct pathspec pathspec;
49 struct tree *source_tree;
51 int new_worktree_mode;
54 static int post_checkout_hook(struct commit *old, struct commit *new,
55 int changed)
57 return run_hook_le(NULL, "post-checkout",
58 sha1_to_hex(old ? old->object.sha1 : null_sha1),
59 sha1_to_hex(new ? new->object.sha1 : null_sha1),
60 changed ? "1" : "0", NULL);
61 /* "new" can be NULL when checking out from the index before
62 a commit exists. */
66 static int update_some(const unsigned char *sha1, const char *base, int baselen,
67 const char *pathname, unsigned mode, int stage, void *context)
69 int len;
70 struct cache_entry *ce;
72 if (S_ISDIR(mode))
73 return READ_TREE_RECURSIVE;
75 len = baselen + strlen(pathname);
76 ce = xcalloc(1, cache_entry_size(len));
77 hashcpy(ce->sha1, sha1);
78 memcpy(ce->name, base, baselen);
79 memcpy(ce->name + baselen, pathname, len - baselen);
80 ce->ce_flags = create_ce_flags(0) | CE_UPDATE;
81 ce->ce_namelen = len;
82 ce->ce_mode = create_ce_mode(mode);
83 add_cache_entry(ce, ADD_CACHE_OK_TO_ADD | ADD_CACHE_OK_TO_REPLACE);
84 return 0;
87 static int read_tree_some(struct tree *tree, const struct pathspec *pathspec)
89 read_tree_recursive(tree, "", 0, 0, pathspec, update_some, NULL);
91 /* update the index with the given tree's info
92 * for all args, expanding wildcards, and exit
93 * with any non-zero return code.
95 return 0;
98 static int skip_same_name(const struct cache_entry *ce, int pos)
100 while (++pos < active_nr &&
101 !strcmp(active_cache[pos]->name, ce->name))
102 ; /* skip */
103 return pos;
106 static int check_stage(int stage, const struct cache_entry *ce, int pos)
108 while (pos < active_nr &&
109 !strcmp(active_cache[pos]->name, ce->name)) {
110 if (ce_stage(active_cache[pos]) == stage)
111 return 0;
112 pos++;
114 if (stage == 2)
115 return error(_("path '%s' does not have our version"), ce->name);
116 else
117 return error(_("path '%s' does not have their version"), ce->name);
120 static int check_stages(unsigned stages, const struct cache_entry *ce, int pos)
122 unsigned seen = 0;
123 const char *name = ce->name;
125 while (pos < active_nr) {
126 ce = active_cache[pos];
127 if (strcmp(name, ce->name))
128 break;
129 seen |= (1 << ce_stage(ce));
130 pos++;
132 if ((stages & seen) != stages)
133 return error(_("path '%s' does not have all necessary versions"),
134 name);
135 return 0;
138 static int checkout_stage(int stage, struct cache_entry *ce, int pos,
139 struct checkout *state)
141 while (pos < active_nr &&
142 !strcmp(active_cache[pos]->name, ce->name)) {
143 if (ce_stage(active_cache[pos]) == stage)
144 return checkout_entry(active_cache[pos], state, NULL);
145 pos++;
147 if (stage == 2)
148 return error(_("path '%s' does not have our version"), ce->name);
149 else
150 return error(_("path '%s' does not have their version"), ce->name);
153 static int checkout_merged(int pos, struct checkout *state)
155 struct cache_entry *ce = active_cache[pos];
156 const char *path = ce->name;
157 mmfile_t ancestor, ours, theirs;
158 int status;
159 unsigned char sha1[20];
160 mmbuffer_t result_buf;
161 unsigned char threeway[3][20];
162 unsigned mode = 0;
164 memset(threeway, 0, sizeof(threeway));
165 while (pos < active_nr) {
166 int stage;
167 stage = ce_stage(ce);
168 if (!stage || strcmp(path, ce->name))
169 break;
170 hashcpy(threeway[stage - 1], ce->sha1);
171 if (stage == 2)
172 mode = create_ce_mode(ce->ce_mode);
173 pos++;
174 ce = active_cache[pos];
176 if (is_null_sha1(threeway[1]) || is_null_sha1(threeway[2]))
177 return error(_("path '%s' does not have necessary versions"), path);
179 read_mmblob(&ancestor, threeway[0]);
180 read_mmblob(&ours, threeway[1]);
181 read_mmblob(&theirs, threeway[2]);
184 * NEEDSWORK: re-create conflicts from merges with
185 * merge.renormalize set, too
187 status = ll_merge(&result_buf, path, &ancestor, "base",
188 &ours, "ours", &theirs, "theirs", NULL);
189 free(ancestor.ptr);
190 free(ours.ptr);
191 free(theirs.ptr);
192 if (status < 0 || !result_buf.ptr) {
193 free(result_buf.ptr);
194 return error(_("path '%s': cannot merge"), path);
198 * NEEDSWORK:
199 * There is absolutely no reason to write this as a blob object
200 * and create a phony cache entry just to leak. This hack is
201 * primarily to get to the write_entry() machinery that massages
202 * the contents to work-tree format and writes out which only
203 * allows it for a cache entry. The code in write_entry() needs
204 * to be refactored to allow us to feed a <buffer, size, mode>
205 * instead of a cache entry. Such a refactoring would help
206 * merge_recursive as well (it also writes the merge result to the
207 * object database even when it may contain conflicts).
209 if (write_sha1_file(result_buf.ptr, result_buf.size,
210 blob_type, sha1))
211 die(_("Unable to add merge result for '%s'"), path);
212 ce = make_cache_entry(mode, sha1, path, 2, 0);
213 if (!ce)
214 die(_("make_cache_entry failed for path '%s'"), path);
215 status = checkout_entry(ce, state, NULL);
216 return status;
219 static int checkout_paths(const struct checkout_opts *opts,
220 const char *revision)
222 int pos;
223 struct checkout state;
224 static char *ps_matched;
225 unsigned char rev[20];
226 int flag;
227 struct commit *head;
228 int errs = 0;
229 struct lock_file *lock_file;
231 if (opts->track != BRANCH_TRACK_UNSPECIFIED)
232 die(_("'%s' cannot be used with updating paths"), "--track");
234 if (opts->new_branch_log)
235 die(_("'%s' cannot be used with updating paths"), "-l");
237 if (opts->force && opts->patch_mode)
238 die(_("'%s' cannot be used with updating paths"), "-f");
240 if (opts->force_detach)
241 die(_("'%s' cannot be used with updating paths"), "--detach");
243 if (opts->merge && opts->patch_mode)
244 die(_("'%s' cannot be used with %s"), "--merge", "--patch");
246 if (opts->force && opts->merge)
247 die(_("'%s' cannot be used with %s"), "-f", "-m");
249 if (opts->new_branch)
250 die(_("Cannot update paths and switch to branch '%s' at the same time."),
251 opts->new_branch);
253 if (opts->patch_mode)
254 return run_add_interactive(revision, "--patch=checkout",
255 &opts->pathspec);
257 lock_file = xcalloc(1, sizeof(struct lock_file));
259 hold_locked_index(lock_file, 1);
260 if (read_cache_preload(&opts->pathspec) < 0)
261 return error(_("corrupt index file"));
263 if (opts->source_tree)
264 read_tree_some(opts->source_tree, &opts->pathspec);
266 ps_matched = xcalloc(1, opts->pathspec.nr);
269 * Make sure all pathspecs participated in locating the paths
270 * to be checked out.
272 for (pos = 0; pos < active_nr; pos++) {
273 struct cache_entry *ce = active_cache[pos];
274 ce->ce_flags &= ~CE_MATCHED;
275 if (!opts->ignore_skipworktree && ce_skip_worktree(ce))
276 continue;
277 if (opts->source_tree && !(ce->ce_flags & CE_UPDATE))
279 * "git checkout tree-ish -- path", but this entry
280 * is in the original index; it will not be checked
281 * out to the working tree and it does not matter
282 * if pathspec matched this entry. We will not do
283 * anything to this entry at all.
285 continue;
287 * Either this entry came from the tree-ish we are
288 * checking the paths out of, or we are checking out
289 * of the index.
291 * If it comes from the tree-ish, we already know it
292 * matches the pathspec and could just stamp
293 * CE_MATCHED to it from update_some(). But we still
294 * need ps_matched and read_tree_recursive (and
295 * eventually tree_entry_interesting) cannot fill
296 * ps_matched yet. Once it can, we can avoid calling
297 * match_pathspec() for _all_ entries when
298 * opts->source_tree != NULL.
300 if (ce_path_match(ce, &opts->pathspec, ps_matched))
301 ce->ce_flags |= CE_MATCHED;
304 if (report_path_error(ps_matched, &opts->pathspec, opts->prefix)) {
305 free(ps_matched);
306 return 1;
308 free(ps_matched);
310 /* "checkout -m path" to recreate conflicted state */
311 if (opts->merge)
312 unmerge_marked_index(&the_index);
314 /* Any unmerged paths? */
315 for (pos = 0; pos < active_nr; pos++) {
316 const struct cache_entry *ce = active_cache[pos];
317 if (ce->ce_flags & CE_MATCHED) {
318 if (!ce_stage(ce))
319 continue;
320 if (opts->force) {
321 warning(_("path '%s' is unmerged"), ce->name);
322 } else if (opts->writeout_stage) {
323 errs |= check_stage(opts->writeout_stage, ce, pos);
324 } else if (opts->merge) {
325 errs |= check_stages((1<<2) | (1<<3), ce, pos);
326 } else {
327 errs = 1;
328 error(_("path '%s' is unmerged"), ce->name);
330 pos = skip_same_name(ce, pos) - 1;
333 if (errs)
334 return 1;
336 /* Now we are committed to check them out */
337 memset(&state, 0, sizeof(state));
338 state.force = 1;
339 state.refresh_cache = 1;
340 state.istate = &the_index;
341 for (pos = 0; pos < active_nr; pos++) {
342 struct cache_entry *ce = active_cache[pos];
343 if (ce->ce_flags & CE_MATCHED) {
344 if (!ce_stage(ce)) {
345 errs |= checkout_entry(ce, &state, NULL);
346 continue;
348 if (opts->writeout_stage)
349 errs |= checkout_stage(opts->writeout_stage, ce, pos, &state);
350 else if (opts->merge)
351 errs |= checkout_merged(pos, &state);
352 pos = skip_same_name(ce, pos) - 1;
356 if (write_locked_index(&the_index, lock_file, COMMIT_LOCK))
357 die(_("unable to write new index file"));
359 read_ref_full("HEAD", 0, rev, &flag);
360 head = lookup_commit_reference_gently(rev, 1);
362 errs |= post_checkout_hook(head, head, 0);
363 return errs;
366 static void show_local_changes(struct object *head,
367 const struct diff_options *opts)
369 struct rev_info rev;
370 /* I think we want full paths, even if we're in a subdirectory. */
371 init_revisions(&rev, NULL);
372 rev.diffopt.flags = opts->flags;
373 rev.diffopt.output_format |= DIFF_FORMAT_NAME_STATUS;
374 diff_setup_done(&rev.diffopt);
375 add_pending_object(&rev, head, NULL);
376 run_diff_index(&rev, 0);
379 static void describe_detached_head(const char *msg, struct commit *commit)
381 struct strbuf sb = STRBUF_INIT;
382 if (!parse_commit(commit))
383 pp_commit_easy(CMIT_FMT_ONELINE, commit, &sb);
384 fprintf(stderr, "%s %s... %s\n", msg,
385 find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV), sb.buf);
386 strbuf_release(&sb);
389 static int reset_tree(struct tree *tree, const struct checkout_opts *o,
390 int worktree, int *writeout_error)
392 struct unpack_trees_options opts;
393 struct tree_desc tree_desc;
395 memset(&opts, 0, sizeof(opts));
396 opts.head_idx = -1;
397 opts.update = worktree;
398 opts.skip_unmerged = !worktree;
399 opts.reset = 1;
400 opts.merge = 1;
401 opts.fn = oneway_merge;
402 opts.verbose_update = !o->quiet && isatty(2);
403 opts.src_index = &the_index;
404 opts.dst_index = &the_index;
405 parse_tree(tree);
406 init_tree_desc(&tree_desc, tree->buffer, tree->size);
407 switch (unpack_trees(1, &tree_desc, &opts)) {
408 case -2:
409 *writeout_error = 1;
411 * We return 0 nevertheless, as the index is all right
412 * and more importantly we have made best efforts to
413 * update paths in the work tree, and we cannot revert
414 * them.
416 case 0:
417 return 0;
418 default:
419 return 128;
423 struct branch_info {
424 const char *name; /* The short name used */
425 const char *path; /* The full name of a real branch */
426 struct commit *commit; /* The named commit */
428 * if not null the branch is detached because it's already
429 * checked out in this checkout
431 char *checkout;
434 static void setup_branch_path(struct branch_info *branch)
436 struct strbuf buf = STRBUF_INIT;
438 strbuf_branchname(&buf, branch->name);
439 if (strcmp(buf.buf, branch->name))
440 branch->name = xstrdup(buf.buf);
441 strbuf_splice(&buf, 0, 0, "refs/heads/", 11);
442 branch->path = strbuf_detach(&buf, NULL);
445 static int merge_working_tree(const struct checkout_opts *opts,
446 struct branch_info *old,
447 struct branch_info *new,
448 int *writeout_error)
450 int ret;
451 struct lock_file *lock_file = xcalloc(1, sizeof(struct lock_file));
453 hold_locked_index(lock_file, 1);
454 if (read_cache_preload(NULL) < 0)
455 return error(_("corrupt index file"));
457 resolve_undo_clear();
458 if (opts->force) {
459 ret = reset_tree(new->commit->tree, opts, 1, writeout_error);
460 if (ret)
461 return ret;
462 } else {
463 struct tree_desc trees[2];
464 struct tree *tree;
465 struct unpack_trees_options topts;
467 memset(&topts, 0, sizeof(topts));
468 topts.head_idx = -1;
469 topts.src_index = &the_index;
470 topts.dst_index = &the_index;
472 setup_unpack_trees_porcelain(&topts, "checkout");
474 refresh_cache(REFRESH_QUIET);
476 if (unmerged_cache()) {
477 error(_("you need to resolve your current index first"));
478 return 1;
481 /* 2-way merge to the new branch */
482 topts.initial_checkout = is_cache_unborn();
483 topts.update = 1;
484 topts.merge = 1;
485 topts.gently = opts->merge && old->commit;
486 topts.verbose_update = !opts->quiet && isatty(2);
487 topts.fn = twoway_merge;
488 if (opts->overwrite_ignore) {
489 topts.dir = xcalloc(1, sizeof(*topts.dir));
490 topts.dir->flags |= DIR_SHOW_IGNORED;
491 setup_standard_excludes(topts.dir);
493 tree = parse_tree_indirect(old->commit && !opts->new_worktree_mode ?
494 old->commit->object.sha1 :
495 EMPTY_TREE_SHA1_BIN);
496 init_tree_desc(&trees[0], tree->buffer, tree->size);
497 tree = parse_tree_indirect(new->commit->object.sha1);
498 init_tree_desc(&trees[1], tree->buffer, tree->size);
500 ret = unpack_trees(2, trees, &topts);
501 if (ret == -1) {
503 * Unpack couldn't do a trivial merge; either
504 * give up or do a real merge, depending on
505 * whether the merge flag was used.
507 struct tree *result;
508 struct tree *work;
509 struct merge_options o;
510 if (!opts->merge)
511 return 1;
514 * Without old->commit, the below is the same as
515 * the two-tree unpack we already tried and failed.
517 if (!old->commit)
518 return 1;
520 /* Do more real merge */
523 * We update the index fully, then write the
524 * tree from the index, then merge the new
525 * branch with the current tree, with the old
526 * branch as the base. Then we reset the index
527 * (but not the working tree) to the new
528 * branch, leaving the working tree as the
529 * merged version, but skipping unmerged
530 * entries in the index.
533 add_files_to_cache(NULL, NULL, 0);
535 * NEEDSWORK: carrying over local changes
536 * when branches have different end-of-line
537 * normalization (or clean+smudge rules) is
538 * a pain; plumb in an option to set
539 * o.renormalize?
541 init_merge_options(&o);
542 o.verbosity = 0;
543 work = write_tree_from_memory(&o);
545 ret = reset_tree(new->commit->tree, opts, 1,
546 writeout_error);
547 if (ret)
548 return ret;
549 o.ancestor = old->name;
550 o.branch1 = new->name;
551 o.branch2 = "local";
552 merge_trees(&o, new->commit->tree, work,
553 old->commit->tree, &result);
554 ret = reset_tree(new->commit->tree, opts, 0,
555 writeout_error);
556 if (ret)
557 return ret;
561 if (!active_cache_tree)
562 active_cache_tree = cache_tree();
564 if (!cache_tree_fully_valid(active_cache_tree))
565 cache_tree_update(&the_index, WRITE_TREE_SILENT | WRITE_TREE_REPAIR);
567 if (write_locked_index(&the_index, lock_file, COMMIT_LOCK))
568 die(_("unable to write new index file"));
570 if (!opts->force && !opts->quiet)
571 show_local_changes(&new->commit->object, &opts->diff_options);
573 return 0;
576 static void report_tracking(struct branch_info *new)
578 struct strbuf sb = STRBUF_INIT;
579 struct branch *branch = branch_get(new->name);
581 if (!format_tracking_info(branch, &sb))
582 return;
583 fputs(sb.buf, stdout);
584 strbuf_release(&sb);
587 static void update_refs_for_switch(const struct checkout_opts *opts,
588 struct branch_info *old,
589 struct branch_info *new)
591 struct strbuf msg = STRBUF_INIT;
592 const char *old_desc, *reflog_msg;
593 if (opts->new_branch) {
594 if (opts->new_orphan_branch) {
595 if (opts->new_branch_log && !log_all_ref_updates) {
596 int temp;
597 struct strbuf log_file = STRBUF_INIT;
598 int ret;
599 const char *ref_name;
601 ref_name = mkpath("refs/heads/%s", opts->new_orphan_branch);
602 temp = log_all_ref_updates;
603 log_all_ref_updates = 1;
604 ret = log_ref_setup(ref_name, &log_file);
605 log_all_ref_updates = temp;
606 strbuf_release(&log_file);
607 if (ret) {
608 fprintf(stderr, _("Can not do reflog for '%s'\n"),
609 opts->new_orphan_branch);
610 return;
614 else
615 create_branch(old->name, opts->new_branch, new->name,
616 opts->new_branch_force ? 1 : 0,
617 opts->new_branch_log,
618 opts->new_branch_force ? 1 : 0,
619 opts->quiet,
620 opts->track);
621 new->name = opts->new_branch;
622 setup_branch_path(new);
625 old_desc = old->name;
626 if (!old_desc && old->commit)
627 old_desc = sha1_to_hex(old->commit->object.sha1);
629 reflog_msg = getenv("GIT_REFLOG_ACTION");
630 if (!reflog_msg)
631 strbuf_addf(&msg, "checkout: moving from %s to %s",
632 old_desc ? old_desc : "(invalid)", new->name);
633 else
634 strbuf_insert(&msg, 0, reflog_msg, strlen(reflog_msg));
636 if (!strcmp(new->name, "HEAD") && !new->path && !opts->force_detach) {
637 /* Nothing to do. */
638 } else if (opts->force_detach || !new->path) { /* No longer on any branch. */
639 update_ref(msg.buf, "HEAD", new->commit->object.sha1, NULL,
640 REF_NODEREF, UPDATE_REFS_DIE_ON_ERR);
641 if (!opts->quiet) {
642 if (old->path && advice_detached_head)
643 detach_advice(new->name);
644 describe_detached_head(_("HEAD is now at"), new->commit);
646 } else if (new->path) { /* Switch branches. */
647 create_symref("HEAD", new->path, msg.buf);
648 if (!opts->quiet) {
649 if (old->path && !strcmp(new->path, old->path)) {
650 if (opts->new_branch_force)
651 fprintf(stderr, _("Reset branch '%s'\n"),
652 new->name);
653 else
654 fprintf(stderr, _("Already on '%s'\n"),
655 new->name);
656 } else if (opts->new_branch) {
657 if (opts->branch_exists)
658 fprintf(stderr, _("Switched to and reset branch '%s'\n"), new->name);
659 else
660 fprintf(stderr, _("Switched to a new branch '%s'\n"), new->name);
661 } else {
662 fprintf(stderr, _("Switched to branch '%s'\n"),
663 new->name);
666 if (old->path && old->name) {
667 if (!ref_exists(old->path) && reflog_exists(old->path))
668 delete_reflog(old->path);
671 remove_branch_state();
672 strbuf_release(&msg);
673 if (!opts->quiet &&
674 (new->path || (!opts->force_detach && !strcmp(new->name, "HEAD"))))
675 report_tracking(new);
678 static int add_pending_uninteresting_ref(const char *refname,
679 const unsigned char *sha1,
680 int flags, void *cb_data)
682 add_pending_sha1(cb_data, refname, sha1, UNINTERESTING);
683 return 0;
686 static void describe_one_orphan(struct strbuf *sb, struct commit *commit)
688 strbuf_addstr(sb, " ");
689 strbuf_addstr(sb,
690 find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV));
691 strbuf_addch(sb, ' ');
692 if (!parse_commit(commit))
693 pp_commit_easy(CMIT_FMT_ONELINE, commit, sb);
694 strbuf_addch(sb, '\n');
697 #define ORPHAN_CUTOFF 4
698 static void suggest_reattach(struct commit *commit, struct rev_info *revs)
700 struct commit *c, *last = NULL;
701 struct strbuf sb = STRBUF_INIT;
702 int lost = 0;
703 while ((c = get_revision(revs)) != NULL) {
704 if (lost < ORPHAN_CUTOFF)
705 describe_one_orphan(&sb, c);
706 last = c;
707 lost++;
709 if (ORPHAN_CUTOFF < lost) {
710 int more = lost - ORPHAN_CUTOFF;
711 if (more == 1)
712 describe_one_orphan(&sb, last);
713 else
714 strbuf_addf(&sb, _(" ... and %d more.\n"), more);
717 fprintf(stderr,
719 /* The singular version */
720 "Warning: you are leaving %d commit behind, "
721 "not connected to\n"
722 "any of your branches:\n\n"
723 "%s\n",
724 /* The plural version */
725 "Warning: you are leaving %d commits behind, "
726 "not connected to\n"
727 "any of your branches:\n\n"
728 "%s\n",
729 /* Give ngettext() the count */
730 lost),
731 lost,
732 sb.buf);
733 strbuf_release(&sb);
735 if (advice_detached_head)
736 fprintf(stderr,
738 "If you want to keep them by creating a new branch, "
739 "this may be a good time\nto do so with:\n\n"
740 " git branch new_branch_name %s\n\n"),
741 find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV));
745 * We are about to leave commit that was at the tip of a detached
746 * HEAD. If it is not reachable from any ref, this is the last chance
747 * for the user to do so without resorting to reflog.
749 static void orphaned_commit_warning(struct commit *old, struct commit *new)
751 struct rev_info revs;
752 struct object *object = &old->object;
753 struct object_array refs;
755 init_revisions(&revs, NULL);
756 setup_revisions(0, NULL, &revs, NULL);
758 object->flags &= ~UNINTERESTING;
759 add_pending_object(&revs, object, sha1_to_hex(object->sha1));
761 for_each_ref(add_pending_uninteresting_ref, &revs);
762 add_pending_sha1(&revs, "HEAD", new->object.sha1, UNINTERESTING);
764 refs = revs.pending;
765 revs.leak_pending = 1;
767 if (prepare_revision_walk(&revs))
768 die(_("internal error in revision walk"));
769 if (!(old->object.flags & UNINTERESTING))
770 suggest_reattach(old, &revs);
771 else
772 describe_detached_head(_("Previous HEAD position was"), old);
774 clear_commit_marks_for_object_array(&refs, ALL_REV_FLAGS);
775 free(refs.objects);
778 static int switch_branches(const struct checkout_opts *opts,
779 struct branch_info *new)
781 int ret = 0;
782 struct branch_info old;
783 void *path_to_free;
784 unsigned char rev[20];
785 int flag, writeout_error = 0;
786 memset(&old, 0, sizeof(old));
787 old.path = path_to_free = resolve_refdup("HEAD", 0, rev, &flag);
788 old.commit = lookup_commit_reference_gently(rev, 1);
789 if (!(flag & REF_ISSYMREF))
790 old.path = NULL;
792 if (old.path)
793 skip_prefix(old.path, "refs/heads/", &old.name);
795 if (!new->name) {
796 new->name = "HEAD";
797 new->commit = old.commit;
798 if (!new->commit)
799 die(_("You are on a branch yet to be born"));
800 parse_commit_or_die(new->commit);
803 ret = merge_working_tree(opts, &old, new, &writeout_error);
804 if (ret) {
805 free(path_to_free);
806 return ret;
809 if (!opts->quiet && !old.path && old.commit &&
810 new->commit != old.commit && !opts->new_worktree_mode)
811 orphaned_commit_warning(old.commit, new->commit);
813 update_refs_for_switch(opts, &old, new);
815 ret = post_checkout_hook(old.commit, new->commit, 1);
816 free(path_to_free);
817 return ret || writeout_error;
820 static int git_checkout_config(const char *var, const char *value, void *cb)
822 if (!strcmp(var, "diff.ignoresubmodules")) {
823 struct checkout_opts *opts = cb;
824 handle_ignore_submodules_arg(&opts->diff_options, value);
825 return 0;
828 if (starts_with(var, "submodule."))
829 return parse_submodule_config_option(var, value);
831 return git_xmerge_config(var, value, NULL);
834 struct tracking_name_data {
835 /* const */ char *src_ref;
836 char *dst_ref;
837 unsigned char *dst_sha1;
838 int unique;
841 static int check_tracking_name(struct remote *remote, void *cb_data)
843 struct tracking_name_data *cb = cb_data;
844 struct refspec query;
845 memset(&query, 0, sizeof(struct refspec));
846 query.src = cb->src_ref;
847 if (remote_find_tracking(remote, &query) ||
848 get_sha1(query.dst, cb->dst_sha1)) {
849 free(query.dst);
850 return 0;
852 if (cb->dst_ref) {
853 free(query.dst);
854 cb->unique = 0;
855 return 0;
857 cb->dst_ref = query.dst;
858 return 0;
861 static const char *unique_tracking_name(const char *name, unsigned char *sha1)
863 struct tracking_name_data cb_data = { NULL, NULL, NULL, 1 };
864 char src_ref[PATH_MAX];
865 snprintf(src_ref, PATH_MAX, "refs/heads/%s", name);
866 cb_data.src_ref = src_ref;
867 cb_data.dst_sha1 = sha1;
868 for_each_remote(check_tracking_name, &cb_data);
869 if (cb_data.unique)
870 return cb_data.dst_ref;
871 free(cb_data.dst_ref);
872 return NULL;
875 static void check_linked_checkout(struct branch_info *new, const char *id)
877 struct strbuf sb = STRBUF_INIT;
878 struct strbuf path = STRBUF_INIT;
879 struct strbuf gitdir = STRBUF_INIT;
880 const char *start, *end;
882 if (id)
883 strbuf_addf(&path, "%s/worktrees/%s/HEAD", get_git_common_dir(), id);
884 else
885 strbuf_addf(&path, "%s/HEAD", get_git_common_dir());
887 if (strbuf_read_file(&sb, path.buf, 0) < 0 ||
888 !skip_prefix(sb.buf, "ref:", &start))
889 goto done;
890 while (isspace(*start))
891 start++;
892 end = start;
893 while (*end && !isspace(*end))
894 end++;
895 if (strncmp(start, new->path, end - start) || new->path[end - start] != '\0')
896 goto done;
897 if (id) {
898 strbuf_reset(&path);
899 strbuf_addf(&path, "%s/worktrees/%s/gitdir", get_git_common_dir(), id);
900 if (strbuf_read_file(&gitdir, path.buf, 0) <= 0)
901 goto done;
902 strbuf_rtrim(&gitdir);
903 } else
904 strbuf_addstr(&gitdir, get_git_common_dir());
905 die(_("'%s' is already checked out at '%s'; use --force to override"),
906 new->name, gitdir.buf);
907 done:
908 strbuf_release(&path);
909 strbuf_release(&sb);
910 strbuf_release(&gitdir);
913 static void check_linked_checkouts(struct branch_info *new)
915 struct strbuf path = STRBUF_INIT;
916 DIR *dir;
917 struct dirent *d;
919 strbuf_addf(&path, "%s/worktrees", get_git_common_dir());
920 if ((dir = opendir(path.buf)) == NULL) {
921 strbuf_release(&path);
922 return;
926 * $GIT_COMMON_DIR/HEAD is practically outside
927 * $GIT_DIR so resolve_ref_unsafe() won't work (it
928 * uses git_path). Parse the ref ourselves.
930 check_linked_checkout(new, NULL);
932 while ((d = readdir(dir)) != NULL) {
933 if (!strcmp(d->d_name, ".") || !strcmp(d->d_name, ".."))
934 continue;
935 check_linked_checkout(new, d->d_name);
937 strbuf_release(&path);
938 closedir(dir);
941 static int parse_branchname_arg(int argc, const char **argv,
942 int dwim_new_local_branch_ok,
943 struct branch_info *new,
944 struct checkout_opts *opts,
945 unsigned char rev[20])
947 struct tree **source_tree = &opts->source_tree;
948 const char **new_branch = &opts->new_branch;
949 int argcount = 0;
950 unsigned char branch_rev[20];
951 const char *arg;
952 int dash_dash_pos;
953 int has_dash_dash = 0;
954 int i;
957 * case 1: git checkout <ref> -- [<paths>]
959 * <ref> must be a valid tree, everything after the '--' must be
960 * a path.
962 * case 2: git checkout -- [<paths>]
964 * everything after the '--' must be paths.
966 * case 3: git checkout <something> [--]
968 * (a) If <something> is a commit, that is to
969 * switch to the branch or detach HEAD at it. As a special case,
970 * if <something> is A...B (missing A or B means HEAD but you can
971 * omit at most one side), and if there is a unique merge base
972 * between A and B, A...B names that merge base.
974 * (b) If <something> is _not_ a commit, either "--" is present
975 * or <something> is not a path, no -t or -b was given, and
976 * and there is a tracking branch whose name is <something>
977 * in one and only one remote, then this is a short-hand to
978 * fork local <something> from that remote-tracking branch.
980 * (c) Otherwise, if "--" is present, treat it like case (1).
982 * (d) Otherwise :
983 * - if it's a reference, treat it like case (1)
984 * - else if it's a path, treat it like case (2)
985 * - else: fail.
987 * case 4: git checkout <something> <paths>
989 * The first argument must not be ambiguous.
990 * - If it's *only* a reference, treat it like case (1).
991 * - If it's only a path, treat it like case (2).
992 * - else: fail.
995 if (!argc)
996 return 0;
998 arg = argv[0];
999 dash_dash_pos = -1;
1000 for (i = 0; i < argc; i++) {
1001 if (!strcmp(argv[i], "--")) {
1002 dash_dash_pos = i;
1003 break;
1006 if (dash_dash_pos == 0)
1007 return 1; /* case (2) */
1008 else if (dash_dash_pos == 1)
1009 has_dash_dash = 1; /* case (3) or (1) */
1010 else if (dash_dash_pos >= 2)
1011 die(_("only one reference expected, %d given."), dash_dash_pos);
1013 if (!strcmp(arg, "-"))
1014 arg = "@{-1}";
1016 if (get_sha1_mb(arg, rev)) {
1018 * Either case (3) or (4), with <something> not being
1019 * a commit, or an attempt to use case (1) with an
1020 * invalid ref.
1022 * It's likely an error, but we need to find out if
1023 * we should auto-create the branch, case (3).(b).
1025 int recover_with_dwim = dwim_new_local_branch_ok;
1027 if (check_filename(NULL, arg) && !has_dash_dash)
1028 recover_with_dwim = 0;
1030 * Accept "git checkout foo" and "git checkout foo --"
1031 * as candidates for dwim.
1033 if (!(argc == 1 && !has_dash_dash) &&
1034 !(argc == 2 && has_dash_dash))
1035 recover_with_dwim = 0;
1037 if (recover_with_dwim) {
1038 const char *remote = unique_tracking_name(arg, rev);
1039 if (remote) {
1040 *new_branch = arg;
1041 arg = remote;
1042 /* DWIMmed to create local branch, case (3).(b) */
1043 } else {
1044 recover_with_dwim = 0;
1048 if (!recover_with_dwim) {
1049 if (has_dash_dash)
1050 die(_("invalid reference: %s"), arg);
1051 return argcount;
1055 /* we can't end up being in (2) anymore, eat the argument */
1056 argcount++;
1057 argv++;
1058 argc--;
1060 new->name = arg;
1061 setup_branch_path(new);
1063 if (!check_refname_format(new->path, 0) &&
1064 !read_ref(new->path, branch_rev))
1065 hashcpy(rev, branch_rev);
1066 else
1067 new->path = NULL; /* not an existing branch */
1069 new->commit = lookup_commit_reference_gently(rev, 1);
1070 if (!new->commit) {
1071 /* not a commit */
1072 *source_tree = parse_tree_indirect(rev);
1073 } else {
1074 parse_commit_or_die(new->commit);
1075 *source_tree = new->commit->tree;
1078 if (!*source_tree) /* case (1): want a tree */
1079 die(_("reference is not a tree: %s"), arg);
1080 if (!has_dash_dash) {/* case (3).(d) -> (1) */
1082 * Do not complain the most common case
1083 * git checkout branch
1084 * even if there happen to be a file called 'branch';
1085 * it would be extremely annoying.
1087 if (argc)
1088 verify_non_filename(NULL, arg);
1089 } else {
1090 argcount++;
1091 argv++;
1092 argc--;
1095 return argcount;
1098 static int switch_unborn_to_new_branch(const struct checkout_opts *opts)
1100 int status;
1101 struct strbuf branch_ref = STRBUF_INIT;
1103 if (!opts->new_branch)
1104 die(_("You are on a branch yet to be born"));
1105 strbuf_addf(&branch_ref, "refs/heads/%s", opts->new_branch);
1106 status = create_symref("HEAD", branch_ref.buf, "checkout -b");
1107 strbuf_release(&branch_ref);
1108 if (!opts->quiet)
1109 fprintf(stderr, _("Switched to a new branch '%s'\n"),
1110 opts->new_branch);
1111 return status;
1114 static int checkout_branch(struct checkout_opts *opts,
1115 struct branch_info *new)
1117 if (opts->pathspec.nr)
1118 die(_("paths cannot be used with switching branches"));
1120 if (opts->patch_mode)
1121 die(_("'%s' cannot be used with switching branches"),
1122 "--patch");
1124 if (opts->writeout_stage)
1125 die(_("'%s' cannot be used with switching branches"),
1126 "--ours/--theirs");
1128 if (opts->force && opts->merge)
1129 die(_("'%s' cannot be used with '%s'"), "-f", "-m");
1131 if (opts->force_detach && opts->new_branch)
1132 die(_("'%s' cannot be used with '%s'"),
1133 "--detach", "-b/-B/--orphan");
1135 if (opts->new_orphan_branch) {
1136 if (opts->track != BRANCH_TRACK_UNSPECIFIED)
1137 die(_("'%s' cannot be used with '%s'"), "--orphan", "-t");
1138 } else if (opts->force_detach) {
1139 if (opts->track != BRANCH_TRACK_UNSPECIFIED)
1140 die(_("'%s' cannot be used with '%s'"), "--detach", "-t");
1141 } else if (opts->track == BRANCH_TRACK_UNSPECIFIED)
1142 opts->track = git_branch_track;
1144 if (new->name && !new->commit)
1145 die(_("Cannot switch branch to a non-commit '%s'"),
1146 new->name);
1148 if (new->path && !opts->force_detach && !opts->new_branch) {
1149 unsigned char sha1[20];
1150 int flag;
1151 char *head_ref = resolve_refdup("HEAD", 0, sha1, &flag);
1152 if (head_ref &&
1153 (!(flag & REF_ISSYMREF) || strcmp(head_ref, new->path)) &&
1154 !opts->force)
1155 check_linked_checkouts(new);
1156 free(head_ref);
1159 if (!new->commit && opts->new_branch) {
1160 unsigned char rev[20];
1161 int flag;
1163 if (!read_ref_full("HEAD", 0, rev, &flag) &&
1164 (flag & REF_ISSYMREF) && is_null_sha1(rev))
1165 return switch_unborn_to_new_branch(opts);
1167 return switch_branches(opts, new);
1170 int cmd_checkout(int argc, const char **argv, const char *prefix)
1172 struct checkout_opts opts;
1173 struct branch_info new;
1174 char *conflict_style = NULL;
1175 int dwim_new_local_branch = 1;
1176 struct option options[] = {
1177 OPT__QUIET(&opts.quiet, N_("suppress progress reporting")),
1178 OPT_STRING('b', NULL, &opts.new_branch, N_("branch"),
1179 N_("create and checkout a new branch")),
1180 OPT_STRING('B', NULL, &opts.new_branch_force, N_("branch"),
1181 N_("create/reset and checkout a branch")),
1182 OPT_BOOL('l', NULL, &opts.new_branch_log, N_("create reflog for new branch")),
1183 OPT_BOOL(0, "detach", &opts.force_detach, N_("detach the HEAD at named commit")),
1184 OPT_SET_INT('t', "track", &opts.track, N_("set upstream info for new branch"),
1185 BRANCH_TRACK_EXPLICIT),
1186 OPT_STRING(0, "orphan", &opts.new_orphan_branch, N_("new-branch"), N_("new unparented branch")),
1187 OPT_SET_INT('2', "ours", &opts.writeout_stage, N_("checkout our version for unmerged files"),
1189 OPT_SET_INT('3', "theirs", &opts.writeout_stage, N_("checkout their version for unmerged files"),
1191 OPT__FORCE(&opts.force, N_("force checkout (throw away local modifications)")),
1192 OPT_BOOL('m', "merge", &opts.merge, N_("perform a 3-way merge with the new branch")),
1193 OPT_BOOL(0, "overwrite-ignore", &opts.overwrite_ignore, N_("update ignored files (default)")),
1194 OPT_STRING(0, "conflict", &conflict_style, N_("style"),
1195 N_("conflict style (merge or diff3)")),
1196 OPT_BOOL('p', "patch", &opts.patch_mode, N_("select hunks interactively")),
1197 OPT_BOOL(0, "ignore-skip-worktree-bits", &opts.ignore_skipworktree,
1198 N_("do not limit pathspecs to sparse entries only")),
1199 OPT_HIDDEN_BOOL(0, "guess", &dwim_new_local_branch,
1200 N_("second guess 'git checkout no-such-branch'")),
1201 OPT_END(),
1204 memset(&opts, 0, sizeof(opts));
1205 memset(&new, 0, sizeof(new));
1206 opts.overwrite_ignore = 1;
1207 opts.prefix = prefix;
1209 gitmodules_config();
1210 git_config(git_checkout_config, &opts);
1212 opts.track = BRANCH_TRACK_UNSPECIFIED;
1214 argc = parse_options(argc, argv, prefix, options, checkout_usage,
1215 PARSE_OPT_KEEP_DASHDASH);
1217 opts.new_worktree_mode = getenv("GIT_CHECKOUT_NEW_WORKTREE") != NULL;
1219 if (conflict_style) {
1220 opts.merge = 1; /* implied */
1221 git_xmerge_config("merge.conflictstyle", conflict_style, NULL);
1224 if ((!!opts.new_branch + !!opts.new_branch_force + !!opts.new_orphan_branch) > 1)
1225 die(_("-b, -B and --orphan are mutually exclusive"));
1228 * From here on, new_branch will contain the branch to be checked out,
1229 * and new_branch_force and new_orphan_branch will tell us which one of
1230 * -b/-B/--orphan is being used.
1232 if (opts.new_branch_force)
1233 opts.new_branch = opts.new_branch_force;
1235 if (opts.new_orphan_branch)
1236 opts.new_branch = opts.new_orphan_branch;
1238 /* --track without -b/-B/--orphan should DWIM */
1239 if (opts.track != BRANCH_TRACK_UNSPECIFIED && !opts.new_branch) {
1240 const char *argv0 = argv[0];
1241 if (!argc || !strcmp(argv0, "--"))
1242 die (_("--track needs a branch name"));
1243 skip_prefix(argv0, "refs/", &argv0);
1244 skip_prefix(argv0, "remotes/", &argv0);
1245 argv0 = strchr(argv0, '/');
1246 if (!argv0 || !argv0[1])
1247 die (_("Missing branch name; try -b"));
1248 opts.new_branch = argv0 + 1;
1252 * Extract branch name from command line arguments, so
1253 * all that is left is pathspecs.
1255 * Handle
1257 * 1) git checkout <tree> -- [<paths>]
1258 * 2) git checkout -- [<paths>]
1259 * 3) git checkout <something> [<paths>]
1261 * including "last branch" syntax and DWIM-ery for names of
1262 * remote branches, erroring out for invalid or ambiguous cases.
1264 if (argc) {
1265 unsigned char rev[20];
1266 int dwim_ok =
1267 !opts.patch_mode &&
1268 dwim_new_local_branch &&
1269 opts.track == BRANCH_TRACK_UNSPECIFIED &&
1270 !opts.new_branch;
1271 int n = parse_branchname_arg(argc, argv, dwim_ok,
1272 &new, &opts, rev);
1273 argv += n;
1274 argc -= n;
1277 if (argc) {
1278 parse_pathspec(&opts.pathspec, 0,
1279 opts.patch_mode ? PATHSPEC_PREFIX_ORIGIN : 0,
1280 prefix, argv);
1282 if (!opts.pathspec.nr)
1283 die(_("invalid path specification"));
1286 * Try to give more helpful suggestion.
1287 * new_branch && argc > 1 will be caught later.
1289 if (opts.new_branch && argc == 1)
1290 die(_("Cannot update paths and switch to branch '%s' at the same time.\n"
1291 "Did you intend to checkout '%s' which can not be resolved as commit?"),
1292 opts.new_branch, argv[0]);
1294 if (opts.force_detach)
1295 die(_("git checkout: --detach does not take a path argument '%s'"),
1296 argv[0]);
1298 if (1 < !!opts.writeout_stage + !!opts.force + !!opts.merge)
1299 die(_("git checkout: --ours/--theirs, --force and --merge are incompatible when\n"
1300 "checking out of the index."));
1303 if (opts.new_branch) {
1304 struct strbuf buf = STRBUF_INIT;
1306 opts.branch_exists =
1307 validate_new_branchname(opts.new_branch, &buf,
1308 !!opts.new_branch_force,
1309 !!opts.new_branch_force);
1311 strbuf_release(&buf);
1314 if (opts.patch_mode || opts.pathspec.nr)
1315 return checkout_paths(&opts, new.name);
1316 else
1317 return checkout_branch(&opts, &new);