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