]> git.ipfire.org Git - thirdparty/git.git/blob - builtin/checkout.c
Merge branch 'dl/checkout-p-merge-base'
[thirdparty/git.git] / builtin / checkout.c
1 #define USE_THE_INDEX_COMPATIBILITY_MACROS
2 #include "builtin.h"
3 #include "advice.h"
4 #include "blob.h"
5 #include "branch.h"
6 #include "cache-tree.h"
7 #include "checkout.h"
8 #include "commit.h"
9 #include "config.h"
10 #include "diff.h"
11 #include "dir.h"
12 #include "ll-merge.h"
13 #include "lockfile.h"
14 #include "merge-recursive.h"
15 #include "object-store.h"
16 #include "parse-options.h"
17 #include "refs.h"
18 #include "remote.h"
19 #include "resolve-undo.h"
20 #include "revision.h"
21 #include "run-command.h"
22 #include "submodule.h"
23 #include "submodule-config.h"
24 #include "tree.h"
25 #include "tree-walk.h"
26 #include "unpack-trees.h"
27 #include "wt-status.h"
28 #include "xdiff-interface.h"
29
30 static const char * const checkout_usage[] = {
31 N_("git checkout [<options>] <branch>"),
32 N_("git checkout [<options>] [<branch>] -- <file>..."),
33 NULL,
34 };
35
36 static const char * const switch_branch_usage[] = {
37 N_("git switch [<options>] [<branch>]"),
38 NULL,
39 };
40
41 static const char * const restore_usage[] = {
42 N_("git restore [<options>] [--source=<branch>] <file>..."),
43 NULL,
44 };
45
46 struct checkout_opts {
47 int patch_mode;
48 int quiet;
49 int merge;
50 int force;
51 int force_detach;
52 int implicit_detach;
53 int writeout_stage;
54 int overwrite_ignore;
55 int ignore_skipworktree;
56 int ignore_other_worktrees;
57 int show_progress;
58 int count_checkout_paths;
59 int overlay_mode;
60 int dwim_new_local_branch;
61 int discard_changes;
62 int accept_ref;
63 int accept_pathspec;
64 int switch_branch_doing_nothing_is_ok;
65 int only_merge_on_switching_branches;
66 int can_switch_when_in_progress;
67 int orphan_from_empty_tree;
68 int empty_pathspec_ok;
69 int checkout_index;
70 int checkout_worktree;
71 const char *ignore_unmerged_opt;
72 int ignore_unmerged;
73 int pathspec_file_nul;
74 const char *pathspec_from_file;
75
76 const char *new_branch;
77 const char *new_branch_force;
78 const char *new_orphan_branch;
79 int new_branch_log;
80 enum branch_track track;
81 struct diff_options diff_options;
82 char *conflict_style;
83
84 int branch_exists;
85 const char *prefix;
86 struct pathspec pathspec;
87 const char *from_treeish;
88 struct tree *source_tree;
89 };
90
91 struct branch_info {
92 const char *name; /* The short name used */
93 const char *path; /* The full name of a real branch */
94 struct commit *commit; /* The named commit */
95 char *refname; /* The full name of the ref being checked out. */
96 struct object_id oid; /* The object ID of the commit being checked out. */
97 /*
98 * if not null the branch is detached because it's already
99 * checked out in this checkout
100 */
101 char *checkout;
102 };
103
104 static int post_checkout_hook(struct commit *old_commit, struct commit *new_commit,
105 int changed)
106 {
107 return run_hook_le(NULL, "post-checkout",
108 oid_to_hex(old_commit ? &old_commit->object.oid : &null_oid),
109 oid_to_hex(new_commit ? &new_commit->object.oid : &null_oid),
110 changed ? "1" : "0", NULL);
111 /* "new_commit" can be NULL when checking out from the index before
112 a commit exists. */
113
114 }
115
116 static int update_some(const struct object_id *oid, struct strbuf *base,
117 const char *pathname, unsigned mode, int stage, void *context)
118 {
119 int len;
120 struct cache_entry *ce;
121 int pos;
122
123 if (S_ISDIR(mode))
124 return READ_TREE_RECURSIVE;
125
126 len = base->len + strlen(pathname);
127 ce = make_empty_cache_entry(&the_index, len);
128 oidcpy(&ce->oid, oid);
129 memcpy(ce->name, base->buf, base->len);
130 memcpy(ce->name + base->len, pathname, len - base->len);
131 ce->ce_flags = create_ce_flags(0) | CE_UPDATE;
132 ce->ce_namelen = len;
133 ce->ce_mode = create_ce_mode(mode);
134
135 /*
136 * If the entry is the same as the current index, we can leave the old
137 * entry in place. Whether it is UPTODATE or not, checkout_entry will
138 * do the right thing.
139 */
140 pos = cache_name_pos(ce->name, ce->ce_namelen);
141 if (pos >= 0) {
142 struct cache_entry *old = active_cache[pos];
143 if (ce->ce_mode == old->ce_mode &&
144 !ce_intent_to_add(old) &&
145 oideq(&ce->oid, &old->oid)) {
146 old->ce_flags |= CE_UPDATE;
147 discard_cache_entry(ce);
148 return 0;
149 }
150 }
151
152 add_cache_entry(ce, ADD_CACHE_OK_TO_ADD | ADD_CACHE_OK_TO_REPLACE);
153 return 0;
154 }
155
156 static int read_tree_some(struct tree *tree, const struct pathspec *pathspec)
157 {
158 read_tree_recursive(the_repository, tree, "", 0, 0,
159 pathspec, update_some, NULL);
160
161 /* update the index with the given tree's info
162 * for all args, expanding wildcards, and exit
163 * with any non-zero return code.
164 */
165 return 0;
166 }
167
168 static int skip_same_name(const struct cache_entry *ce, int pos)
169 {
170 while (++pos < active_nr &&
171 !strcmp(active_cache[pos]->name, ce->name))
172 ; /* skip */
173 return pos;
174 }
175
176 static int check_stage(int stage, const struct cache_entry *ce, int pos,
177 int overlay_mode)
178 {
179 while (pos < active_nr &&
180 !strcmp(active_cache[pos]->name, ce->name)) {
181 if (ce_stage(active_cache[pos]) == stage)
182 return 0;
183 pos++;
184 }
185 if (!overlay_mode)
186 return 0;
187 if (stage == 2)
188 return error(_("path '%s' does not have our version"), ce->name);
189 else
190 return error(_("path '%s' does not have their version"), ce->name);
191 }
192
193 static int check_stages(unsigned stages, const struct cache_entry *ce, int pos)
194 {
195 unsigned seen = 0;
196 const char *name = ce->name;
197
198 while (pos < active_nr) {
199 ce = active_cache[pos];
200 if (strcmp(name, ce->name))
201 break;
202 seen |= (1 << ce_stage(ce));
203 pos++;
204 }
205 if ((stages & seen) != stages)
206 return error(_("path '%s' does not have all necessary versions"),
207 name);
208 return 0;
209 }
210
211 static int checkout_stage(int stage, const struct cache_entry *ce, int pos,
212 const struct checkout *state, int *nr_checkouts,
213 int overlay_mode)
214 {
215 while (pos < active_nr &&
216 !strcmp(active_cache[pos]->name, ce->name)) {
217 if (ce_stage(active_cache[pos]) == stage)
218 return checkout_entry(active_cache[pos], state,
219 NULL, nr_checkouts);
220 pos++;
221 }
222 if (!overlay_mode) {
223 unlink_entry(ce);
224 return 0;
225 }
226 if (stage == 2)
227 return error(_("path '%s' does not have our version"), ce->name);
228 else
229 return error(_("path '%s' does not have their version"), ce->name);
230 }
231
232 static int checkout_merged(int pos, const struct checkout *state, int *nr_checkouts)
233 {
234 struct cache_entry *ce = active_cache[pos];
235 const char *path = ce->name;
236 mmfile_t ancestor, ours, theirs;
237 int status;
238 struct object_id oid;
239 mmbuffer_t result_buf;
240 struct object_id threeway[3];
241 unsigned mode = 0;
242 struct ll_merge_options ll_opts;
243 int renormalize = 0;
244
245 memset(threeway, 0, sizeof(threeway));
246 while (pos < active_nr) {
247 int stage;
248 stage = ce_stage(ce);
249 if (!stage || strcmp(path, ce->name))
250 break;
251 oidcpy(&threeway[stage - 1], &ce->oid);
252 if (stage == 2)
253 mode = create_ce_mode(ce->ce_mode);
254 pos++;
255 ce = active_cache[pos];
256 }
257 if (is_null_oid(&threeway[1]) || is_null_oid(&threeway[2]))
258 return error(_("path '%s' does not have necessary versions"), path);
259
260 read_mmblob(&ancestor, &threeway[0]);
261 read_mmblob(&ours, &threeway[1]);
262 read_mmblob(&theirs, &threeway[2]);
263
264 memset(&ll_opts, 0, sizeof(ll_opts));
265 git_config_get_bool("merge.renormalize", &renormalize);
266 ll_opts.renormalize = renormalize;
267 status = ll_merge(&result_buf, path, &ancestor, "base",
268 &ours, "ours", &theirs, "theirs",
269 state->istate, &ll_opts);
270 free(ancestor.ptr);
271 free(ours.ptr);
272 free(theirs.ptr);
273 if (status < 0 || !result_buf.ptr) {
274 free(result_buf.ptr);
275 return error(_("path '%s': cannot merge"), path);
276 }
277
278 /*
279 * NEEDSWORK:
280 * There is absolutely no reason to write this as a blob object
281 * and create a phony cache entry. This hack is primarily to get
282 * to the write_entry() machinery that massages the contents to
283 * work-tree format and writes out which only allows it for a
284 * cache entry. The code in write_entry() needs to be refactored
285 * to allow us to feed a <buffer, size, mode> instead of a cache
286 * entry. Such a refactoring would help merge_recursive as well
287 * (it also writes the merge result to the object database even
288 * when it may contain conflicts).
289 */
290 if (write_object_file(result_buf.ptr, result_buf.size, blob_type, &oid))
291 die(_("Unable to add merge result for '%s'"), path);
292 free(result_buf.ptr);
293 ce = make_transient_cache_entry(mode, &oid, path, 2);
294 if (!ce)
295 die(_("make_cache_entry failed for path '%s'"), path);
296 status = checkout_entry(ce, state, NULL, nr_checkouts);
297 discard_cache_entry(ce);
298 return status;
299 }
300
301 static void mark_ce_for_checkout_overlay(struct cache_entry *ce,
302 char *ps_matched,
303 const struct checkout_opts *opts)
304 {
305 ce->ce_flags &= ~CE_MATCHED;
306 if (!opts->ignore_skipworktree && ce_skip_worktree(ce))
307 return;
308 if (opts->source_tree && !(ce->ce_flags & CE_UPDATE))
309 /*
310 * "git checkout tree-ish -- path", but this entry
311 * is in the original index but is not in tree-ish
312 * or does not match the pathspec; it will not be
313 * checked out to the working tree. We will not do
314 * anything to this entry at all.
315 */
316 return;
317 /*
318 * Either this entry came from the tree-ish we are
319 * checking the paths out of, or we are checking out
320 * of the index.
321 *
322 * If it comes from the tree-ish, we already know it
323 * matches the pathspec and could just stamp
324 * CE_MATCHED to it from update_some(). But we still
325 * need ps_matched and read_tree_recursive (and
326 * eventually tree_entry_interesting) cannot fill
327 * ps_matched yet. Once it can, we can avoid calling
328 * match_pathspec() for _all_ entries when
329 * opts->source_tree != NULL.
330 */
331 if (ce_path_match(&the_index, ce, &opts->pathspec, ps_matched))
332 ce->ce_flags |= CE_MATCHED;
333 }
334
335 static void mark_ce_for_checkout_no_overlay(struct cache_entry *ce,
336 char *ps_matched,
337 const struct checkout_opts *opts)
338 {
339 ce->ce_flags &= ~CE_MATCHED;
340 if (!opts->ignore_skipworktree && ce_skip_worktree(ce))
341 return;
342 if (ce_path_match(&the_index, ce, &opts->pathspec, ps_matched)) {
343 ce->ce_flags |= CE_MATCHED;
344 if (opts->source_tree && !(ce->ce_flags & CE_UPDATE))
345 /*
346 * In overlay mode, but the path is not in
347 * tree-ish, which means we should remove it
348 * from the index and the working tree.
349 */
350 ce->ce_flags |= CE_REMOVE | CE_WT_REMOVE;
351 }
352 }
353
354 static int checkout_worktree(const struct checkout_opts *opts,
355 const struct branch_info *info)
356 {
357 struct checkout state = CHECKOUT_INIT;
358 int nr_checkouts = 0, nr_unmerged = 0;
359 int errs = 0;
360 int pos;
361
362 state.force = 1;
363 state.refresh_cache = 1;
364 state.istate = &the_index;
365
366 init_checkout_metadata(&state.meta, info->refname,
367 info->commit ? &info->commit->object.oid : &info->oid,
368 NULL);
369
370 enable_delayed_checkout(&state);
371 for (pos = 0; pos < active_nr; pos++) {
372 struct cache_entry *ce = active_cache[pos];
373 if (ce->ce_flags & CE_MATCHED) {
374 if (!ce_stage(ce)) {
375 errs |= checkout_entry(ce, &state,
376 NULL, &nr_checkouts);
377 continue;
378 }
379 if (opts->writeout_stage)
380 errs |= checkout_stage(opts->writeout_stage,
381 ce, pos,
382 &state,
383 &nr_checkouts, opts->overlay_mode);
384 else if (opts->merge)
385 errs |= checkout_merged(pos, &state,
386 &nr_unmerged);
387 pos = skip_same_name(ce, pos) - 1;
388 }
389 }
390 remove_marked_cache_entries(&the_index, 1);
391 remove_scheduled_dirs();
392 errs |= finish_delayed_checkout(&state, &nr_checkouts);
393
394 if (opts->count_checkout_paths) {
395 if (nr_unmerged)
396 fprintf_ln(stderr, Q_("Recreated %d merge conflict",
397 "Recreated %d merge conflicts",
398 nr_unmerged),
399 nr_unmerged);
400 if (opts->source_tree)
401 fprintf_ln(stderr, Q_("Updated %d path from %s",
402 "Updated %d paths from %s",
403 nr_checkouts),
404 nr_checkouts,
405 find_unique_abbrev(&opts->source_tree->object.oid,
406 DEFAULT_ABBREV));
407 else if (!nr_unmerged || nr_checkouts)
408 fprintf_ln(stderr, Q_("Updated %d path from the index",
409 "Updated %d paths from the index",
410 nr_checkouts),
411 nr_checkouts);
412 }
413
414 return errs;
415 }
416
417 static int checkout_paths(const struct checkout_opts *opts,
418 const struct branch_info *new_branch_info)
419 {
420 int pos;
421 static char *ps_matched;
422 struct object_id rev;
423 struct commit *head;
424 int errs = 0;
425 struct lock_file lock_file = LOCK_INIT;
426 int checkout_index;
427
428 trace2_cmd_mode(opts->patch_mode ? "patch" : "path");
429
430 if (opts->track != BRANCH_TRACK_UNSPECIFIED)
431 die(_("'%s' cannot be used with updating paths"), "--track");
432
433 if (opts->new_branch_log)
434 die(_("'%s' cannot be used with updating paths"), "-l");
435
436 if (opts->ignore_unmerged && opts->patch_mode)
437 die(_("'%s' cannot be used with updating paths"),
438 opts->ignore_unmerged_opt);
439
440 if (opts->force_detach)
441 die(_("'%s' cannot be used with updating paths"), "--detach");
442
443 if (opts->merge && opts->patch_mode)
444 die(_("'%s' cannot be used with %s"), "--merge", "--patch");
445
446 if (opts->ignore_unmerged && opts->merge)
447 die(_("'%s' cannot be used with %s"),
448 opts->ignore_unmerged_opt, "-m");
449
450 if (opts->new_branch)
451 die(_("Cannot update paths and switch to branch '%s' at the same time."),
452 opts->new_branch);
453
454 if (!opts->checkout_worktree && !opts->checkout_index)
455 die(_("neither '%s' or '%s' is specified"),
456 "--staged", "--worktree");
457
458 if (!opts->checkout_worktree && !opts->from_treeish)
459 die(_("'%s' must be used when '%s' is not specified"),
460 "--worktree", "--source");
461
462 if (opts->checkout_index && !opts->checkout_worktree &&
463 opts->writeout_stage)
464 die(_("'%s' or '%s' cannot be used with %s"),
465 "--ours", "--theirs", "--staged");
466
467 if (opts->checkout_index && !opts->checkout_worktree &&
468 opts->merge)
469 die(_("'%s' or '%s' cannot be used with %s"),
470 "--merge", "--conflict", "--staged");
471
472 if (opts->patch_mode) {
473 const char *patch_mode;
474 const char *rev = new_branch_info->name;
475 char rev_oid[GIT_MAX_HEXSZ + 1];
476
477 /*
478 * Since rev can be in the form of `<a>...<b>` (which is not
479 * recognized by diff-index), we will always replace the name
480 * with the hex of the commit (whether it's in `...` form or
481 * not) for the run_add_interactive() machinery to work
482 * properly. However, there is special logic for the HEAD case
483 * so we mustn't replace that.
484 */
485 if (rev && strcmp(rev, "HEAD"))
486 rev = oid_to_hex_r(rev_oid, &new_branch_info->commit->object.oid);
487
488 if (opts->checkout_index && opts->checkout_worktree)
489 patch_mode = "--patch=checkout";
490 else if (opts->checkout_index && !opts->checkout_worktree)
491 patch_mode = "--patch=reset";
492 else if (!opts->checkout_index && opts->checkout_worktree)
493 patch_mode = "--patch=worktree";
494 else
495 BUG("either flag must have been set, worktree=%d, index=%d",
496 opts->checkout_worktree, opts->checkout_index);
497 return run_add_interactive(rev, patch_mode, &opts->pathspec);
498 }
499
500 repo_hold_locked_index(the_repository, &lock_file, LOCK_DIE_ON_ERROR);
501 if (read_cache_preload(&opts->pathspec) < 0)
502 return error(_("index file corrupt"));
503
504 if (opts->source_tree)
505 read_tree_some(opts->source_tree, &opts->pathspec);
506
507 ps_matched = xcalloc(opts->pathspec.nr, 1);
508
509 /*
510 * Make sure all pathspecs participated in locating the paths
511 * to be checked out.
512 */
513 for (pos = 0; pos < active_nr; pos++)
514 if (opts->overlay_mode)
515 mark_ce_for_checkout_overlay(active_cache[pos],
516 ps_matched,
517 opts);
518 else
519 mark_ce_for_checkout_no_overlay(active_cache[pos],
520 ps_matched,
521 opts);
522
523 if (report_path_error(ps_matched, &opts->pathspec)) {
524 free(ps_matched);
525 return 1;
526 }
527 free(ps_matched);
528
529 /* "checkout -m path" to recreate conflicted state */
530 if (opts->merge)
531 unmerge_marked_index(&the_index);
532
533 /* Any unmerged paths? */
534 for (pos = 0; pos < active_nr; pos++) {
535 const struct cache_entry *ce = active_cache[pos];
536 if (ce->ce_flags & CE_MATCHED) {
537 if (!ce_stage(ce))
538 continue;
539 if (opts->ignore_unmerged) {
540 if (!opts->quiet)
541 warning(_("path '%s' is unmerged"), ce->name);
542 } else if (opts->writeout_stage) {
543 errs |= check_stage(opts->writeout_stage, ce, pos, opts->overlay_mode);
544 } else if (opts->merge) {
545 errs |= check_stages((1<<2) | (1<<3), ce, pos);
546 } else {
547 errs = 1;
548 error(_("path '%s' is unmerged"), ce->name);
549 }
550 pos = skip_same_name(ce, pos) - 1;
551 }
552 }
553 if (errs)
554 return 1;
555
556 /* Now we are committed to check them out */
557 if (opts->checkout_worktree)
558 errs |= checkout_worktree(opts, new_branch_info);
559 else
560 remove_marked_cache_entries(&the_index, 1);
561
562 /*
563 * Allow updating the index when checking out from the index.
564 * This is to save new stat info.
565 */
566 if (opts->checkout_worktree && !opts->checkout_index && !opts->source_tree)
567 checkout_index = 1;
568 else
569 checkout_index = opts->checkout_index;
570
571 if (checkout_index) {
572 if (write_locked_index(&the_index, &lock_file, COMMIT_LOCK))
573 die(_("unable to write new index file"));
574 } else {
575 /*
576 * NEEDSWORK: if --worktree is not specified, we
577 * should save stat info of checked out files in the
578 * index to avoid the next (potentially costly)
579 * refresh. But it's a bit tricker to do...
580 */
581 rollback_lock_file(&lock_file);
582 }
583
584 read_ref_full("HEAD", 0, &rev, NULL);
585 head = lookup_commit_reference_gently(the_repository, &rev, 1);
586
587 errs |= post_checkout_hook(head, head, 0);
588 return errs;
589 }
590
591 static void show_local_changes(struct object *head,
592 const struct diff_options *opts)
593 {
594 struct rev_info rev;
595 /* I think we want full paths, even if we're in a subdirectory. */
596 repo_init_revisions(the_repository, &rev, NULL);
597 rev.diffopt.flags = opts->flags;
598 rev.diffopt.output_format |= DIFF_FORMAT_NAME_STATUS;
599 diff_setup_done(&rev.diffopt);
600 add_pending_object(&rev, head, NULL);
601 run_diff_index(&rev, 0);
602 }
603
604 static void describe_detached_head(const char *msg, struct commit *commit)
605 {
606 struct strbuf sb = STRBUF_INIT;
607
608 if (!parse_commit(commit))
609 pp_commit_easy(CMIT_FMT_ONELINE, commit, &sb);
610 if (print_sha1_ellipsis()) {
611 fprintf(stderr, "%s %s... %s\n", msg,
612 find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV), sb.buf);
613 } else {
614 fprintf(stderr, "%s %s %s\n", msg,
615 find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV), sb.buf);
616 }
617 strbuf_release(&sb);
618 }
619
620 static int reset_tree(struct tree *tree, const struct checkout_opts *o,
621 int worktree, int *writeout_error,
622 struct branch_info *info)
623 {
624 struct unpack_trees_options opts;
625 struct tree_desc tree_desc;
626
627 memset(&opts, 0, sizeof(opts));
628 opts.head_idx = -1;
629 opts.update = worktree;
630 opts.skip_unmerged = !worktree;
631 opts.reset = 1;
632 opts.merge = 1;
633 opts.fn = oneway_merge;
634 opts.verbose_update = o->show_progress;
635 opts.src_index = &the_index;
636 opts.dst_index = &the_index;
637 init_checkout_metadata(&opts.meta, info->refname,
638 info->commit ? &info->commit->object.oid : &null_oid,
639 NULL);
640 parse_tree(tree);
641 init_tree_desc(&tree_desc, tree->buffer, tree->size);
642 switch (unpack_trees(1, &tree_desc, &opts)) {
643 case -2:
644 *writeout_error = 1;
645 /*
646 * We return 0 nevertheless, as the index is all right
647 * and more importantly we have made best efforts to
648 * update paths in the work tree, and we cannot revert
649 * them.
650 */
651 /* fallthrough */
652 case 0:
653 return 0;
654 default:
655 return 128;
656 }
657 }
658
659 static void setup_branch_path(struct branch_info *branch)
660 {
661 struct strbuf buf = STRBUF_INIT;
662
663 /*
664 * If this is a ref, resolve it; otherwise, look up the OID for our
665 * expression. Failure here is okay.
666 */
667 if (!dwim_ref(branch->name, strlen(branch->name), &branch->oid, &branch->refname, 0))
668 repo_get_oid_committish(the_repository, branch->name, &branch->oid);
669
670 strbuf_branchname(&buf, branch->name, INTERPRET_BRANCH_LOCAL);
671 if (strcmp(buf.buf, branch->name))
672 branch->name = xstrdup(buf.buf);
673 strbuf_splice(&buf, 0, 0, "refs/heads/", 11);
674 branch->path = strbuf_detach(&buf, NULL);
675 }
676
677 static int merge_working_tree(const struct checkout_opts *opts,
678 struct branch_info *old_branch_info,
679 struct branch_info *new_branch_info,
680 int *writeout_error)
681 {
682 int ret;
683 struct lock_file lock_file = LOCK_INIT;
684 struct tree *new_tree;
685
686 hold_locked_index(&lock_file, LOCK_DIE_ON_ERROR);
687 if (read_cache_preload(NULL) < 0)
688 return error(_("index file corrupt"));
689
690 resolve_undo_clear();
691 if (opts->new_orphan_branch && opts->orphan_from_empty_tree) {
692 if (new_branch_info->commit)
693 BUG("'switch --orphan' should never accept a commit as starting point");
694 new_tree = parse_tree_indirect(the_hash_algo->empty_tree);
695 } else
696 new_tree = get_commit_tree(new_branch_info->commit);
697 if (opts->discard_changes) {
698 ret = reset_tree(new_tree, opts, 1, writeout_error, new_branch_info);
699 if (ret)
700 return ret;
701 } else {
702 struct tree_desc trees[2];
703 struct tree *tree;
704 struct unpack_trees_options topts;
705
706 memset(&topts, 0, sizeof(topts));
707 topts.head_idx = -1;
708 topts.src_index = &the_index;
709 topts.dst_index = &the_index;
710
711 setup_unpack_trees_porcelain(&topts, "checkout");
712
713 refresh_cache(REFRESH_QUIET);
714
715 if (unmerged_cache()) {
716 error(_("you need to resolve your current index first"));
717 return 1;
718 }
719
720 /* 2-way merge to the new branch */
721 topts.initial_checkout = is_cache_unborn();
722 topts.update = 1;
723 topts.merge = 1;
724 topts.quiet = opts->merge && old_branch_info->commit;
725 topts.verbose_update = opts->show_progress;
726 topts.fn = twoway_merge;
727 init_checkout_metadata(&topts.meta, new_branch_info->refname,
728 new_branch_info->commit ?
729 &new_branch_info->commit->object.oid :
730 &new_branch_info->oid, NULL);
731 if (opts->overwrite_ignore) {
732 topts.dir = xcalloc(1, sizeof(*topts.dir));
733 topts.dir->flags |= DIR_SHOW_IGNORED;
734 setup_standard_excludes(topts.dir);
735 }
736 tree = parse_tree_indirect(old_branch_info->commit ?
737 &old_branch_info->commit->object.oid :
738 the_hash_algo->empty_tree);
739 init_tree_desc(&trees[0], tree->buffer, tree->size);
740 parse_tree(new_tree);
741 tree = new_tree;
742 init_tree_desc(&trees[1], tree->buffer, tree->size);
743
744 ret = unpack_trees(2, trees, &topts);
745 clear_unpack_trees_porcelain(&topts);
746 if (ret == -1) {
747 /*
748 * Unpack couldn't do a trivial merge; either
749 * give up or do a real merge, depending on
750 * whether the merge flag was used.
751 */
752 struct tree *work;
753 struct tree *old_tree;
754 struct merge_options o;
755 struct strbuf sb = STRBUF_INIT;
756 struct strbuf old_commit_shortname = STRBUF_INIT;
757
758 if (!opts->merge)
759 return 1;
760
761 /*
762 * Without old_branch_info->commit, the below is the same as
763 * the two-tree unpack we already tried and failed.
764 */
765 if (!old_branch_info->commit)
766 return 1;
767 old_tree = get_commit_tree(old_branch_info->commit);
768
769 if (repo_index_has_changes(the_repository, old_tree, &sb))
770 die(_("cannot continue with staged changes in "
771 "the following files:\n%s"), sb.buf);
772 strbuf_release(&sb);
773
774 /* Do more real merge */
775
776 /*
777 * We update the index fully, then write the
778 * tree from the index, then merge the new
779 * branch with the current tree, with the old
780 * branch as the base. Then we reset the index
781 * (but not the working tree) to the new
782 * branch, leaving the working tree as the
783 * merged version, but skipping unmerged
784 * entries in the index.
785 */
786
787 add_files_to_cache(NULL, NULL, 0);
788 init_merge_options(&o, the_repository);
789 o.verbosity = 0;
790 work = write_in_core_index_as_tree(the_repository);
791
792 ret = reset_tree(new_tree,
793 opts, 1,
794 writeout_error, new_branch_info);
795 if (ret)
796 return ret;
797 o.ancestor = old_branch_info->name;
798 if (old_branch_info->name == NULL) {
799 strbuf_add_unique_abbrev(&old_commit_shortname,
800 &old_branch_info->commit->object.oid,
801 DEFAULT_ABBREV);
802 o.ancestor = old_commit_shortname.buf;
803 }
804 o.branch1 = new_branch_info->name;
805 o.branch2 = "local";
806 ret = merge_trees(&o,
807 new_tree,
808 work,
809 old_tree);
810 if (ret < 0)
811 exit(128);
812 ret = reset_tree(new_tree,
813 opts, 0,
814 writeout_error, new_branch_info);
815 strbuf_release(&o.obuf);
816 strbuf_release(&old_commit_shortname);
817 if (ret)
818 return ret;
819 }
820 }
821
822 if (!active_cache_tree)
823 active_cache_tree = cache_tree();
824
825 if (!cache_tree_fully_valid(active_cache_tree))
826 cache_tree_update(&the_index, WRITE_TREE_SILENT | WRITE_TREE_REPAIR);
827
828 if (write_locked_index(&the_index, &lock_file, COMMIT_LOCK))
829 die(_("unable to write new index file"));
830
831 if (!opts->discard_changes && !opts->quiet && new_branch_info->commit)
832 show_local_changes(&new_branch_info->commit->object, &opts->diff_options);
833
834 return 0;
835 }
836
837 static void report_tracking(struct branch_info *new_branch_info)
838 {
839 struct strbuf sb = STRBUF_INIT;
840 struct branch *branch = branch_get(new_branch_info->name);
841
842 if (!format_tracking_info(branch, &sb, AHEAD_BEHIND_FULL))
843 return;
844 fputs(sb.buf, stdout);
845 strbuf_release(&sb);
846 }
847
848 static void update_refs_for_switch(const struct checkout_opts *opts,
849 struct branch_info *old_branch_info,
850 struct branch_info *new_branch_info)
851 {
852 struct strbuf msg = STRBUF_INIT;
853 const char *old_desc, *reflog_msg;
854 if (opts->new_branch) {
855 if (opts->new_orphan_branch) {
856 char *refname;
857
858 refname = mkpathdup("refs/heads/%s", opts->new_orphan_branch);
859 if (opts->new_branch_log &&
860 !should_autocreate_reflog(refname)) {
861 int ret;
862 struct strbuf err = STRBUF_INIT;
863
864 ret = safe_create_reflog(refname, 1, &err);
865 if (ret) {
866 fprintf(stderr, _("Can not do reflog for '%s': %s\n"),
867 opts->new_orphan_branch, err.buf);
868 strbuf_release(&err);
869 free(refname);
870 return;
871 }
872 strbuf_release(&err);
873 }
874 free(refname);
875 }
876 else
877 create_branch(the_repository,
878 opts->new_branch, new_branch_info->name,
879 opts->new_branch_force ? 1 : 0,
880 opts->new_branch_force ? 1 : 0,
881 opts->new_branch_log,
882 opts->quiet,
883 opts->track);
884 new_branch_info->name = opts->new_branch;
885 setup_branch_path(new_branch_info);
886 }
887
888 old_desc = old_branch_info->name;
889 if (!old_desc && old_branch_info->commit)
890 old_desc = oid_to_hex(&old_branch_info->commit->object.oid);
891
892 reflog_msg = getenv("GIT_REFLOG_ACTION");
893 if (!reflog_msg)
894 strbuf_addf(&msg, "checkout: moving from %s to %s",
895 old_desc ? old_desc : "(invalid)", new_branch_info->name);
896 else
897 strbuf_insertstr(&msg, 0, reflog_msg);
898
899 if (!strcmp(new_branch_info->name, "HEAD") && !new_branch_info->path && !opts->force_detach) {
900 /* Nothing to do. */
901 } else if (opts->force_detach || !new_branch_info->path) { /* No longer on any branch. */
902 update_ref(msg.buf, "HEAD", &new_branch_info->commit->object.oid, NULL,
903 REF_NO_DEREF, UPDATE_REFS_DIE_ON_ERR);
904 if (!opts->quiet) {
905 if (old_branch_info->path &&
906 advice_detached_head && !opts->force_detach)
907 detach_advice(new_branch_info->name);
908 describe_detached_head(_("HEAD is now at"), new_branch_info->commit);
909 }
910 } else if (new_branch_info->path) { /* Switch branches. */
911 if (create_symref("HEAD", new_branch_info->path, msg.buf) < 0)
912 die(_("unable to update HEAD"));
913 if (!opts->quiet) {
914 if (old_branch_info->path && !strcmp(new_branch_info->path, old_branch_info->path)) {
915 if (opts->new_branch_force)
916 fprintf(stderr, _("Reset branch '%s'\n"),
917 new_branch_info->name);
918 else
919 fprintf(stderr, _("Already on '%s'\n"),
920 new_branch_info->name);
921 } else if (opts->new_branch) {
922 if (opts->branch_exists)
923 fprintf(stderr, _("Switched to and reset branch '%s'\n"), new_branch_info->name);
924 else
925 fprintf(stderr, _("Switched to a new branch '%s'\n"), new_branch_info->name);
926 } else {
927 fprintf(stderr, _("Switched to branch '%s'\n"),
928 new_branch_info->name);
929 }
930 }
931 if (old_branch_info->path && old_branch_info->name) {
932 if (!ref_exists(old_branch_info->path) && reflog_exists(old_branch_info->path))
933 delete_reflog(old_branch_info->path);
934 }
935 }
936 remove_branch_state(the_repository, !opts->quiet);
937 strbuf_release(&msg);
938 if (!opts->quiet &&
939 (new_branch_info->path || (!opts->force_detach && !strcmp(new_branch_info->name, "HEAD"))))
940 report_tracking(new_branch_info);
941 }
942
943 static int add_pending_uninteresting_ref(const char *refname,
944 const struct object_id *oid,
945 int flags, void *cb_data)
946 {
947 add_pending_oid(cb_data, refname, oid, UNINTERESTING);
948 return 0;
949 }
950
951 static void describe_one_orphan(struct strbuf *sb, struct commit *commit)
952 {
953 strbuf_addstr(sb, " ");
954 strbuf_add_unique_abbrev(sb, &commit->object.oid, DEFAULT_ABBREV);
955 strbuf_addch(sb, ' ');
956 if (!parse_commit(commit))
957 pp_commit_easy(CMIT_FMT_ONELINE, commit, sb);
958 strbuf_addch(sb, '\n');
959 }
960
961 #define ORPHAN_CUTOFF 4
962 static void suggest_reattach(struct commit *commit, struct rev_info *revs)
963 {
964 struct commit *c, *last = NULL;
965 struct strbuf sb = STRBUF_INIT;
966 int lost = 0;
967 while ((c = get_revision(revs)) != NULL) {
968 if (lost < ORPHAN_CUTOFF)
969 describe_one_orphan(&sb, c);
970 last = c;
971 lost++;
972 }
973 if (ORPHAN_CUTOFF < lost) {
974 int more = lost - ORPHAN_CUTOFF;
975 if (more == 1)
976 describe_one_orphan(&sb, last);
977 else
978 strbuf_addf(&sb, _(" ... and %d more.\n"), more);
979 }
980
981 fprintf(stderr,
982 Q_(
983 /* The singular version */
984 "Warning: you are leaving %d commit behind, "
985 "not connected to\n"
986 "any of your branches:\n\n"
987 "%s\n",
988 /* The plural version */
989 "Warning: you are leaving %d commits behind, "
990 "not connected to\n"
991 "any of your branches:\n\n"
992 "%s\n",
993 /* Give ngettext() the count */
994 lost),
995 lost,
996 sb.buf);
997 strbuf_release(&sb);
998
999 if (advice_detached_head)
1000 fprintf(stderr,
1001 Q_(
1002 /* The singular version */
1003 "If you want to keep it by creating a new branch, "
1004 "this may be a good time\nto do so with:\n\n"
1005 " git branch <new-branch-name> %s\n\n",
1006 /* The plural version */
1007 "If you want to keep them by creating a new branch, "
1008 "this may be a good time\nto do so with:\n\n"
1009 " git branch <new-branch-name> %s\n\n",
1010 /* Give ngettext() the count */
1011 lost),
1012 find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV));
1013 }
1014
1015 /*
1016 * We are about to leave commit that was at the tip of a detached
1017 * HEAD. If it is not reachable from any ref, this is the last chance
1018 * for the user to do so without resorting to reflog.
1019 */
1020 static void orphaned_commit_warning(struct commit *old_commit, struct commit *new_commit)
1021 {
1022 struct rev_info revs;
1023 struct object *object = &old_commit->object;
1024
1025 repo_init_revisions(the_repository, &revs, NULL);
1026 setup_revisions(0, NULL, &revs, NULL);
1027
1028 object->flags &= ~UNINTERESTING;
1029 add_pending_object(&revs, object, oid_to_hex(&object->oid));
1030
1031 for_each_ref(add_pending_uninteresting_ref, &revs);
1032 if (new_commit)
1033 add_pending_oid(&revs, "HEAD",
1034 &new_commit->object.oid,
1035 UNINTERESTING);
1036
1037 if (prepare_revision_walk(&revs))
1038 die(_("internal error in revision walk"));
1039 if (!(old_commit->object.flags & UNINTERESTING))
1040 suggest_reattach(old_commit, &revs);
1041 else
1042 describe_detached_head(_("Previous HEAD position was"), old_commit);
1043
1044 /* Clean up objects used, as they will be reused. */
1045 clear_commit_marks_all(ALL_REV_FLAGS);
1046 }
1047
1048 static int switch_branches(const struct checkout_opts *opts,
1049 struct branch_info *new_branch_info)
1050 {
1051 int ret = 0;
1052 struct branch_info old_branch_info;
1053 void *path_to_free;
1054 struct object_id rev;
1055 int flag, writeout_error = 0;
1056 int do_merge = 1;
1057
1058 trace2_cmd_mode("branch");
1059
1060 memset(&old_branch_info, 0, sizeof(old_branch_info));
1061 old_branch_info.path = path_to_free = resolve_refdup("HEAD", 0, &rev, &flag);
1062 if (old_branch_info.path)
1063 old_branch_info.commit = lookup_commit_reference_gently(the_repository, &rev, 1);
1064 if (!(flag & REF_ISSYMREF))
1065 old_branch_info.path = NULL;
1066
1067 if (old_branch_info.path)
1068 skip_prefix(old_branch_info.path, "refs/heads/", &old_branch_info.name);
1069
1070 if (opts->new_orphan_branch && opts->orphan_from_empty_tree) {
1071 if (new_branch_info->name)
1072 BUG("'switch --orphan' should never accept a commit as starting point");
1073 new_branch_info->commit = NULL;
1074 new_branch_info->name = "(empty)";
1075 do_merge = 1;
1076 }
1077
1078 if (!new_branch_info->name) {
1079 new_branch_info->name = "HEAD";
1080 new_branch_info->commit = old_branch_info.commit;
1081 if (!new_branch_info->commit)
1082 die(_("You are on a branch yet to be born"));
1083 parse_commit_or_die(new_branch_info->commit);
1084
1085 if (opts->only_merge_on_switching_branches)
1086 do_merge = 0;
1087 }
1088
1089 if (do_merge) {
1090 ret = merge_working_tree(opts, &old_branch_info, new_branch_info, &writeout_error);
1091 if (ret) {
1092 free(path_to_free);
1093 return ret;
1094 }
1095 }
1096
1097 if (!opts->quiet && !old_branch_info.path && old_branch_info.commit && new_branch_info->commit != old_branch_info.commit)
1098 orphaned_commit_warning(old_branch_info.commit, new_branch_info->commit);
1099
1100 update_refs_for_switch(opts, &old_branch_info, new_branch_info);
1101
1102 ret = post_checkout_hook(old_branch_info.commit, new_branch_info->commit, 1);
1103 free(path_to_free);
1104 return ret || writeout_error;
1105 }
1106
1107 static int git_checkout_config(const char *var, const char *value, void *cb)
1108 {
1109 if (!strcmp(var, "diff.ignoresubmodules")) {
1110 struct checkout_opts *opts = cb;
1111 handle_ignore_submodules_arg(&opts->diff_options, value);
1112 return 0;
1113 }
1114
1115 if (starts_with(var, "submodule."))
1116 return git_default_submodule_config(var, value, NULL);
1117
1118 return git_xmerge_config(var, value, NULL);
1119 }
1120
1121 static void setup_new_branch_info_and_source_tree(
1122 struct branch_info *new_branch_info,
1123 struct checkout_opts *opts,
1124 struct object_id *rev,
1125 const char *arg)
1126 {
1127 struct tree **source_tree = &opts->source_tree;
1128 struct object_id branch_rev;
1129
1130 new_branch_info->name = arg;
1131 setup_branch_path(new_branch_info);
1132
1133 if (!check_refname_format(new_branch_info->path, 0) &&
1134 !read_ref(new_branch_info->path, &branch_rev))
1135 oidcpy(rev, &branch_rev);
1136 else {
1137 free((char *)new_branch_info->path);
1138 new_branch_info->path = NULL; /* not an existing branch */
1139 }
1140
1141 new_branch_info->commit = lookup_commit_reference_gently(the_repository, rev, 1);
1142 if (!new_branch_info->commit) {
1143 /* not a commit */
1144 *source_tree = parse_tree_indirect(rev);
1145 } else {
1146 parse_commit_or_die(new_branch_info->commit);
1147 *source_tree = get_commit_tree(new_branch_info->commit);
1148 }
1149 }
1150
1151 static const char *parse_remote_branch(const char *arg,
1152 struct object_id *rev,
1153 int could_be_checkout_paths)
1154 {
1155 int num_matches = 0;
1156 const char *remote = unique_tracking_name(arg, rev, &num_matches);
1157
1158 if (remote && could_be_checkout_paths) {
1159 die(_("'%s' could be both a local file and a tracking branch.\n"
1160 "Please use -- (and optionally --no-guess) to disambiguate"),
1161 arg);
1162 }
1163
1164 if (!remote && num_matches > 1) {
1165 if (advice_checkout_ambiguous_remote_branch_name) {
1166 advise(_("If you meant to check out a remote tracking branch on, e.g. 'origin',\n"
1167 "you can do so by fully qualifying the name with the --track option:\n"
1168 "\n"
1169 " git checkout --track origin/<name>\n"
1170 "\n"
1171 "If you'd like to always have checkouts of an ambiguous <name> prefer\n"
1172 "one remote, e.g. the 'origin' remote, consider setting\n"
1173 "checkout.defaultRemote=origin in your config."));
1174 }
1175
1176 die(_("'%s' matched multiple (%d) remote tracking branches"),
1177 arg, num_matches);
1178 }
1179
1180 return remote;
1181 }
1182
1183 static int parse_branchname_arg(int argc, const char **argv,
1184 int dwim_new_local_branch_ok,
1185 struct branch_info *new_branch_info,
1186 struct checkout_opts *opts,
1187 struct object_id *rev)
1188 {
1189 const char **new_branch = &opts->new_branch;
1190 int argcount = 0;
1191 const char *arg;
1192 int dash_dash_pos;
1193 int has_dash_dash = 0;
1194 int i;
1195
1196 /*
1197 * case 1: git checkout <ref> -- [<paths>]
1198 *
1199 * <ref> must be a valid tree, everything after the '--' must be
1200 * a path.
1201 *
1202 * case 2: git checkout -- [<paths>]
1203 *
1204 * everything after the '--' must be paths.
1205 *
1206 * case 3: git checkout <something> [--]
1207 *
1208 * (a) If <something> is a commit, that is to
1209 * switch to the branch or detach HEAD at it. As a special case,
1210 * if <something> is A...B (missing A or B means HEAD but you can
1211 * omit at most one side), and if there is a unique merge base
1212 * between A and B, A...B names that merge base.
1213 *
1214 * (b) If <something> is _not_ a commit, either "--" is present
1215 * or <something> is not a path, no -t or -b was given, and
1216 * and there is a tracking branch whose name is <something>
1217 * in one and only one remote (or if the branch exists on the
1218 * remote named in checkout.defaultRemote), then this is a
1219 * short-hand to fork local <something> from that
1220 * remote-tracking branch.
1221 *
1222 * (c) Otherwise, if "--" is present, treat it like case (1).
1223 *
1224 * (d) Otherwise :
1225 * - if it's a reference, treat it like case (1)
1226 * - else if it's a path, treat it like case (2)
1227 * - else: fail.
1228 *
1229 * case 4: git checkout <something> <paths>
1230 *
1231 * The first argument must not be ambiguous.
1232 * - If it's *only* a reference, treat it like case (1).
1233 * - If it's only a path, treat it like case (2).
1234 * - else: fail.
1235 *
1236 */
1237 if (!argc)
1238 return 0;
1239
1240 if (!opts->accept_pathspec) {
1241 if (argc > 1)
1242 die(_("only one reference expected"));
1243 has_dash_dash = 1; /* helps disambiguate */
1244 }
1245
1246 arg = argv[0];
1247 dash_dash_pos = -1;
1248 for (i = 0; i < argc; i++) {
1249 if (opts->accept_pathspec && !strcmp(argv[i], "--")) {
1250 dash_dash_pos = i;
1251 break;
1252 }
1253 }
1254 if (dash_dash_pos == 0)
1255 return 1; /* case (2) */
1256 else if (dash_dash_pos == 1)
1257 has_dash_dash = 1; /* case (3) or (1) */
1258 else if (dash_dash_pos >= 2)
1259 die(_("only one reference expected, %d given."), dash_dash_pos);
1260 opts->count_checkout_paths = !opts->quiet && !has_dash_dash;
1261
1262 if (!strcmp(arg, "-"))
1263 arg = "@{-1}";
1264
1265 if (get_oid_mb(arg, rev)) {
1266 /*
1267 * Either case (3) or (4), with <something> not being
1268 * a commit, or an attempt to use case (1) with an
1269 * invalid ref.
1270 *
1271 * It's likely an error, but we need to find out if
1272 * we should auto-create the branch, case (3).(b).
1273 */
1274 int recover_with_dwim = dwim_new_local_branch_ok;
1275
1276 int could_be_checkout_paths = !has_dash_dash &&
1277 check_filename(opts->prefix, arg);
1278
1279 if (!has_dash_dash && !no_wildcard(arg))
1280 recover_with_dwim = 0;
1281
1282 /*
1283 * Accept "git checkout foo", "git checkout foo --"
1284 * and "git switch foo" as candidates for dwim.
1285 */
1286 if (!(argc == 1 && !has_dash_dash) &&
1287 !(argc == 2 && has_dash_dash) &&
1288 opts->accept_pathspec)
1289 recover_with_dwim = 0;
1290
1291 if (recover_with_dwim) {
1292 const char *remote = parse_remote_branch(arg, rev,
1293 could_be_checkout_paths);
1294 if (remote) {
1295 *new_branch = arg;
1296 arg = remote;
1297 /* DWIMmed to create local branch, case (3).(b) */
1298 } else {
1299 recover_with_dwim = 0;
1300 }
1301 }
1302
1303 if (!recover_with_dwim) {
1304 if (has_dash_dash)
1305 die(_("invalid reference: %s"), arg);
1306 return argcount;
1307 }
1308 }
1309
1310 /* we can't end up being in (2) anymore, eat the argument */
1311 argcount++;
1312 argv++;
1313 argc--;
1314
1315 setup_new_branch_info_and_source_tree(new_branch_info, opts, rev, arg);
1316
1317 if (!opts->source_tree) /* case (1): want a tree */
1318 die(_("reference is not a tree: %s"), arg);
1319
1320 if (!has_dash_dash) { /* case (3).(d) -> (1) */
1321 /*
1322 * Do not complain the most common case
1323 * git checkout branch
1324 * even if there happen to be a file called 'branch';
1325 * it would be extremely annoying.
1326 */
1327 if (argc)
1328 verify_non_filename(opts->prefix, arg);
1329 } else if (opts->accept_pathspec) {
1330 argcount++;
1331 argv++;
1332 argc--;
1333 }
1334
1335 return argcount;
1336 }
1337
1338 static int switch_unborn_to_new_branch(const struct checkout_opts *opts)
1339 {
1340 int status;
1341 struct strbuf branch_ref = STRBUF_INIT;
1342
1343 trace2_cmd_mode("unborn");
1344
1345 if (!opts->new_branch)
1346 die(_("You are on a branch yet to be born"));
1347 strbuf_addf(&branch_ref, "refs/heads/%s", opts->new_branch);
1348 status = create_symref("HEAD", branch_ref.buf, "checkout -b");
1349 strbuf_release(&branch_ref);
1350 if (!opts->quiet)
1351 fprintf(stderr, _("Switched to a new branch '%s'\n"),
1352 opts->new_branch);
1353 return status;
1354 }
1355
1356 static void die_expecting_a_branch(const struct branch_info *branch_info)
1357 {
1358 struct object_id oid;
1359 char *to_free;
1360
1361 if (dwim_ref(branch_info->name, strlen(branch_info->name), &oid, &to_free, 0) == 1) {
1362 const char *ref = to_free;
1363
1364 if (skip_prefix(ref, "refs/tags/", &ref))
1365 die(_("a branch is expected, got tag '%s'"), ref);
1366 if (skip_prefix(ref, "refs/remotes/", &ref))
1367 die(_("a branch is expected, got remote branch '%s'"), ref);
1368 die(_("a branch is expected, got '%s'"), ref);
1369 }
1370 if (branch_info->commit)
1371 die(_("a branch is expected, got commit '%s'"), branch_info->name);
1372 /*
1373 * This case should never happen because we already die() on
1374 * non-commit, but just in case.
1375 */
1376 die(_("a branch is expected, got '%s'"), branch_info->name);
1377 }
1378
1379 static void die_if_some_operation_in_progress(void)
1380 {
1381 struct wt_status_state state;
1382
1383 memset(&state, 0, sizeof(state));
1384 wt_status_get_state(the_repository, &state, 0);
1385
1386 if (state.merge_in_progress)
1387 die(_("cannot switch branch while merging\n"
1388 "Consider \"git merge --quit\" "
1389 "or \"git worktree add\"."));
1390 if (state.am_in_progress)
1391 die(_("cannot switch branch in the middle of an am session\n"
1392 "Consider \"git am --quit\" "
1393 "or \"git worktree add\"."));
1394 if (state.rebase_interactive_in_progress || state.rebase_in_progress)
1395 die(_("cannot switch branch while rebasing\n"
1396 "Consider \"git rebase --quit\" "
1397 "or \"git worktree add\"."));
1398 if (state.cherry_pick_in_progress)
1399 die(_("cannot switch branch while cherry-picking\n"
1400 "Consider \"git cherry-pick --quit\" "
1401 "or \"git worktree add\"."));
1402 if (state.revert_in_progress)
1403 die(_("cannot switch branch while reverting\n"
1404 "Consider \"git revert --quit\" "
1405 "or \"git worktree add\"."));
1406 if (state.bisect_in_progress)
1407 warning(_("you are switching branch while bisecting"));
1408 }
1409
1410 static int checkout_branch(struct checkout_opts *opts,
1411 struct branch_info *new_branch_info)
1412 {
1413 if (opts->pathspec.nr)
1414 die(_("paths cannot be used with switching branches"));
1415
1416 if (opts->patch_mode)
1417 die(_("'%s' cannot be used with switching branches"),
1418 "--patch");
1419
1420 if (opts->overlay_mode != -1)
1421 die(_("'%s' cannot be used with switching branches"),
1422 "--[no]-overlay");
1423
1424 if (opts->writeout_stage)
1425 die(_("'%s' cannot be used with switching branches"),
1426 "--ours/--theirs");
1427
1428 if (opts->force && opts->merge)
1429 die(_("'%s' cannot be used with '%s'"), "-f", "-m");
1430
1431 if (opts->discard_changes && opts->merge)
1432 die(_("'%s' cannot be used with '%s'"), "--discard-changes", "--merge");
1433
1434 if (opts->force_detach && opts->new_branch)
1435 die(_("'%s' cannot be used with '%s'"),
1436 "--detach", "-b/-B/--orphan");
1437
1438 if (opts->new_orphan_branch) {
1439 if (opts->track != BRANCH_TRACK_UNSPECIFIED)
1440 die(_("'%s' cannot be used with '%s'"), "--orphan", "-t");
1441 if (opts->orphan_from_empty_tree && new_branch_info->name)
1442 die(_("'%s' cannot take <start-point>"), "--orphan");
1443 } else if (opts->force_detach) {
1444 if (opts->track != BRANCH_TRACK_UNSPECIFIED)
1445 die(_("'%s' cannot be used with '%s'"), "--detach", "-t");
1446 } else if (opts->track == BRANCH_TRACK_UNSPECIFIED)
1447 opts->track = git_branch_track;
1448
1449 if (new_branch_info->name && !new_branch_info->commit)
1450 die(_("Cannot switch branch to a non-commit '%s'"),
1451 new_branch_info->name);
1452
1453 if (!opts->switch_branch_doing_nothing_is_ok &&
1454 !new_branch_info->name &&
1455 !opts->new_branch &&
1456 !opts->force_detach)
1457 die(_("missing branch or commit argument"));
1458
1459 if (!opts->implicit_detach &&
1460 !opts->force_detach &&
1461 !opts->new_branch &&
1462 !opts->new_branch_force &&
1463 new_branch_info->name &&
1464 !new_branch_info->path)
1465 die_expecting_a_branch(new_branch_info);
1466
1467 if (!opts->can_switch_when_in_progress)
1468 die_if_some_operation_in_progress();
1469
1470 if (new_branch_info->path && !opts->force_detach && !opts->new_branch &&
1471 !opts->ignore_other_worktrees) {
1472 int flag;
1473 char *head_ref = resolve_refdup("HEAD", 0, NULL, &flag);
1474 if (head_ref &&
1475 (!(flag & REF_ISSYMREF) || strcmp(head_ref, new_branch_info->path)))
1476 die_if_checked_out(new_branch_info->path, 1);
1477 free(head_ref);
1478 }
1479
1480 if (!new_branch_info->commit && opts->new_branch) {
1481 struct object_id rev;
1482 int flag;
1483
1484 if (!read_ref_full("HEAD", 0, &rev, &flag) &&
1485 (flag & REF_ISSYMREF) && is_null_oid(&rev))
1486 return switch_unborn_to_new_branch(opts);
1487 }
1488 return switch_branches(opts, new_branch_info);
1489 }
1490
1491 static struct option *add_common_options(struct checkout_opts *opts,
1492 struct option *prevopts)
1493 {
1494 struct option options[] = {
1495 OPT__QUIET(&opts->quiet, N_("suppress progress reporting")),
1496 OPT_CALLBACK_F(0, "recurse-submodules", NULL,
1497 "checkout", "control recursive updating of submodules",
1498 PARSE_OPT_OPTARG, option_parse_recurse_submodules_worktree_updater),
1499 OPT_BOOL(0, "progress", &opts->show_progress, N_("force progress reporting")),
1500 OPT_BOOL('m', "merge", &opts->merge, N_("perform a 3-way merge with the new branch")),
1501 OPT_STRING(0, "conflict", &opts->conflict_style, N_("style"),
1502 N_("conflict style (merge or diff3)")),
1503 OPT_END()
1504 };
1505 struct option *newopts = parse_options_concat(prevopts, options);
1506 free(prevopts);
1507 return newopts;
1508 }
1509
1510 static struct option *add_common_switch_branch_options(
1511 struct checkout_opts *opts, struct option *prevopts)
1512 {
1513 struct option options[] = {
1514 OPT_BOOL('d', "detach", &opts->force_detach, N_("detach HEAD at named commit")),
1515 OPT_SET_INT('t', "track", &opts->track, N_("set upstream info for new branch"),
1516 BRANCH_TRACK_EXPLICIT),
1517 OPT__FORCE(&opts->force, N_("force checkout (throw away local modifications)"),
1518 PARSE_OPT_NOCOMPLETE),
1519 OPT_STRING(0, "orphan", &opts->new_orphan_branch, N_("new-branch"), N_("new unparented branch")),
1520 OPT_BOOL_F(0, "overwrite-ignore", &opts->overwrite_ignore,
1521 N_("update ignored files (default)"),
1522 PARSE_OPT_NOCOMPLETE),
1523 OPT_BOOL(0, "ignore-other-worktrees", &opts->ignore_other_worktrees,
1524 N_("do not check if another worktree is holding the given ref")),
1525 OPT_END()
1526 };
1527 struct option *newopts = parse_options_concat(prevopts, options);
1528 free(prevopts);
1529 return newopts;
1530 }
1531
1532 static struct option *add_checkout_path_options(struct checkout_opts *opts,
1533 struct option *prevopts)
1534 {
1535 struct option options[] = {
1536 OPT_SET_INT_F('2', "ours", &opts->writeout_stage,
1537 N_("checkout our version for unmerged files"),
1538 2, PARSE_OPT_NONEG),
1539 OPT_SET_INT_F('3', "theirs", &opts->writeout_stage,
1540 N_("checkout their version for unmerged files"),
1541 3, PARSE_OPT_NONEG),
1542 OPT_BOOL('p', "patch", &opts->patch_mode, N_("select hunks interactively")),
1543 OPT_BOOL(0, "ignore-skip-worktree-bits", &opts->ignore_skipworktree,
1544 N_("do not limit pathspecs to sparse entries only")),
1545 OPT_PATHSPEC_FROM_FILE(&opts->pathspec_from_file),
1546 OPT_PATHSPEC_FILE_NUL(&opts->pathspec_file_nul),
1547 OPT_END()
1548 };
1549 struct option *newopts = parse_options_concat(prevopts, options);
1550 free(prevopts);
1551 return newopts;
1552 }
1553
1554 /* create-branch option (either b or c) */
1555 static char cb_option = 'b';
1556
1557 static int checkout_main(int argc, const char **argv, const char *prefix,
1558 struct checkout_opts *opts, struct option *options,
1559 const char * const usagestr[])
1560 {
1561 struct branch_info new_branch_info;
1562 int parseopt_flags = 0;
1563
1564 memset(&new_branch_info, 0, sizeof(new_branch_info));
1565 opts->overwrite_ignore = 1;
1566 opts->prefix = prefix;
1567 opts->show_progress = -1;
1568
1569 git_config(git_checkout_config, opts);
1570
1571 opts->track = BRANCH_TRACK_UNSPECIFIED;
1572
1573 if (!opts->accept_pathspec && !opts->accept_ref)
1574 BUG("make up your mind, you need to take _something_");
1575 if (opts->accept_pathspec && opts->accept_ref)
1576 parseopt_flags = PARSE_OPT_KEEP_DASHDASH;
1577
1578 argc = parse_options(argc, argv, prefix, options,
1579 usagestr, parseopt_flags);
1580
1581 if (opts->show_progress < 0) {
1582 if (opts->quiet)
1583 opts->show_progress = 0;
1584 else
1585 opts->show_progress = isatty(2);
1586 }
1587
1588 if (opts->conflict_style) {
1589 opts->merge = 1; /* implied */
1590 git_xmerge_config("merge.conflictstyle", opts->conflict_style, NULL);
1591 }
1592 if (opts->force) {
1593 opts->discard_changes = 1;
1594 opts->ignore_unmerged_opt = "--force";
1595 opts->ignore_unmerged = 1;
1596 }
1597
1598 if ((!!opts->new_branch + !!opts->new_branch_force + !!opts->new_orphan_branch) > 1)
1599 die(_("-%c, -%c and --orphan are mutually exclusive"),
1600 cb_option, toupper(cb_option));
1601
1602 if (opts->overlay_mode == 1 && opts->patch_mode)
1603 die(_("-p and --overlay are mutually exclusive"));
1604
1605 if (opts->checkout_index >= 0 || opts->checkout_worktree >= 0) {
1606 if (opts->checkout_index < 0)
1607 opts->checkout_index = 0;
1608 if (opts->checkout_worktree < 0)
1609 opts->checkout_worktree = 0;
1610 } else {
1611 if (opts->checkout_index < 0)
1612 opts->checkout_index = -opts->checkout_index - 1;
1613 if (opts->checkout_worktree < 0)
1614 opts->checkout_worktree = -opts->checkout_worktree - 1;
1615 }
1616 if (opts->checkout_index < 0 || opts->checkout_worktree < 0)
1617 BUG("these flags should be non-negative by now");
1618 /*
1619 * convenient shortcut: "git restore --staged [--worktree]" equals
1620 * "git restore --staged [--worktree] --source HEAD"
1621 */
1622 if (!opts->from_treeish && opts->checkout_index)
1623 opts->from_treeish = "HEAD";
1624
1625 /*
1626 * From here on, new_branch will contain the branch to be checked out,
1627 * and new_branch_force and new_orphan_branch will tell us which one of
1628 * -b/-B/-c/-C/--orphan is being used.
1629 */
1630 if (opts->new_branch_force)
1631 opts->new_branch = opts->new_branch_force;
1632
1633 if (opts->new_orphan_branch)
1634 opts->new_branch = opts->new_orphan_branch;
1635
1636 /* --track without -c/-C/-b/-B/--orphan should DWIM */
1637 if (opts->track != BRANCH_TRACK_UNSPECIFIED && !opts->new_branch) {
1638 const char *argv0 = argv[0];
1639 if (!argc || !strcmp(argv0, "--"))
1640 die(_("--track needs a branch name"));
1641 skip_prefix(argv0, "refs/", &argv0);
1642 skip_prefix(argv0, "remotes/", &argv0);
1643 argv0 = strchr(argv0, '/');
1644 if (!argv0 || !argv0[1])
1645 die(_("missing branch name; try -%c"), cb_option);
1646 opts->new_branch = argv0 + 1;
1647 }
1648
1649 /*
1650 * Extract branch name from command line arguments, so
1651 * all that is left is pathspecs.
1652 *
1653 * Handle
1654 *
1655 * 1) git checkout <tree> -- [<paths>]
1656 * 2) git checkout -- [<paths>]
1657 * 3) git checkout <something> [<paths>]
1658 *
1659 * including "last branch" syntax and DWIM-ery for names of
1660 * remote branches, erroring out for invalid or ambiguous cases.
1661 */
1662 if (argc && opts->accept_ref) {
1663 struct object_id rev;
1664 int dwim_ok =
1665 !opts->patch_mode &&
1666 opts->dwim_new_local_branch &&
1667 opts->track == BRANCH_TRACK_UNSPECIFIED &&
1668 !opts->new_branch;
1669 int n = parse_branchname_arg(argc, argv, dwim_ok,
1670 &new_branch_info, opts, &rev);
1671 argv += n;
1672 argc -= n;
1673 } else if (!opts->accept_ref && opts->from_treeish) {
1674 struct object_id rev;
1675
1676 if (get_oid_mb(opts->from_treeish, &rev))
1677 die(_("could not resolve %s"), opts->from_treeish);
1678
1679 setup_new_branch_info_and_source_tree(&new_branch_info,
1680 opts, &rev,
1681 opts->from_treeish);
1682
1683 if (!opts->source_tree)
1684 die(_("reference is not a tree: %s"), opts->from_treeish);
1685 }
1686
1687 if (argc) {
1688 parse_pathspec(&opts->pathspec, 0,
1689 opts->patch_mode ? PATHSPEC_PREFIX_ORIGIN : 0,
1690 prefix, argv);
1691
1692 if (!opts->pathspec.nr)
1693 die(_("invalid path specification"));
1694
1695 /*
1696 * Try to give more helpful suggestion.
1697 * new_branch && argc > 1 will be caught later.
1698 */
1699 if (opts->new_branch && argc == 1 && !new_branch_info.commit)
1700 die(_("'%s' is not a commit and a branch '%s' cannot be created from it"),
1701 argv[0], opts->new_branch);
1702
1703 if (opts->force_detach)
1704 die(_("git checkout: --detach does not take a path argument '%s'"),
1705 argv[0]);
1706 }
1707
1708 if (opts->pathspec_from_file) {
1709 if (opts->pathspec.nr)
1710 die(_("--pathspec-from-file is incompatible with pathspec arguments"));
1711
1712 if (opts->force_detach)
1713 die(_("--pathspec-from-file is incompatible with --detach"));
1714
1715 if (opts->patch_mode)
1716 die(_("--pathspec-from-file is incompatible with --patch"));
1717
1718 parse_pathspec_file(&opts->pathspec, 0,
1719 0,
1720 prefix, opts->pathspec_from_file, opts->pathspec_file_nul);
1721 } else if (opts->pathspec_file_nul) {
1722 die(_("--pathspec-file-nul requires --pathspec-from-file"));
1723 }
1724
1725 opts->pathspec.recursive = 1;
1726
1727 if (opts->pathspec.nr) {
1728 if (1 < !!opts->writeout_stage + !!opts->force + !!opts->merge)
1729 die(_("git checkout: --ours/--theirs, --force and --merge are incompatible when\n"
1730 "checking out of the index."));
1731 } else {
1732 if (opts->accept_pathspec && !opts->empty_pathspec_ok &&
1733 !opts->patch_mode) /* patch mode is special */
1734 die(_("you must specify path(s) to restore"));
1735 }
1736
1737 if (opts->new_branch) {
1738 struct strbuf buf = STRBUF_INIT;
1739
1740 if (opts->new_branch_force)
1741 opts->branch_exists = validate_branchname(opts->new_branch, &buf);
1742 else
1743 opts->branch_exists =
1744 validate_new_branchname(opts->new_branch, &buf, 0);
1745 strbuf_release(&buf);
1746 }
1747
1748 UNLEAK(opts);
1749 if (opts->patch_mode || opts->pathspec.nr)
1750 return checkout_paths(opts, &new_branch_info);
1751 else
1752 return checkout_branch(opts, &new_branch_info);
1753 }
1754
1755 int cmd_checkout(int argc, const char **argv, const char *prefix)
1756 {
1757 struct checkout_opts opts;
1758 struct option *options;
1759 struct option checkout_options[] = {
1760 OPT_STRING('b', NULL, &opts.new_branch, N_("branch"),
1761 N_("create and checkout a new branch")),
1762 OPT_STRING('B', NULL, &opts.new_branch_force, N_("branch"),
1763 N_("create/reset and checkout a branch")),
1764 OPT_BOOL('l', NULL, &opts.new_branch_log, N_("create reflog for new branch")),
1765 OPT_BOOL(0, "guess", &opts.dwim_new_local_branch,
1766 N_("second guess 'git checkout <no-such-branch>' (default)")),
1767 OPT_BOOL(0, "overlay", &opts.overlay_mode, N_("use overlay mode (default)")),
1768 OPT_END()
1769 };
1770 int ret;
1771
1772 memset(&opts, 0, sizeof(opts));
1773 opts.dwim_new_local_branch = 1;
1774 opts.switch_branch_doing_nothing_is_ok = 1;
1775 opts.only_merge_on_switching_branches = 0;
1776 opts.accept_ref = 1;
1777 opts.accept_pathspec = 1;
1778 opts.implicit_detach = 1;
1779 opts.can_switch_when_in_progress = 1;
1780 opts.orphan_from_empty_tree = 0;
1781 opts.empty_pathspec_ok = 1;
1782 opts.overlay_mode = -1;
1783 opts.checkout_index = -2; /* default on */
1784 opts.checkout_worktree = -2; /* default on */
1785
1786 if (argc == 3 && !strcmp(argv[1], "-b")) {
1787 /*
1788 * User ran 'git checkout -b <branch>' and expects
1789 * the same behavior as 'git switch -c <branch>'.
1790 */
1791 opts.switch_branch_doing_nothing_is_ok = 0;
1792 opts.only_merge_on_switching_branches = 1;
1793 }
1794
1795 options = parse_options_dup(checkout_options);
1796 options = add_common_options(&opts, options);
1797 options = add_common_switch_branch_options(&opts, options);
1798 options = add_checkout_path_options(&opts, options);
1799
1800 ret = checkout_main(argc, argv, prefix, &opts,
1801 options, checkout_usage);
1802 FREE_AND_NULL(options);
1803 return ret;
1804 }
1805
1806 int cmd_switch(int argc, const char **argv, const char *prefix)
1807 {
1808 struct checkout_opts opts;
1809 struct option *options = NULL;
1810 struct option switch_options[] = {
1811 OPT_STRING('c', "create", &opts.new_branch, N_("branch"),
1812 N_("create and switch to a new branch")),
1813 OPT_STRING('C', "force-create", &opts.new_branch_force, N_("branch"),
1814 N_("create/reset and switch to a branch")),
1815 OPT_BOOL(0, "guess", &opts.dwim_new_local_branch,
1816 N_("second guess 'git switch <no-such-branch>'")),
1817 OPT_BOOL(0, "discard-changes", &opts.discard_changes,
1818 N_("throw away local modifications")),
1819 OPT_END()
1820 };
1821 int ret;
1822
1823 memset(&opts, 0, sizeof(opts));
1824 opts.dwim_new_local_branch = 1;
1825 opts.accept_ref = 1;
1826 opts.accept_pathspec = 0;
1827 opts.switch_branch_doing_nothing_is_ok = 0;
1828 opts.only_merge_on_switching_branches = 1;
1829 opts.implicit_detach = 0;
1830 opts.can_switch_when_in_progress = 0;
1831 opts.orphan_from_empty_tree = 1;
1832 opts.overlay_mode = -1;
1833
1834 options = parse_options_dup(switch_options);
1835 options = add_common_options(&opts, options);
1836 options = add_common_switch_branch_options(&opts, options);
1837
1838 cb_option = 'c';
1839
1840 ret = checkout_main(argc, argv, prefix, &opts,
1841 options, switch_branch_usage);
1842 FREE_AND_NULL(options);
1843 return ret;
1844 }
1845
1846 int cmd_restore(int argc, const char **argv, const char *prefix)
1847 {
1848 struct checkout_opts opts;
1849 struct option *options;
1850 struct option restore_options[] = {
1851 OPT_STRING('s', "source", &opts.from_treeish, "<tree-ish>",
1852 N_("which tree-ish to checkout from")),
1853 OPT_BOOL('S', "staged", &opts.checkout_index,
1854 N_("restore the index")),
1855 OPT_BOOL('W', "worktree", &opts.checkout_worktree,
1856 N_("restore the working tree (default)")),
1857 OPT_BOOL(0, "ignore-unmerged", &opts.ignore_unmerged,
1858 N_("ignore unmerged entries")),
1859 OPT_BOOL(0, "overlay", &opts.overlay_mode, N_("use overlay mode")),
1860 OPT_END()
1861 };
1862 int ret;
1863
1864 memset(&opts, 0, sizeof(opts));
1865 opts.accept_ref = 0;
1866 opts.accept_pathspec = 1;
1867 opts.empty_pathspec_ok = 0;
1868 opts.overlay_mode = 0;
1869 opts.checkout_index = -1; /* default off */
1870 opts.checkout_worktree = -2; /* default on */
1871 opts.ignore_unmerged_opt = "--ignore-unmerged";
1872
1873 options = parse_options_dup(restore_options);
1874 options = add_common_options(&opts, options);
1875 options = add_checkout_path_options(&opts, options);
1876
1877 ret = checkout_main(argc, argv, prefix, &opts,
1878 options, restore_usage);
1879 FREE_AND_NULL(options);
1880 return ret;
1881 }