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