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