]> git.ipfire.org Git - thirdparty/git.git/blob - builtin/checkout.c
hooks: convert non-worktree 'post-checkout' hook to hook library
[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(_("'%s' cannot be used with %s"), "--merge", "--patch");
469
470 if (opts->ignore_unmerged && opts->merge)
471 die(_("'%s' cannot be used with %s"),
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 else
1099 BUG("should be able to skip past '%s' in '%s'!",
1100 prefix, old_branch_info.path);
1101 }
1102
1103 if (opts->new_orphan_branch && opts->orphan_from_empty_tree) {
1104 if (new_branch_info->name)
1105 BUG("'switch --orphan' should never accept a commit as starting point");
1106 new_branch_info->commit = NULL;
1107 new_branch_info->name = xstrdup("(empty)");
1108 do_merge = 1;
1109 }
1110
1111 if (!new_branch_info->name) {
1112 new_branch_info->name = xstrdup("HEAD");
1113 new_branch_info->commit = old_branch_info.commit;
1114 if (!new_branch_info->commit)
1115 die(_("You are on a branch yet to be born"));
1116 parse_commit_or_die(new_branch_info->commit);
1117
1118 if (opts->only_merge_on_switching_branches)
1119 do_merge = 0;
1120 }
1121
1122 if (do_merge) {
1123 ret = merge_working_tree(opts, &old_branch_info, new_branch_info, &writeout_error);
1124 if (ret) {
1125 branch_info_release(&old_branch_info);
1126 return ret;
1127 }
1128 }
1129
1130 if (!opts->quiet && !old_branch_info.path && old_branch_info.commit && new_branch_info->commit != old_branch_info.commit)
1131 orphaned_commit_warning(old_branch_info.commit, new_branch_info->commit);
1132
1133 update_refs_for_switch(opts, &old_branch_info, new_branch_info);
1134
1135 ret = post_checkout_hook(old_branch_info.commit, new_branch_info->commit, 1);
1136 branch_info_release(&old_branch_info);
1137
1138 return ret || writeout_error;
1139 }
1140
1141 static int git_checkout_config(const char *var, const char *value, void *cb)
1142 {
1143 struct checkout_opts *opts = cb;
1144
1145 if (!strcmp(var, "diff.ignoresubmodules")) {
1146 handle_ignore_submodules_arg(&opts->diff_options, value);
1147 return 0;
1148 }
1149 if (!strcmp(var, "checkout.guess")) {
1150 opts->dwim_new_local_branch = git_config_bool(var, value);
1151 return 0;
1152 }
1153
1154 if (starts_with(var, "submodule."))
1155 return git_default_submodule_config(var, value, NULL);
1156
1157 return git_xmerge_config(var, value, NULL);
1158 }
1159
1160 static void setup_new_branch_info_and_source_tree(
1161 struct branch_info *new_branch_info,
1162 struct checkout_opts *opts,
1163 struct object_id *rev,
1164 const char *arg)
1165 {
1166 struct tree **source_tree = &opts->source_tree;
1167 struct object_id branch_rev;
1168
1169 new_branch_info->name = xstrdup(arg);
1170 setup_branch_path(new_branch_info);
1171
1172 if (!check_refname_format(new_branch_info->path, 0) &&
1173 !read_ref(new_branch_info->path, &branch_rev))
1174 oidcpy(rev, &branch_rev);
1175 else
1176 /* not an existing branch */
1177 FREE_AND_NULL(new_branch_info->path);
1178
1179 new_branch_info->commit = lookup_commit_reference_gently(the_repository, rev, 1);
1180 if (!new_branch_info->commit) {
1181 /* not a commit */
1182 *source_tree = parse_tree_indirect(rev);
1183 } else {
1184 parse_commit_or_die(new_branch_info->commit);
1185 *source_tree = get_commit_tree(new_branch_info->commit);
1186 }
1187 }
1188
1189 static const char *parse_remote_branch(const char *arg,
1190 struct object_id *rev,
1191 int could_be_checkout_paths)
1192 {
1193 int num_matches = 0;
1194 const char *remote = unique_tracking_name(arg, rev, &num_matches);
1195
1196 if (remote && could_be_checkout_paths) {
1197 die(_("'%s' could be both a local file and a tracking branch.\n"
1198 "Please use -- (and optionally --no-guess) to disambiguate"),
1199 arg);
1200 }
1201
1202 if (!remote && num_matches > 1) {
1203 if (advice_enabled(ADVICE_CHECKOUT_AMBIGUOUS_REMOTE_BRANCH_NAME)) {
1204 advise(_("If you meant to check out a remote tracking branch on, e.g. 'origin',\n"
1205 "you can do so by fully qualifying the name with the --track option:\n"
1206 "\n"
1207 " git checkout --track origin/<name>\n"
1208 "\n"
1209 "If you'd like to always have checkouts of an ambiguous <name> prefer\n"
1210 "one remote, e.g. the 'origin' remote, consider setting\n"
1211 "checkout.defaultRemote=origin in your config."));
1212 }
1213
1214 die(_("'%s' matched multiple (%d) remote tracking branches"),
1215 arg, num_matches);
1216 }
1217
1218 return remote;
1219 }
1220
1221 static int parse_branchname_arg(int argc, const char **argv,
1222 int dwim_new_local_branch_ok,
1223 struct branch_info *new_branch_info,
1224 struct checkout_opts *opts,
1225 struct object_id *rev)
1226 {
1227 const char **new_branch = &opts->new_branch;
1228 int argcount = 0;
1229 const char *arg;
1230 int dash_dash_pos;
1231 int has_dash_dash = 0;
1232 int i;
1233
1234 /*
1235 * case 1: git checkout <ref> -- [<paths>]
1236 *
1237 * <ref> must be a valid tree, everything after the '--' must be
1238 * a path.
1239 *
1240 * case 2: git checkout -- [<paths>]
1241 *
1242 * everything after the '--' must be paths.
1243 *
1244 * case 3: git checkout <something> [--]
1245 *
1246 * (a) If <something> is a commit, that is to
1247 * switch to the branch or detach HEAD at it. As a special case,
1248 * if <something> is A...B (missing A or B means HEAD but you can
1249 * omit at most one side), and if there is a unique merge base
1250 * between A and B, A...B names that merge base.
1251 *
1252 * (b) If <something> is _not_ a commit, either "--" is present
1253 * or <something> is not a path, no -t or -b was given, and
1254 * and there is a tracking branch whose name is <something>
1255 * in one and only one remote (or if the branch exists on the
1256 * remote named in checkout.defaultRemote), then this is a
1257 * short-hand to fork local <something> from that
1258 * remote-tracking branch.
1259 *
1260 * (c) Otherwise, if "--" is present, treat it like case (1).
1261 *
1262 * (d) Otherwise :
1263 * - if it's a reference, treat it like case (1)
1264 * - else if it's a path, treat it like case (2)
1265 * - else: fail.
1266 *
1267 * case 4: git checkout <something> <paths>
1268 *
1269 * The first argument must not be ambiguous.
1270 * - If it's *only* a reference, treat it like case (1).
1271 * - If it's only a path, treat it like case (2).
1272 * - else: fail.
1273 *
1274 */
1275 if (!argc)
1276 return 0;
1277
1278 if (!opts->accept_pathspec) {
1279 if (argc > 1)
1280 die(_("only one reference expected"));
1281 has_dash_dash = 1; /* helps disambiguate */
1282 }
1283
1284 arg = argv[0];
1285 dash_dash_pos = -1;
1286 for (i = 0; i < argc; i++) {
1287 if (opts->accept_pathspec && !strcmp(argv[i], "--")) {
1288 dash_dash_pos = i;
1289 break;
1290 }
1291 }
1292 if (dash_dash_pos == 0)
1293 return 1; /* case (2) */
1294 else if (dash_dash_pos == 1)
1295 has_dash_dash = 1; /* case (3) or (1) */
1296 else if (dash_dash_pos >= 2)
1297 die(_("only one reference expected, %d given."), dash_dash_pos);
1298 opts->count_checkout_paths = !opts->quiet && !has_dash_dash;
1299
1300 if (!strcmp(arg, "-"))
1301 arg = "@{-1}";
1302
1303 if (get_oid_mb(arg, rev)) {
1304 /*
1305 * Either case (3) or (4), with <something> not being
1306 * a commit, or an attempt to use case (1) with an
1307 * invalid ref.
1308 *
1309 * It's likely an error, but we need to find out if
1310 * we should auto-create the branch, case (3).(b).
1311 */
1312 int recover_with_dwim = dwim_new_local_branch_ok;
1313
1314 int could_be_checkout_paths = !has_dash_dash &&
1315 check_filename(opts->prefix, arg);
1316
1317 if (!has_dash_dash && !no_wildcard(arg))
1318 recover_with_dwim = 0;
1319
1320 /*
1321 * Accept "git checkout foo", "git checkout foo --"
1322 * and "git switch foo" as candidates for dwim.
1323 */
1324 if (!(argc == 1 && !has_dash_dash) &&
1325 !(argc == 2 && has_dash_dash) &&
1326 opts->accept_pathspec)
1327 recover_with_dwim = 0;
1328
1329 if (recover_with_dwim) {
1330 const char *remote = parse_remote_branch(arg, rev,
1331 could_be_checkout_paths);
1332 if (remote) {
1333 *new_branch = arg;
1334 arg = remote;
1335 /* DWIMmed to create local branch, case (3).(b) */
1336 } else {
1337 recover_with_dwim = 0;
1338 }
1339 }
1340
1341 if (!recover_with_dwim) {
1342 if (has_dash_dash)
1343 die(_("invalid reference: %s"), arg);
1344 return argcount;
1345 }
1346 }
1347
1348 /* we can't end up being in (2) anymore, eat the argument */
1349 argcount++;
1350 argv++;
1351 argc--;
1352
1353 setup_new_branch_info_and_source_tree(new_branch_info, opts, rev, arg);
1354
1355 if (!opts->source_tree) /* case (1): want a tree */
1356 die(_("reference is not a tree: %s"), arg);
1357
1358 if (!has_dash_dash) { /* case (3).(d) -> (1) */
1359 /*
1360 * Do not complain the most common case
1361 * git checkout branch
1362 * even if there happen to be a file called 'branch';
1363 * it would be extremely annoying.
1364 */
1365 if (argc)
1366 verify_non_filename(opts->prefix, arg);
1367 } else if (opts->accept_pathspec) {
1368 argcount++;
1369 argv++;
1370 argc--;
1371 }
1372
1373 return argcount;
1374 }
1375
1376 static int switch_unborn_to_new_branch(const struct checkout_opts *opts)
1377 {
1378 int status;
1379 struct strbuf branch_ref = STRBUF_INIT;
1380
1381 trace2_cmd_mode("unborn");
1382
1383 if (!opts->new_branch)
1384 die(_("You are on a branch yet to be born"));
1385 strbuf_addf(&branch_ref, "refs/heads/%s", opts->new_branch);
1386 status = create_symref("HEAD", branch_ref.buf, "checkout -b");
1387 strbuf_release(&branch_ref);
1388 if (!opts->quiet)
1389 fprintf(stderr, _("Switched to a new branch '%s'\n"),
1390 opts->new_branch);
1391 return status;
1392 }
1393
1394 static void die_expecting_a_branch(const struct branch_info *branch_info)
1395 {
1396 struct object_id oid;
1397 char *to_free;
1398
1399 if (dwim_ref(branch_info->name, strlen(branch_info->name), &oid, &to_free, 0) == 1) {
1400 const char *ref = to_free;
1401
1402 if (skip_prefix(ref, "refs/tags/", &ref))
1403 die(_("a branch is expected, got tag '%s'"), ref);
1404 if (skip_prefix(ref, "refs/remotes/", &ref))
1405 die(_("a branch is expected, got remote branch '%s'"), ref);
1406 die(_("a branch is expected, got '%s'"), ref);
1407 }
1408 if (branch_info->commit)
1409 die(_("a branch is expected, got commit '%s'"), branch_info->name);
1410 /*
1411 * This case should never happen because we already die() on
1412 * non-commit, but just in case.
1413 */
1414 die(_("a branch is expected, got '%s'"), branch_info->name);
1415 }
1416
1417 static void die_if_some_operation_in_progress(void)
1418 {
1419 struct wt_status_state state;
1420
1421 memset(&state, 0, sizeof(state));
1422 wt_status_get_state(the_repository, &state, 0);
1423
1424 if (state.merge_in_progress)
1425 die(_("cannot switch branch while merging\n"
1426 "Consider \"git merge --quit\" "
1427 "or \"git worktree add\"."));
1428 if (state.am_in_progress)
1429 die(_("cannot switch branch in the middle of an am session\n"
1430 "Consider \"git am --quit\" "
1431 "or \"git worktree add\"."));
1432 if (state.rebase_interactive_in_progress || state.rebase_in_progress)
1433 die(_("cannot switch branch while rebasing\n"
1434 "Consider \"git rebase --quit\" "
1435 "or \"git worktree add\"."));
1436 if (state.cherry_pick_in_progress)
1437 die(_("cannot switch branch while cherry-picking\n"
1438 "Consider \"git cherry-pick --quit\" "
1439 "or \"git worktree add\"."));
1440 if (state.revert_in_progress)
1441 die(_("cannot switch branch while reverting\n"
1442 "Consider \"git revert --quit\" "
1443 "or \"git worktree add\"."));
1444 if (state.bisect_in_progress)
1445 warning(_("you are switching branch while bisecting"));
1446 }
1447
1448 static int checkout_branch(struct checkout_opts *opts,
1449 struct branch_info *new_branch_info)
1450 {
1451 if (opts->pathspec.nr)
1452 die(_("paths cannot be used with switching branches"));
1453
1454 if (opts->patch_mode)
1455 die(_("'%s' cannot be used with switching branches"),
1456 "--patch");
1457
1458 if (opts->overlay_mode != -1)
1459 die(_("'%s' cannot be used with switching branches"),
1460 "--[no]-overlay");
1461
1462 if (opts->writeout_stage)
1463 die(_("'%s' cannot be used with switching branches"),
1464 "--ours/--theirs");
1465
1466 if (opts->force && opts->merge)
1467 die(_("'%s' cannot be used with '%s'"), "-f", "-m");
1468
1469 if (opts->discard_changes && opts->merge)
1470 die(_("'%s' cannot be used with '%s'"), "--discard-changes", "--merge");
1471
1472 if (opts->force_detach && opts->new_branch)
1473 die(_("'%s' cannot be used with '%s'"),
1474 "--detach", "-b/-B/--orphan");
1475
1476 if (opts->new_orphan_branch) {
1477 if (opts->track != BRANCH_TRACK_UNSPECIFIED)
1478 die(_("'%s' cannot be used with '%s'"), "--orphan", "-t");
1479 if (opts->orphan_from_empty_tree && new_branch_info->name)
1480 die(_("'%s' cannot take <start-point>"), "--orphan");
1481 } else if (opts->force_detach) {
1482 if (opts->track != BRANCH_TRACK_UNSPECIFIED)
1483 die(_("'%s' cannot be used with '%s'"), "--detach", "-t");
1484 } else if (opts->track == BRANCH_TRACK_UNSPECIFIED)
1485 opts->track = git_branch_track;
1486
1487 if (new_branch_info->name && !new_branch_info->commit)
1488 die(_("Cannot switch branch to a non-commit '%s'"),
1489 new_branch_info->name);
1490
1491 if (!opts->switch_branch_doing_nothing_is_ok &&
1492 !new_branch_info->name &&
1493 !opts->new_branch &&
1494 !opts->force_detach)
1495 die(_("missing branch or commit argument"));
1496
1497 if (!opts->implicit_detach &&
1498 !opts->force_detach &&
1499 !opts->new_branch &&
1500 !opts->new_branch_force &&
1501 new_branch_info->name &&
1502 !new_branch_info->path)
1503 die_expecting_a_branch(new_branch_info);
1504
1505 if (!opts->can_switch_when_in_progress)
1506 die_if_some_operation_in_progress();
1507
1508 if (new_branch_info->path && !opts->force_detach && !opts->new_branch &&
1509 !opts->ignore_other_worktrees) {
1510 int flag;
1511 char *head_ref = resolve_refdup("HEAD", 0, NULL, &flag);
1512 if (head_ref &&
1513 (!(flag & REF_ISSYMREF) || strcmp(head_ref, new_branch_info->path)))
1514 die_if_checked_out(new_branch_info->path, 1);
1515 free(head_ref);
1516 }
1517
1518 if (!new_branch_info->commit && opts->new_branch) {
1519 struct object_id rev;
1520 int flag;
1521
1522 if (!read_ref_full("HEAD", 0, &rev, &flag) &&
1523 (flag & REF_ISSYMREF) && is_null_oid(&rev))
1524 return switch_unborn_to_new_branch(opts);
1525 }
1526 return switch_branches(opts, new_branch_info);
1527 }
1528
1529 static struct option *add_common_options(struct checkout_opts *opts,
1530 struct option *prevopts)
1531 {
1532 struct option options[] = {
1533 OPT__QUIET(&opts->quiet, N_("suppress progress reporting")),
1534 OPT_CALLBACK_F(0, "recurse-submodules", NULL,
1535 "checkout", "control recursive updating of submodules",
1536 PARSE_OPT_OPTARG, option_parse_recurse_submodules_worktree_updater),
1537 OPT_BOOL(0, "progress", &opts->show_progress, N_("force progress reporting")),
1538 OPT_BOOL('m', "merge", &opts->merge, N_("perform a 3-way merge with the new branch")),
1539 OPT_STRING(0, "conflict", &opts->conflict_style, N_("style"),
1540 N_("conflict style (merge, diff3, or zdiff3)")),
1541 OPT_END()
1542 };
1543 struct option *newopts = parse_options_concat(prevopts, options);
1544 free(prevopts);
1545 return newopts;
1546 }
1547
1548 static struct option *add_common_switch_branch_options(
1549 struct checkout_opts *opts, struct option *prevopts)
1550 {
1551 struct option options[] = {
1552 OPT_BOOL('d', "detach", &opts->force_detach, N_("detach HEAD at named commit")),
1553 OPT_SET_INT('t', "track", &opts->track, N_("set upstream info for new branch"),
1554 BRANCH_TRACK_EXPLICIT),
1555 OPT__FORCE(&opts->force, N_("force checkout (throw away local modifications)"),
1556 PARSE_OPT_NOCOMPLETE),
1557 OPT_STRING(0, "orphan", &opts->new_orphan_branch, N_("new-branch"), N_("new unparented branch")),
1558 OPT_BOOL_F(0, "overwrite-ignore", &opts->overwrite_ignore,
1559 N_("update ignored files (default)"),
1560 PARSE_OPT_NOCOMPLETE),
1561 OPT_BOOL(0, "ignore-other-worktrees", &opts->ignore_other_worktrees,
1562 N_("do not check if another worktree is holding the given ref")),
1563 OPT_END()
1564 };
1565 struct option *newopts = parse_options_concat(prevopts, options);
1566 free(prevopts);
1567 return newopts;
1568 }
1569
1570 static struct option *add_checkout_path_options(struct checkout_opts *opts,
1571 struct option *prevopts)
1572 {
1573 struct option options[] = {
1574 OPT_SET_INT_F('2', "ours", &opts->writeout_stage,
1575 N_("checkout our version for unmerged files"),
1576 2, PARSE_OPT_NONEG),
1577 OPT_SET_INT_F('3', "theirs", &opts->writeout_stage,
1578 N_("checkout their version for unmerged files"),
1579 3, PARSE_OPT_NONEG),
1580 OPT_BOOL('p', "patch", &opts->patch_mode, N_("select hunks interactively")),
1581 OPT_BOOL(0, "ignore-skip-worktree-bits", &opts->ignore_skipworktree,
1582 N_("do not limit pathspecs to sparse entries only")),
1583 OPT_PATHSPEC_FROM_FILE(&opts->pathspec_from_file),
1584 OPT_PATHSPEC_FILE_NUL(&opts->pathspec_file_nul),
1585 OPT_END()
1586 };
1587 struct option *newopts = parse_options_concat(prevopts, options);
1588 free(prevopts);
1589 return newopts;
1590 }
1591
1592 /* create-branch option (either b or c) */
1593 static char cb_option = 'b';
1594
1595 static int checkout_main(int argc, const char **argv, const char *prefix,
1596 struct checkout_opts *opts, struct option *options,
1597 const char * const usagestr[],
1598 struct branch_info *new_branch_info)
1599 {
1600 int parseopt_flags = 0;
1601
1602 opts->overwrite_ignore = 1;
1603 opts->prefix = prefix;
1604 opts->show_progress = -1;
1605
1606 git_config(git_checkout_config, opts);
1607
1608 prepare_repo_settings(the_repository);
1609 the_repository->settings.command_requires_full_index = 0;
1610
1611 opts->track = BRANCH_TRACK_UNSPECIFIED;
1612
1613 if (!opts->accept_pathspec && !opts->accept_ref)
1614 BUG("make up your mind, you need to take _something_");
1615 if (opts->accept_pathspec && opts->accept_ref)
1616 parseopt_flags = PARSE_OPT_KEEP_DASHDASH;
1617
1618 argc = parse_options(argc, argv, prefix, options,
1619 usagestr, parseopt_flags);
1620
1621 if (opts->show_progress < 0) {
1622 if (opts->quiet)
1623 opts->show_progress = 0;
1624 else
1625 opts->show_progress = isatty(2);
1626 }
1627
1628 if (opts->conflict_style) {
1629 opts->merge = 1; /* implied */
1630 git_xmerge_config("merge.conflictstyle", opts->conflict_style, NULL);
1631 }
1632 if (opts->force) {
1633 opts->discard_changes = 1;
1634 opts->ignore_unmerged_opt = "--force";
1635 opts->ignore_unmerged = 1;
1636 }
1637
1638 if ((!!opts->new_branch + !!opts->new_branch_force + !!opts->new_orphan_branch) > 1)
1639 die(_("-%c, -%c and --orphan are mutually exclusive"),
1640 cb_option, toupper(cb_option));
1641
1642 if (opts->overlay_mode == 1 && opts->patch_mode)
1643 die(_("-p and --overlay are mutually exclusive"));
1644
1645 if (opts->checkout_index >= 0 || opts->checkout_worktree >= 0) {
1646 if (opts->checkout_index < 0)
1647 opts->checkout_index = 0;
1648 if (opts->checkout_worktree < 0)
1649 opts->checkout_worktree = 0;
1650 } else {
1651 if (opts->checkout_index < 0)
1652 opts->checkout_index = -opts->checkout_index - 1;
1653 if (opts->checkout_worktree < 0)
1654 opts->checkout_worktree = -opts->checkout_worktree - 1;
1655 }
1656 if (opts->checkout_index < 0 || opts->checkout_worktree < 0)
1657 BUG("these flags should be non-negative by now");
1658 /*
1659 * convenient shortcut: "git restore --staged [--worktree]" equals
1660 * "git restore --staged [--worktree] --source HEAD"
1661 */
1662 if (!opts->from_treeish && opts->checkout_index)
1663 opts->from_treeish = "HEAD";
1664
1665 /*
1666 * From here on, new_branch will contain the branch to be checked out,
1667 * and new_branch_force and new_orphan_branch will tell us which one of
1668 * -b/-B/-c/-C/--orphan is being used.
1669 */
1670 if (opts->new_branch_force)
1671 opts->new_branch = opts->new_branch_force;
1672
1673 if (opts->new_orphan_branch)
1674 opts->new_branch = opts->new_orphan_branch;
1675
1676 /* --track without -c/-C/-b/-B/--orphan should DWIM */
1677 if (opts->track != BRANCH_TRACK_UNSPECIFIED && !opts->new_branch) {
1678 const char *argv0 = argv[0];
1679 if (!argc || !strcmp(argv0, "--"))
1680 die(_("--track needs a branch name"));
1681 skip_prefix(argv0, "refs/", &argv0);
1682 skip_prefix(argv0, "remotes/", &argv0);
1683 argv0 = strchr(argv0, '/');
1684 if (!argv0 || !argv0[1])
1685 die(_("missing branch name; try -%c"), cb_option);
1686 opts->new_branch = argv0 + 1;
1687 }
1688
1689 /*
1690 * Extract branch name from command line arguments, so
1691 * all that is left is pathspecs.
1692 *
1693 * Handle
1694 *
1695 * 1) git checkout <tree> -- [<paths>]
1696 * 2) git checkout -- [<paths>]
1697 * 3) git checkout <something> [<paths>]
1698 *
1699 * including "last branch" syntax and DWIM-ery for names of
1700 * remote branches, erroring out for invalid or ambiguous cases.
1701 */
1702 if (argc && opts->accept_ref) {
1703 struct object_id rev;
1704 int dwim_ok =
1705 !opts->patch_mode &&
1706 opts->dwim_new_local_branch &&
1707 opts->track == BRANCH_TRACK_UNSPECIFIED &&
1708 !opts->new_branch;
1709 int n = parse_branchname_arg(argc, argv, dwim_ok,
1710 new_branch_info, opts, &rev);
1711 argv += n;
1712 argc -= n;
1713 } else if (!opts->accept_ref && opts->from_treeish) {
1714 struct object_id rev;
1715
1716 if (get_oid_mb(opts->from_treeish, &rev))
1717 die(_("could not resolve %s"), opts->from_treeish);
1718
1719 setup_new_branch_info_and_source_tree(new_branch_info,
1720 opts, &rev,
1721 opts->from_treeish);
1722
1723 if (!opts->source_tree)
1724 die(_("reference is not a tree: %s"), opts->from_treeish);
1725 }
1726
1727 if (argc) {
1728 parse_pathspec(&opts->pathspec, 0,
1729 opts->patch_mode ? PATHSPEC_PREFIX_ORIGIN : 0,
1730 prefix, argv);
1731
1732 if (!opts->pathspec.nr)
1733 die(_("invalid path specification"));
1734
1735 /*
1736 * Try to give more helpful suggestion.
1737 * new_branch && argc > 1 will be caught later.
1738 */
1739 if (opts->new_branch && argc == 1 && !new_branch_info->commit)
1740 die(_("'%s' is not a commit and a branch '%s' cannot be created from it"),
1741 argv[0], opts->new_branch);
1742
1743 if (opts->force_detach)
1744 die(_("git checkout: --detach does not take a path argument '%s'"),
1745 argv[0]);
1746 }
1747
1748 if (opts->pathspec_from_file) {
1749 if (opts->pathspec.nr)
1750 die(_("--pathspec-from-file is incompatible with pathspec arguments"));
1751
1752 if (opts->force_detach)
1753 die(_("--pathspec-from-file is incompatible with --detach"));
1754
1755 if (opts->patch_mode)
1756 die(_("--pathspec-from-file is incompatible with --patch"));
1757
1758 parse_pathspec_file(&opts->pathspec, 0,
1759 0,
1760 prefix, opts->pathspec_from_file, opts->pathspec_file_nul);
1761 } else if (opts->pathspec_file_nul) {
1762 die(_("--pathspec-file-nul requires --pathspec-from-file"));
1763 }
1764
1765 opts->pathspec.recursive = 1;
1766
1767 if (opts->pathspec.nr) {
1768 if (1 < !!opts->writeout_stage + !!opts->force + !!opts->merge)
1769 die(_("git checkout: --ours/--theirs, --force and --merge are incompatible when\n"
1770 "checking out of the index."));
1771 } else {
1772 if (opts->accept_pathspec && !opts->empty_pathspec_ok &&
1773 !opts->patch_mode) /* patch mode is special */
1774 die(_("you must specify path(s) to restore"));
1775 }
1776
1777 if (opts->new_branch) {
1778 struct strbuf buf = STRBUF_INIT;
1779
1780 if (opts->new_branch_force)
1781 opts->branch_exists = validate_branchname(opts->new_branch, &buf);
1782 else
1783 opts->branch_exists =
1784 validate_new_branchname(opts->new_branch, &buf, 0);
1785 strbuf_release(&buf);
1786 }
1787
1788 if (opts->patch_mode || opts->pathspec.nr)
1789 return checkout_paths(opts, new_branch_info);
1790 else
1791 return checkout_branch(opts, new_branch_info);
1792 }
1793
1794 int cmd_checkout(int argc, const char **argv, const char *prefix)
1795 {
1796 struct checkout_opts opts;
1797 struct option *options;
1798 struct option checkout_options[] = {
1799 OPT_STRING('b', NULL, &opts.new_branch, N_("branch"),
1800 N_("create and checkout a new branch")),
1801 OPT_STRING('B', NULL, &opts.new_branch_force, N_("branch"),
1802 N_("create/reset and checkout a branch")),
1803 OPT_BOOL('l', NULL, &opts.new_branch_log, N_("create reflog for new branch")),
1804 OPT_BOOL(0, "guess", &opts.dwim_new_local_branch,
1805 N_("second guess 'git checkout <no-such-branch>' (default)")),
1806 OPT_BOOL(0, "overlay", &opts.overlay_mode, N_("use overlay mode (default)")),
1807 OPT_END()
1808 };
1809 int ret;
1810 struct branch_info new_branch_info = { 0 };
1811
1812 memset(&opts, 0, sizeof(opts));
1813 opts.dwim_new_local_branch = 1;
1814 opts.switch_branch_doing_nothing_is_ok = 1;
1815 opts.only_merge_on_switching_branches = 0;
1816 opts.accept_ref = 1;
1817 opts.accept_pathspec = 1;
1818 opts.implicit_detach = 1;
1819 opts.can_switch_when_in_progress = 1;
1820 opts.orphan_from_empty_tree = 0;
1821 opts.empty_pathspec_ok = 1;
1822 opts.overlay_mode = -1;
1823 opts.checkout_index = -2; /* default on */
1824 opts.checkout_worktree = -2; /* default on */
1825
1826 if (argc == 3 && !strcmp(argv[1], "-b")) {
1827 /*
1828 * User ran 'git checkout -b <branch>' and expects
1829 * the same behavior as 'git switch -c <branch>'.
1830 */
1831 opts.switch_branch_doing_nothing_is_ok = 0;
1832 opts.only_merge_on_switching_branches = 1;
1833 }
1834
1835 options = parse_options_dup(checkout_options);
1836 options = add_common_options(&opts, options);
1837 options = add_common_switch_branch_options(&opts, options);
1838 options = add_checkout_path_options(&opts, options);
1839
1840 ret = checkout_main(argc, argv, prefix, &opts,
1841 options, checkout_usage, &new_branch_info);
1842 branch_info_release(&new_branch_info);
1843 clear_pathspec(&opts.pathspec);
1844 FREE_AND_NULL(options);
1845 return ret;
1846 }
1847
1848 int cmd_switch(int argc, const char **argv, const char *prefix)
1849 {
1850 struct checkout_opts opts;
1851 struct option *options = NULL;
1852 struct option switch_options[] = {
1853 OPT_STRING('c', "create", &opts.new_branch, N_("branch"),
1854 N_("create and switch to a new branch")),
1855 OPT_STRING('C', "force-create", &opts.new_branch_force, N_("branch"),
1856 N_("create/reset and switch to a branch")),
1857 OPT_BOOL(0, "guess", &opts.dwim_new_local_branch,
1858 N_("second guess 'git switch <no-such-branch>'")),
1859 OPT_BOOL(0, "discard-changes", &opts.discard_changes,
1860 N_("throw away local modifications")),
1861 OPT_END()
1862 };
1863 int ret;
1864 struct branch_info new_branch_info = { 0 };
1865
1866 memset(&opts, 0, sizeof(opts));
1867 opts.dwim_new_local_branch = 1;
1868 opts.accept_ref = 1;
1869 opts.accept_pathspec = 0;
1870 opts.switch_branch_doing_nothing_is_ok = 0;
1871 opts.only_merge_on_switching_branches = 1;
1872 opts.implicit_detach = 0;
1873 opts.can_switch_when_in_progress = 0;
1874 opts.orphan_from_empty_tree = 1;
1875 opts.overlay_mode = -1;
1876
1877 options = parse_options_dup(switch_options);
1878 options = add_common_options(&opts, options);
1879 options = add_common_switch_branch_options(&opts, options);
1880
1881 cb_option = 'c';
1882
1883 ret = checkout_main(argc, argv, prefix, &opts,
1884 options, switch_branch_usage, &new_branch_info);
1885 branch_info_release(&new_branch_info);
1886 FREE_AND_NULL(options);
1887 return ret;
1888 }
1889
1890 int cmd_restore(int argc, const char **argv, const char *prefix)
1891 {
1892 struct checkout_opts opts;
1893 struct option *options;
1894 struct option restore_options[] = {
1895 OPT_STRING('s', "source", &opts.from_treeish, "<tree-ish>",
1896 N_("which tree-ish to checkout from")),
1897 OPT_BOOL('S', "staged", &opts.checkout_index,
1898 N_("restore the index")),
1899 OPT_BOOL('W', "worktree", &opts.checkout_worktree,
1900 N_("restore the working tree (default)")),
1901 OPT_BOOL(0, "ignore-unmerged", &opts.ignore_unmerged,
1902 N_("ignore unmerged entries")),
1903 OPT_BOOL(0, "overlay", &opts.overlay_mode, N_("use overlay mode")),
1904 OPT_END()
1905 };
1906 int ret;
1907 struct branch_info new_branch_info = { 0 };
1908
1909 memset(&opts, 0, sizeof(opts));
1910 opts.accept_ref = 0;
1911 opts.accept_pathspec = 1;
1912 opts.empty_pathspec_ok = 0;
1913 opts.overlay_mode = 0;
1914 opts.checkout_index = -1; /* default off */
1915 opts.checkout_worktree = -2; /* default on */
1916 opts.ignore_unmerged_opt = "--ignore-unmerged";
1917
1918 options = parse_options_dup(restore_options);
1919 options = add_common_options(&opts, options);
1920 options = add_checkout_path_options(&opts, options);
1921
1922 ret = checkout_main(argc, argv, prefix, &opts,
1923 options, restore_usage, &new_branch_info);
1924 branch_info_release(&new_branch_info);
1925 FREE_AND_NULL(options);
1926 return ret;
1927 }