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