]> git.ipfire.org Git - thirdparty/git.git/blame - builtin/checkout.c
restore: take tree-ish from --source option instead
[thirdparty/git.git] / builtin / checkout.c
CommitLineData
f8adbec9 1#define USE_THE_INDEX_COMPATIBILITY_MACROS
782c2d65 2#include "builtin.h"
0dabeffc
NTND
3#include "advice.h"
4#include "blob.h"
5#include "branch.h"
6#include "cache-tree.h"
7c85a87c 7#include "checkout.h"
0dabeffc
NTND
8#include "commit.h"
9#include "config.h"
10#include "diff.h"
11#include "dir.h"
12#include "ll-merge.h"
697cc8ef 13#include "lockfile.h"
0dabeffc
NTND
14#include "merge-recursive.h"
15#include "object-store.h"
782c2d65
DB
16#include "parse-options.h"
17#include "refs.h"
0dabeffc
NTND
18#include "remote.h"
19#include "resolve-undo.h"
20#include "revision.h"
21#include "run-command.h"
22#include "submodule.h"
23#include "submodule-config.h"
782c2d65
DB
24#include "tree.h"
25#include "tree-walk.h"
26#include "unpack-trees.h"
c45f0f52 27#include "wt-status.h"
0cf8581e 28#include "xdiff-interface.h"
782c2d65
DB
29
30static const char * const checkout_usage[] = {
9c9b4f2f
AH
31 N_("git checkout [<options>] <branch>"),
32 N_("git checkout [<options>] [<branch>] -- <file>..."),
782c2d65
DB
33 NULL,
34};
35
d787d311
NTND
36static const char * const switch_branch_usage[] = {
37 N_("git switch [<options>] [<branch>]"),
38 NULL,
39};
40
46e91b66 41static const char * const restore_usage[] = {
c9c935f6 42 N_("git restore [<options>] [--source=<branch>] <file>..."),
46e91b66
NTND
43 NULL,
44};
45
db941099 46struct checkout_opts {
e51e3057 47 int patch_mode;
db941099
JH
48 int quiet;
49 int merge;
50 int force;
32669671 51 int force_detach;
7968bef0 52 int implicit_detach;
38901a48 53 int writeout_stage;
c1d7036b 54 int overwrite_ignore;
08d595dc 55 int ignore_skipworktree;
1d0fa898 56 int ignore_other_worktrees;
870ebdb9 57 int show_progress;
0f086e6d 58 int count_checkout_paths;
091e04bc 59 int overlay_mode;
ccb111b3 60 int dwim_new_local_branch;
3ec37ad1 61 int discard_changes;
c9c935f6 62 int accept_ref;
5c06e269 63 int accept_pathspec;
e342c63a 64 int switch_branch_doing_nothing_is_ok;
65f099b3 65 int only_merge_on_switching_branches;
c45f0f52 66 int can_switch_when_in_progress;
1806c29f 67 int orphan_from_empty_tree;
db941099
JH
68
69 const char *new_branch;
02ac9837 70 const char *new_branch_force;
9db5ebf4 71 const char *new_orphan_branch;
db941099
JH
72 int new_branch_log;
73 enum branch_track track;
175f6e59 74 struct diff_options diff_options;
55cf704a 75 char *conflict_style;
e51e3057
NTND
76
77 int branch_exists;
78 const char *prefix;
817b345a 79 struct pathspec pathspec;
c9c935f6 80 const char *from_treeish;
e51e3057 81 struct tree *source_tree;
db941099
JH
82};
83
c8a3ea1f 84static int post_checkout_hook(struct commit *old_commit, struct commit *new_commit,
782c2d65
DB
85 int changed)
86{
15048f8a 87 return run_hook_le(NULL, "post-checkout",
c8a3ea1f
BW
88 oid_to_hex(old_commit ? &old_commit->object.oid : &null_oid),
89 oid_to_hex(new_commit ? &new_commit->object.oid : &null_oid),
15048f8a 90 changed ? "1" : "0", NULL);
c8a3ea1f 91 /* "new_commit" can be NULL when checking out from the index before
2292ce47 92 a commit exists. */
ae98a008 93
782c2d65
DB
94}
95
df46d77e 96static int update_some(const struct object_id *oid, struct strbuf *base,
671f0707 97 const char *pathname, unsigned mode, int stage, void *context)
782c2d65
DB
98{
99 int len;
100 struct cache_entry *ce;
c5326bd6 101 int pos;
782c2d65 102
782c2d65
DB
103 if (S_ISDIR(mode))
104 return READ_TREE_RECURSIVE;
105
6a0b0b6d 106 len = base->len + strlen(pathname);
a849735b 107 ce = make_empty_cache_entry(&the_index, len);
df46d77e 108 oidcpy(&ce->oid, oid);
6a0b0b6d
NTND
109 memcpy(ce->name, base->buf, base->len);
110 memcpy(ce->name + base->len, pathname, len - base->len);
b60e188c
TG
111 ce->ce_flags = create_ce_flags(0) | CE_UPDATE;
112 ce->ce_namelen = len;
782c2d65 113 ce->ce_mode = create_ce_mode(mode);
c5326bd6
JK
114
115 /*
116 * If the entry is the same as the current index, we can leave the old
117 * entry in place. Whether it is UPTODATE or not, checkout_entry will
118 * do the right thing.
119 */
120 pos = cache_name_pos(ce->name, ce->ce_namelen);
121 if (pos >= 0) {
122 struct cache_entry *old = active_cache[pos];
123 if (ce->ce_mode == old->ce_mode &&
4a7e27e9 124 oideq(&ce->oid, &old->oid)) {
c5326bd6 125 old->ce_flags |= CE_UPDATE;
a849735b 126 discard_cache_entry(ce);
c5326bd6
JK
127 return 0;
128 }
129 }
130
782c2d65
DB
131 add_cache_entry(ce, ADD_CACHE_OK_TO_ADD | ADD_CACHE_OK_TO_REPLACE);
132 return 0;
133}
134
18e4f405 135static int read_tree_some(struct tree *tree, const struct pathspec *pathspec)
782c2d65 136{
e092073d
NTND
137 read_tree_recursive(the_repository, tree, "", 0, 0,
138 pathspec, update_some, NULL);
782c2d65 139
782c2d65
DB
140 /* update the index with the given tree's info
141 * for all args, expanding wildcards, and exit
142 * with any non-zero return code.
143 */
144 return 0;
145}
146
9c5e6c80 147static int skip_same_name(const struct cache_entry *ce, int pos)
8fdcf312
JH
148{
149 while (++pos < active_nr &&
150 !strcmp(active_cache[pos]->name, ce->name))
151 ; /* skip */
152 return pos;
153}
154
091e04bc
TG
155static int check_stage(int stage, const struct cache_entry *ce, int pos,
156 int overlay_mode)
38901a48
JH
157{
158 while (pos < active_nr &&
159 !strcmp(active_cache[pos]->name, ce->name)) {
160 if (ce_stage(active_cache[pos]) == stage)
161 return 0;
162 pos++;
163 }
091e04bc
TG
164 if (!overlay_mode)
165 return 0;
9f97ab08
ÆAB
166 if (stage == 2)
167 return error(_("path '%s' does not have our version"), ce->name);
168 else
169 return error(_("path '%s' does not have their version"), ce->name);
38901a48
JH
170}
171
9c5e6c80 172static int check_stages(unsigned stages, const struct cache_entry *ce, int pos)
0cf8581e 173{
fbbccd0a
JH
174 unsigned seen = 0;
175 const char *name = ce->name;
176
177 while (pos < active_nr) {
178 ce = active_cache[pos];
179 if (strcmp(name, ce->name))
180 break;
181 seen |= (1 << ce_stage(ce));
182 pos++;
183 }
184 if ((stages & seen) != stages)
185 return error(_("path '%s' does not have all necessary versions"),
186 name);
0cf8581e
JH
187 return 0;
188}
189
ce25e4c7 190static int checkout_stage(int stage, const struct cache_entry *ce, int pos,
7d0c1f45
JH
191 const struct checkout *state, int *nr_checkouts,
192 int overlay_mode)
38901a48
JH
193{
194 while (pos < active_nr &&
195 !strcmp(active_cache[pos]->name, ce->name)) {
196 if (ce_stage(active_cache[pos]) == stage)
0f086e6d
NTND
197 return checkout_entry(active_cache[pos], state,
198 NULL, nr_checkouts);
38901a48
JH
199 pos++;
200 }
091e04bc
TG
201 if (!overlay_mode) {
202 unlink_entry(ce);
203 return 0;
204 }
9f97ab08
ÆAB
205 if (stage == 2)
206 return error(_("path '%s' does not have our version"), ce->name);
207 else
208 return error(_("path '%s' does not have their version"), ce->name);
38901a48 209}
8fdcf312 210
0f086e6d 211static int checkout_merged(int pos, const struct checkout *state, int *nr_checkouts)
0cf8581e
JH
212{
213 struct cache_entry *ce = active_cache[pos];
214 const char *path = ce->name;
215 mmfile_t ancestor, ours, theirs;
216 int status;
60af7691 217 struct object_id oid;
0cf8581e 218 mmbuffer_t result_buf;
60af7691 219 struct object_id threeway[3];
335c6e40 220 unsigned mode = 0;
0cf8581e 221
fbbccd0a
JH
222 memset(threeway, 0, sizeof(threeway));
223 while (pos < active_nr) {
224 int stage;
225 stage = ce_stage(ce);
226 if (!stage || strcmp(path, ce->name))
227 break;
60af7691 228 oidcpy(&threeway[stage - 1], &ce->oid);
fbbccd0a
JH
229 if (stage == 2)
230 mode = create_ce_mode(ce->ce_mode);
231 pos++;
232 ce = active_cache[pos];
233 }
60af7691 234 if (is_null_oid(&threeway[1]) || is_null_oid(&threeway[2]))
fbbccd0a 235 return error(_("path '%s' does not have necessary versions"), path);
0cf8581e 236
d449347d 237 read_mmblob(&ancestor, &threeway[0]);
238 read_mmblob(&ours, &threeway[1]);
239 read_mmblob(&theirs, &threeway[2]);
0cf8581e 240
18b037a5
JN
241 /*
242 * NEEDSWORK: re-create conflicts from merges with
243 * merge.renormalize set, too
244 */
f0531a29 245 status = ll_merge(&result_buf, path, &ancestor, "base",
32eaa468
NTND
246 &ours, "ours", &theirs, "theirs",
247 state->istate, NULL);
0cf8581e
JH
248 free(ancestor.ptr);
249 free(ours.ptr);
250 free(theirs.ptr);
251 if (status < 0 || !result_buf.ptr) {
252 free(result_buf.ptr);
e8a8a4d7 253 return error(_("path '%s': cannot merge"), path);
0cf8581e
JH
254 }
255
256 /*
257 * NEEDSWORK:
258 * There is absolutely no reason to write this as a blob object
514e8039
JS
259 * and create a phony cache entry. This hack is primarily to get
260 * to the write_entry() machinery that massages the contents to
261 * work-tree format and writes out which only allows it for a
262 * cache entry. The code in write_entry() needs to be refactored
263 * to allow us to feed a <buffer, size, mode> instead of a cache
264 * entry. Such a refactoring would help merge_recursive as well
265 * (it also writes the merge result to the object database even
266 * when it may contain conflicts).
0cf8581e 267 */
a09c985e 268 if (write_object_file(result_buf.ptr, result_buf.size, blob_type, &oid))
e8a8a4d7 269 die(_("Unable to add merge result for '%s'"), path);
443a12f3 270 free(result_buf.ptr);
a849735b 271 ce = make_transient_cache_entry(mode, &oid, path, 2);
048f2762 272 if (!ce)
e8a8a4d7 273 die(_("make_cache_entry failed for path '%s'"), path);
0f086e6d 274 status = checkout_entry(ce, state, NULL, nr_checkouts);
a849735b 275 discard_cache_entry(ce);
0cf8581e
JH
276 return status;
277}
8fdcf312 278
091e04bc
TG
279static void mark_ce_for_checkout_overlay(struct cache_entry *ce,
280 char *ps_matched,
281 const struct checkout_opts *opts)
b7033e73
TG
282{
283 ce->ce_flags &= ~CE_MATCHED;
284 if (!opts->ignore_skipworktree && ce_skip_worktree(ce))
285 return;
286 if (opts->source_tree && !(ce->ce_flags & CE_UPDATE))
287 /*
288 * "git checkout tree-ish -- path", but this entry
289 * is in the original index but is not in tree-ish
290 * or does not match the pathspec; it will not be
291 * checked out to the working tree. We will not do
292 * anything to this entry at all.
293 */
294 return;
295 /*
296 * Either this entry came from the tree-ish we are
297 * checking the paths out of, or we are checking out
298 * of the index.
299 *
300 * If it comes from the tree-ish, we already know it
301 * matches the pathspec and could just stamp
302 * CE_MATCHED to it from update_some(). But we still
303 * need ps_matched and read_tree_recursive (and
304 * eventually tree_entry_interesting) cannot fill
305 * ps_matched yet. Once it can, we can avoid calling
306 * match_pathspec() for _all_ entries when
307 * opts->source_tree != NULL.
308 */
309 if (ce_path_match(&the_index, ce, &opts->pathspec, ps_matched))
310 ce->ce_flags |= CE_MATCHED;
311}
312
091e04bc
TG
313static void mark_ce_for_checkout_no_overlay(struct cache_entry *ce,
314 char *ps_matched,
315 const struct checkout_opts *opts)
316{
317 ce->ce_flags &= ~CE_MATCHED;
318 if (!opts->ignore_skipworktree && ce_skip_worktree(ce))
319 return;
320 if (ce_path_match(&the_index, ce, &opts->pathspec, ps_matched)) {
321 ce->ce_flags |= CE_MATCHED;
322 if (opts->source_tree && !(ce->ce_flags & CE_UPDATE))
323 /*
324 * In overlay mode, but the path is not in
325 * tree-ish, which means we should remove it
326 * from the index and the working tree.
327 */
328 ce->ce_flags |= CE_REMOVE | CE_WT_REMOVE;
329 }
330}
331
b6312c27
NTND
332static int checkout_paths(const struct checkout_opts *opts,
333 const char *revision)
782c2d65
DB
334{
335 int pos;
68e3d629 336 struct checkout state = CHECKOUT_INIT;
782c2d65 337 static char *ps_matched;
60af7691 338 struct object_id rev;
782c2d65 339 struct commit *head;
d2b3691b 340 int errs = 0;
837e34eb 341 struct lock_file lock_file = LOCK_INIT;
1d1f689b 342 int nr_checkouts = 0, nr_unmerged = 0;
b6312c27 343
e27dd8ae
JH
344 trace2_cmd_mode(opts->patch_mode ? "patch" : "path");
345
b6312c27
NTND
346 if (opts->track != BRANCH_TRACK_UNSPECIFIED)
347 die(_("'%s' cannot be used with updating paths"), "--track");
348
349 if (opts->new_branch_log)
350 die(_("'%s' cannot be used with updating paths"), "-l");
351
352 if (opts->force && opts->patch_mode)
353 die(_("'%s' cannot be used with updating paths"), "-f");
354
355 if (opts->force_detach)
356 die(_("'%s' cannot be used with updating paths"), "--detach");
357
358 if (opts->merge && opts->patch_mode)
359 die(_("'%s' cannot be used with %s"), "--merge", "--patch");
360
361 if (opts->force && opts->merge)
362 die(_("'%s' cannot be used with %s"), "-f", "-m");
363
364 if (opts->new_branch)
365 die(_("Cannot update paths and switch to branch '%s' at the same time."),
366 opts->new_branch);
367
368 if (opts->patch_mode)
369 return run_add_interactive(revision, "--patch=checkout",
480ca644 370 &opts->pathspec);
b6312c27 371
fb4a8464 372 repo_hold_locked_index(the_repository, &lock_file, LOCK_DIE_ON_ERROR);
5ab2a2da 373 if (read_cache_preload(&opts->pathspec) < 0)
e923a8ab 374 return error(_("index file corrupt"));
75336878 375
e51e3057 376 if (opts->source_tree)
18e4f405 377 read_tree_some(opts->source_tree, &opts->pathspec);
75336878 378
8b54c234 379 ps_matched = xcalloc(opts->pathspec.nr, 1);
782c2d65 380
e721c154
NTND
381 /*
382 * Make sure all pathspecs participated in locating the paths
383 * to be checked out.
384 */
b7033e73 385 for (pos = 0; pos < active_nr; pos++)
091e04bc
TG
386 if (opts->overlay_mode)
387 mark_ce_for_checkout_overlay(active_cache[pos],
388 ps_matched,
389 opts);
390 else
391 mark_ce_for_checkout_no_overlay(active_cache[pos],
392 ps_matched,
393 opts);
782c2d65 394
17ddc66e 395 if (report_path_error(ps_matched, &opts->pathspec, opts->prefix)) {
e721c154 396 free(ps_matched);
782c2d65 397 return 1;
e721c154
NTND
398 }
399 free(ps_matched);
782c2d65 400
4421a823
JH
401 /* "checkout -m path" to recreate conflicted state */
402 if (opts->merge)
e721c154 403 unmerge_marked_index(&the_index);
4421a823 404
8fdcf312
JH
405 /* Any unmerged paths? */
406 for (pos = 0; pos < active_nr; pos++) {
9c5e6c80 407 const struct cache_entry *ce = active_cache[pos];
e721c154 408 if (ce->ce_flags & CE_MATCHED) {
8fdcf312
JH
409 if (!ce_stage(ce))
410 continue;
db941099 411 if (opts->force) {
e8a8a4d7 412 warning(_("path '%s' is unmerged"), ce->name);
f9022075 413 } else if (opts->writeout_stage) {
091e04bc 414 errs |= check_stage(opts->writeout_stage, ce, pos, opts->overlay_mode);
0cf8581e 415 } else if (opts->merge) {
fbbccd0a 416 errs |= check_stages((1<<2) | (1<<3), ce, pos);
db941099
JH
417 } else {
418 errs = 1;
e8a8a4d7 419 error(_("path '%s' is unmerged"), ce->name);
db941099 420 }
8fdcf312
JH
421 pos = skip_same_name(ce, pos) - 1;
422 }
423 }
424 if (errs)
425 return 1;
426
d2b3691b 427 /* Now we are committed to check them out */
782c2d65
DB
428 state.force = 1;
429 state.refresh_cache = 1;
d4a2024a 430 state.istate = &the_index;
2841e8f8
LS
431
432 enable_delayed_checkout(&state);
782c2d65
DB
433 for (pos = 0; pos < active_nr; pos++) {
434 struct cache_entry *ce = active_cache[pos];
e721c154 435 if (ce->ce_flags & CE_MATCHED) {
8fdcf312 436 if (!ce_stage(ce)) {
0f086e6d
NTND
437 errs |= checkout_entry(ce, &state,
438 NULL, &nr_checkouts);
8fdcf312
JH
439 continue;
440 }
f9022075 441 if (opts->writeout_stage)
0f086e6d
NTND
442 errs |= checkout_stage(opts->writeout_stage,
443 ce, pos,
7d0c1f45
JH
444 &state,
445 &nr_checkouts, opts->overlay_mode);
f9022075 446 else if (opts->merge)
0f086e6d 447 errs |= checkout_merged(pos, &state,
1d1f689b 448 &nr_unmerged);
8fdcf312 449 pos = skip_same_name(ce, pos) - 1;
782c2d65
DB
450 }
451 }
091e04bc
TG
452 remove_marked_cache_entries(&the_index, 1);
453 remove_scheduled_dirs();
0f086e6d
NTND
454 errs |= finish_delayed_checkout(&state, &nr_checkouts);
455
456 if (opts->count_checkout_paths) {
1d1f689b
NTND
457 if (nr_unmerged)
458 fprintf_ln(stderr, Q_("Recreated %d merge conflict",
459 "Recreated %d merge conflicts",
460 nr_unmerged),
461 nr_unmerged);
0f086e6d 462 if (opts->source_tree)
3c5883b3
NTND
463 fprintf_ln(stderr, Q_("Updated %d path from %s",
464 "Updated %d paths from %s",
0f086e6d
NTND
465 nr_checkouts),
466 nr_checkouts,
467 find_unique_abbrev(&opts->source_tree->object.oid,
468 DEFAULT_ABBREV));
1d1f689b 469 else if (!nr_unmerged || nr_checkouts)
3c5883b3
NTND
470 fprintf_ln(stderr, Q_("Updated %d path from the index",
471 "Updated %d paths from the index",
0f086e6d
NTND
472 nr_checkouts),
473 nr_checkouts);
474 }
782c2d65 475
837e34eb 476 if (write_locked_index(&the_index, &lock_file, COMMIT_LOCK))
e8a8a4d7 477 die(_("unable to write new index file"));
75336878 478
34c290a6 479 read_ref_full("HEAD", 0, &rev, NULL);
21e1ee8f 480 head = lookup_commit_reference_gently(the_repository, &rev, 1);
782c2d65 481
d2b3691b
JH
482 errs |= post_checkout_hook(head, head, 0);
483 return errs;
782c2d65
DB
484}
485
a2b4994c
NTND
486static void show_local_changes(struct object *head,
487 const struct diff_options *opts)
782c2d65
DB
488{
489 struct rev_info rev;
490 /* I think we want full paths, even if we're in a subdirectory. */
2abf3503 491 repo_init_revisions(the_repository, &rev, NULL);
175f6e59 492 rev.diffopt.flags = opts->flags;
782c2d65 493 rev.diffopt.output_format |= DIFF_FORMAT_NAME_STATUS;
28452655 494 diff_setup_done(&rev.diffopt);
782c2d65
DB
495 add_pending_object(&rev, head, NULL);
496 run_diff_index(&rev, 0);
497}
498
b3c0494a 499static void describe_detached_head(const char *msg, struct commit *commit)
782c2d65 500{
f285a2d7 501 struct strbuf sb = STRBUF_INIT;
ca69d4d5 502
3c621839
JK
503 if (!parse_commit(commit))
504 pp_commit_easy(CMIT_FMT_ONELINE, commit, &sb);
ca69d4d5
AR
505 if (print_sha1_ellipsis()) {
506 fprintf(stderr, "%s %s... %s\n", msg,
aab9583f 507 find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV), sb.buf);
ca69d4d5
AR
508 } else {
509 fprintf(stderr, "%s %s %s\n", msg,
aab9583f 510 find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV), sb.buf);
ca69d4d5 511 }
782c2d65
DB
512 strbuf_release(&sb);
513}
514
a2b4994c
NTND
515static int reset_tree(struct tree *tree, const struct checkout_opts *o,
516 int worktree, int *writeout_error)
782c2d65
DB
517{
518 struct unpack_trees_options opts;
519 struct tree_desc tree_desc;
bc052d7f 520
782c2d65
DB
521 memset(&opts, 0, sizeof(opts));
522 opts.head_idx = -1;
6286a08d
JH
523 opts.update = worktree;
524 opts.skip_unmerged = !worktree;
782c2d65
DB
525 opts.reset = 1;
526 opts.merge = 1;
527 opts.fn = oneway_merge;
870ebdb9 528 opts.verbose_update = o->show_progress;
34110cd4
LT
529 opts.src_index = &the_index;
530 opts.dst_index = &the_index;
782c2d65
DB
531 parse_tree(tree);
532 init_tree_desc(&tree_desc, tree->buffer, tree->size);
291d823e
JH
533 switch (unpack_trees(1, &tree_desc, &opts)) {
534 case -2:
a2b4994c 535 *writeout_error = 1;
291d823e
JH
536 /*
537 * We return 0 nevertheless, as the index is all right
538 * and more importantly we have made best efforts to
539 * update paths in the work tree, and we cannot revert
540 * them.
541 */
1cf01a34 542 /* fallthrough */
291d823e
JH
543 case 0:
544 return 0;
545 default:
84a5750b 546 return 128;
291d823e 547 }
782c2d65
DB
548}
549
782c2d65
DB
550struct branch_info {
551 const char *name; /* The short name used */
552 const char *path; /* The full name of a real branch */
553 struct commit *commit; /* The named commit */
5883034c
NTND
554 /*
555 * if not null the branch is detached because it's already
556 * checked out in this checkout
557 */
558 char *checkout;
782c2d65
DB
559};
560
561static void setup_branch_path(struct branch_info *branch)
562{
f285a2d7 563 struct strbuf buf = STRBUF_INIT;
ae5a6c36 564
fd4692ff 565 strbuf_branchname(&buf, branch->name, INTERPRET_BRANCH_LOCAL);
a552de75 566 if (strcmp(buf.buf, branch->name))
ae5a6c36 567 branch->name = xstrdup(buf.buf);
a552de75 568 strbuf_splice(&buf, 0, 0, "refs/heads/", 11);
782c2d65
DB
569 branch->path = strbuf_detach(&buf, NULL);
570}
571
a2b4994c 572static int merge_working_tree(const struct checkout_opts *opts,
c8a3ea1f
BW
573 struct branch_info *old_branch_info,
574 struct branch_info *new_branch_info,
a2b4994c 575 int *writeout_error)
782c2d65
DB
576{
577 int ret;
837e34eb 578 struct lock_file lock_file = LOCK_INIT;
1806c29f 579 struct tree *new_tree;
b96524f8 580
837e34eb 581 hold_locked_index(&lock_file, LOCK_DIE_ON_ERROR);
53996fe5 582 if (read_cache_preload(NULL) < 0)
e923a8ab 583 return error(_("index file corrupt"));
782c2d65 584
cfc5789a 585 resolve_undo_clear();
1806c29f
NTND
586 if (opts->new_orphan_branch && opts->orphan_from_empty_tree) {
587 if (new_branch_info->commit)
588 BUG("'switch --orphan' should never accept a commit as starting point");
589 new_tree = parse_tree_indirect(the_hash_algo->empty_tree);
590 } else
591 new_tree = get_commit_tree(new_branch_info->commit);
3ec37ad1 592 if (opts->discard_changes) {
1806c29f 593 ret = reset_tree(new_tree, opts, 1, writeout_error);
782c2d65
DB
594 if (ret)
595 return ret;
596 } else {
597 struct tree_desc trees[2];
598 struct tree *tree;
599 struct unpack_trees_options topts;
bc052d7f 600
782c2d65
DB
601 memset(&topts, 0, sizeof(topts));
602 topts.head_idx = -1;
34110cd4
LT
603 topts.src_index = &the_index;
604 topts.dst_index = &the_index;
782c2d65 605
e294030f 606 setup_unpack_trees_porcelain(&topts, "checkout");
8ccba008 607
782c2d65
DB
608 refresh_cache(REFRESH_QUIET);
609
610 if (unmerged_cache()) {
e8a8a4d7 611 error(_("you need to resolve your current index first"));
04c9e11f 612 return 1;
782c2d65 613 }
04c9e11f
JH
614
615 /* 2-way merge to the new branch */
fa7b3c2f 616 topts.initial_checkout = is_cache_unborn();
04c9e11f
JH
617 topts.update = 1;
618 topts.merge = 1;
c8a3ea1f 619 topts.gently = opts->merge && old_branch_info->commit;
870ebdb9 620 topts.verbose_update = opts->show_progress;
04c9e11f 621 topts.fn = twoway_merge;
c1d7036b
NTND
622 if (opts->overwrite_ignore) {
623 topts.dir = xcalloc(1, sizeof(*topts.dir));
624 topts.dir->flags |= DIR_SHOW_IGNORED;
625 setup_standard_excludes(topts.dir);
626 }
c8a3ea1f
BW
627 tree = parse_tree_indirect(old_branch_info->commit ?
628 &old_branch_info->commit->object.oid :
eb0ccfd7 629 the_hash_algo->empty_tree);
04c9e11f 630 init_tree_desc(&trees[0], tree->buffer, tree->size);
1806c29f
NTND
631 parse_tree(new_tree);
632 tree = new_tree;
04c9e11f
JH
633 init_tree_desc(&trees[1], tree->buffer, tree->size);
634
291d823e 635 ret = unpack_trees(2, trees, &topts);
1c41d280 636 clear_unpack_trees_porcelain(&topts);
49d833dc 637 if (ret == -1) {
782c2d65
DB
638 /*
639 * Unpack couldn't do a trivial merge; either
640 * give up or do a real merge, depending on
641 * whether the merge flag was used.
642 */
643 struct tree *result;
644 struct tree *work;
8a2fce18 645 struct merge_options o;
782c2d65
DB
646 if (!opts->merge)
647 return 1;
64da3ae5
JH
648
649 /*
c8a3ea1f 650 * Without old_branch_info->commit, the below is the same as
64da3ae5
JH
651 * the two-tree unpack we already tried and failed.
652 */
c8a3ea1f 653 if (!old_branch_info->commit)
64da3ae5 654 return 1;
782c2d65
DB
655
656 /* Do more real merge */
657
658 /*
659 * We update the index fully, then write the
660 * tree from the index, then merge the new
661 * branch with the current tree, with the old
662 * branch as the base. Then we reset the index
663 * (but not the working tree) to the new
664 * branch, leaving the working tree as the
665 * merged version, but skipping unmerged
666 * entries in the index.
667 */
668
610d55af 669 add_files_to_cache(NULL, NULL, 0);
7610fa57
JN
670 /*
671 * NEEDSWORK: carrying over local changes
672 * when branches have different end-of-line
673 * normalization (or clean+smudge rules) is
674 * a pain; plumb in an option to set
675 * o.renormalize?
676 */
0d6caa2d 677 init_merge_options(&o, the_repository);
8a2fce18
MV
678 o.verbosity = 0;
679 work = write_tree_from_memory(&o);
782c2d65 680
1806c29f 681 ret = reset_tree(new_tree,
2e27bd77 682 opts, 1,
a2b4994c 683 writeout_error);
782c2d65
DB
684 if (ret)
685 return ret;
c8a3ea1f
BW
686 o.ancestor = old_branch_info->name;
687 o.branch1 = new_branch_info->name;
8a2fce18 688 o.branch2 = "local";
2e27bd77 689 ret = merge_trees(&o,
1806c29f 690 new_tree,
2e27bd77
DS
691 work,
692 get_commit_tree(old_branch_info->commit),
693 &result);
f241ff0d
JS
694 if (ret < 0)
695 exit(128);
1806c29f 696 ret = reset_tree(new_tree,
2e27bd77 697 opts, 0,
a2b4994c 698 writeout_error);
548009c0 699 strbuf_release(&o.obuf);
84a5750b
JH
700 if (ret)
701 return ret;
782c2d65
DB
702 }
703 }
704
aecf567c
DT
705 if (!active_cache_tree)
706 active_cache_tree = cache_tree();
707
708 if (!cache_tree_fully_valid(active_cache_tree))
3fd13cbc 709 cache_tree_update(&the_index, WRITE_TREE_SILENT | WRITE_TREE_REPAIR);
aecf567c 710
837e34eb 711 if (write_locked_index(&the_index, &lock_file, COMMIT_LOCK))
e8a8a4d7 712 die(_("unable to write new index file"));
782c2d65 713
1806c29f 714 if (!opts->discard_changes && !opts->quiet && new_branch_info->commit)
c8a3ea1f 715 show_local_changes(&new_branch_info->commit->object, &opts->diff_options);
782c2d65
DB
716
717 return 0;
718}
719
c8a3ea1f 720static void report_tracking(struct branch_info *new_branch_info)
79a1e6b4 721{
6d21bf96 722 struct strbuf sb = STRBUF_INIT;
c8a3ea1f 723 struct branch *branch = branch_get(new_branch_info->name);
79a1e6b4 724
f39a757d 725 if (!format_tracking_info(branch, &sb, AHEAD_BEHIND_FULL))
79a1e6b4 726 return;
6d21bf96
JH
727 fputs(sb.buf, stdout);
728 strbuf_release(&sb);
b0030db3 729}
79a1e6b4 730
a2b4994c 731static void update_refs_for_switch(const struct checkout_opts *opts,
c8a3ea1f
BW
732 struct branch_info *old_branch_info,
733 struct branch_info *new_branch_info)
782c2d65 734{
f285a2d7 735 struct strbuf msg = STRBUF_INIT;
3bed291a 736 const char *old_desc, *reflog_msg;
782c2d65 737 if (opts->new_branch) {
3631bf77 738 if (opts->new_orphan_branch) {
341fb286
CW
739 char *refname;
740
741 refname = mkpathdup("refs/heads/%s", opts->new_orphan_branch);
742 if (opts->new_branch_log &&
743 !should_autocreate_reflog(refname)) {
1a83c240 744 int ret;
a4c653df 745 struct strbuf err = STRBUF_INIT;
3631bf77 746
abd0cd3a 747 ret = safe_create_reflog(refname, 1, &err);
1a83c240 748 if (ret) {
a4c653df
DT
749 fprintf(stderr, _("Can not do reflog for '%s': %s\n"),
750 opts->new_orphan_branch, err.buf);
751 strbuf_release(&err);
341fb286 752 free(refname);
3631bf77
EM
753 return;
754 }
abd0cd3a 755 strbuf_release(&err);
3631bf77 756 }
341fb286 757 free(refname);
3631bf77
EM
758 }
759 else
4edce172
NTND
760 create_branch(the_repository,
761 opts->new_branch, new_branch_info->name,
02ac9837 762 opts->new_branch_force ? 1 : 0,
39bd6f72 763 opts->new_branch_force ? 1 : 0,
e2bbd0cc 764 opts->new_branch_log,
f9a482e6 765 opts->quiet,
39bd6f72 766 opts->track);
c8a3ea1f
BW
767 new_branch_info->name = opts->new_branch;
768 setup_branch_path(new_branch_info);
782c2d65
DB
769 }
770
c8a3ea1f
BW
771 old_desc = old_branch_info->name;
772 if (!old_desc && old_branch_info->commit)
773 old_desc = oid_to_hex(&old_branch_info->commit->object.oid);
3bed291a
RR
774
775 reflog_msg = getenv("GIT_REFLOG_ACTION");
776 if (!reflog_msg)
777 strbuf_addf(&msg, "checkout: moving from %s to %s",
c8a3ea1f 778 old_desc ? old_desc : "(invalid)", new_branch_info->name);
3bed291a
RR
779 else
780 strbuf_insert(&msg, 0, reflog_msg, strlen(reflog_msg));
782c2d65 781
c8a3ea1f 782 if (!strcmp(new_branch_info->name, "HEAD") && !new_branch_info->path && !opts->force_detach) {
f8bd36a4 783 /* Nothing to do. */
c8a3ea1f
BW
784 } else if (opts->force_detach || !new_branch_info->path) { /* No longer on any branch. */
785 update_ref(msg.buf, "HEAD", &new_branch_info->commit->object.oid, NULL,
91774afc 786 REF_NO_DEREF, UPDATE_REFS_DIE_ON_ERR);
f8bd36a4 787 if (!opts->quiet) {
c8a3ea1f 788 if (old_branch_info->path &&
779b88a9 789 advice_detached_head && !opts->force_detach)
c8a3ea1f
BW
790 detach_advice(new_branch_info->name);
791 describe_detached_head(_("HEAD is now at"), new_branch_info->commit);
f8bd36a4 792 }
c8a3ea1f
BW
793 } else if (new_branch_info->path) { /* Switch branches. */
794 if (create_symref("HEAD", new_branch_info->path, msg.buf) < 0)
4636f651 795 die(_("unable to update HEAD"));
782c2d65 796 if (!opts->quiet) {
c8a3ea1f 797 if (old_branch_info->path && !strcmp(new_branch_info->path, old_branch_info->path)) {
39bd6f72
JN
798 if (opts->new_branch_force)
799 fprintf(stderr, _("Reset branch '%s'\n"),
c8a3ea1f 800 new_branch_info->name);
39bd6f72
JN
801 else
802 fprintf(stderr, _("Already on '%s'\n"),
c8a3ea1f 803 new_branch_info->name);
08eaa4be
ÆAB
804 } else if (opts->new_branch) {
805 if (opts->branch_exists)
c8a3ea1f 806 fprintf(stderr, _("Switched to and reset branch '%s'\n"), new_branch_info->name);
08eaa4be 807 else
c8a3ea1f 808 fprintf(stderr, _("Switched to a new branch '%s'\n"), new_branch_info->name);
08eaa4be 809 } else {
e8a8a4d7 810 fprintf(stderr, _("Switched to branch '%s'\n"),
c8a3ea1f 811 new_branch_info->name);
08eaa4be 812 }
782c2d65 813 }
c8a3ea1f
BW
814 if (old_branch_info->path && old_branch_info->name) {
815 if (!ref_exists(old_branch_info->path) && reflog_exists(old_branch_info->path))
816 delete_reflog(old_branch_info->path);
3631bf77 817 }
782c2d65 818 }
f4a4b9ac 819 remove_branch_state(the_repository, !opts->quiet);
782c2d65 820 strbuf_release(&msg);
32669671 821 if (!opts->quiet &&
c8a3ea1f
BW
822 (new_branch_info->path || (!opts->force_detach && !strcmp(new_branch_info->name, "HEAD"))))
823 report_tracking(new_branch_info);
782c2d65
DB
824}
825
468224e5 826static int add_pending_uninteresting_ref(const char *refname,
fcb615f5 827 const struct object_id *oid,
468224e5 828 int flags, void *cb_data)
8e2dc6ac 829{
a58a1b01 830 add_pending_oid(cb_data, refname, oid, UNINTERESTING);
5c08dc48
JK
831 return 0;
832}
8e2dc6ac
JH
833
834static void describe_one_orphan(struct strbuf *sb, struct commit *commit)
835{
0be240cc 836 strbuf_addstr(sb, " ");
30e677e0 837 strbuf_add_unique_abbrev(sb, &commit->object.oid, DEFAULT_ABBREV);
0be240cc 838 strbuf_addch(sb, ' ');
3c621839
JK
839 if (!parse_commit(commit))
840 pp_commit_easy(CMIT_FMT_ONELINE, commit, sb);
8e2dc6ac
JH
841 strbuf_addch(sb, '\n');
842}
843
844#define ORPHAN_CUTOFF 4
845static void suggest_reattach(struct commit *commit, struct rev_info *revs)
846{
847 struct commit *c, *last = NULL;
848 struct strbuf sb = STRBUF_INIT;
849 int lost = 0;
850 while ((c = get_revision(revs)) != NULL) {
851 if (lost < ORPHAN_CUTOFF)
852 describe_one_orphan(&sb, c);
853 last = c;
854 lost++;
855 }
856 if (ORPHAN_CUTOFF < lost) {
857 int more = lost - ORPHAN_CUTOFF;
858 if (more == 1)
859 describe_one_orphan(&sb, last);
860 else
f06f08b7 861 strbuf_addf(&sb, _(" ... and %d more.\n"), more);
8e2dc6ac
JH
862 }
863
864 fprintf(stderr,
f06f08b7
ÆAB
865 Q_(
866 /* The singular version */
867 "Warning: you are leaving %d commit behind, "
868 "not connected to\n"
869 "any of your branches:\n\n"
0faf2474 870 "%s\n",
f06f08b7
ÆAB
871 /* The plural version */
872 "Warning: you are leaving %d commits behind, "
8e2dc6ac
JH
873 "not connected to\n"
874 "any of your branches:\n\n"
f807b3dc 875 "%s\n",
f06f08b7
ÆAB
876 /* Give ngettext() the count */
877 lost),
878 lost,
f807b3dc 879 sb.buf);
8e2dc6ac 880 strbuf_release(&sb);
f807b3dc
JH
881
882 if (advice_detached_head)
883 fprintf(stderr,
fc792ca8
TS
884 Q_(
885 /* The singular version */
886 "If you want to keep it by creating a new branch, "
887 "this may be a good time\nto do so with:\n\n"
888 " git branch <new-branch-name> %s\n\n",
889 /* The plural version */
f807b3dc
JH
890 "If you want to keep them by creating a new branch, "
891 "this may be a good time\nto do so with:\n\n"
fc792ca8
TS
892 " git branch <new-branch-name> %s\n\n",
893 /* Give ngettext() the count */
894 lost),
aab9583f 895 find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV));
8e2dc6ac
JH
896}
897
898/*
899 * We are about to leave commit that was at the tip of a detached
900 * HEAD. If it is not reachable from any ref, this is the last chance
901 * for the user to do so without resorting to reflog.
902 */
c8a3ea1f 903static void orphaned_commit_warning(struct commit *old_commit, struct commit *new_commit)
8e2dc6ac 904{
8e2dc6ac 905 struct rev_info revs;
c8a3ea1f 906 struct object *object = &old_commit->object;
8e2dc6ac 907
2abf3503 908 repo_init_revisions(the_repository, &revs, NULL);
468224e5
RS
909 setup_revisions(0, NULL, &revs, NULL);
910
911 object->flags &= ~UNINTERESTING;
f2fd0760 912 add_pending_object(&revs, object, oid_to_hex(&object->oid));
468224e5 913
fcb615f5 914 for_each_ref(add_pending_uninteresting_ref, &revs);
1806c29f
NTND
915 if (new_commit)
916 add_pending_oid(&revs, "HEAD",
917 &new_commit->object.oid,
918 UNINTERESTING);
468224e5 919
8e2dc6ac 920 if (prepare_revision_walk(&revs))
6c80cd29 921 die(_("internal error in revision walk"));
c8a3ea1f
BW
922 if (!(old_commit->object.flags & UNINTERESTING))
923 suggest_reattach(old_commit, &revs);
8e2dc6ac 924 else
c8a3ea1f 925 describe_detached_head(_("Previous HEAD position was"), old_commit);
5c08dc48 926
b2ccdf7f 927 /* Clean up objects used, as they will be reused. */
a9a03fa0 928 clear_commit_marks_all(ALL_REV_FLAGS);
8e2dc6ac
JH
929}
930
e51e3057 931static int switch_branches(const struct checkout_opts *opts,
c8a3ea1f 932 struct branch_info *new_branch_info)
782c2d65
DB
933{
934 int ret = 0;
c8a3ea1f 935 struct branch_info old_branch_info;
96ec7b1e 936 void *path_to_free;
60af7691 937 struct object_id rev;
a2b4994c 938 int flag, writeout_error = 0;
65f099b3 939 int do_merge = 1;
e27dd8ae
JH
940
941 trace2_cmd_mode("branch");
942
c8a3ea1f
BW
943 memset(&old_branch_info, 0, sizeof(old_branch_info));
944 old_branch_info.path = path_to_free = resolve_refdup("HEAD", 0, &rev, &flag);
945 if (old_branch_info.path)
21e1ee8f 946 old_branch_info.commit = lookup_commit_reference_gently(the_repository, &rev, 1);
96ec7b1e 947 if (!(flag & REF_ISSYMREF))
c8a3ea1f 948 old_branch_info.path = NULL;
782c2d65 949
c8a3ea1f
BW
950 if (old_branch_info.path)
951 skip_prefix(old_branch_info.path, "refs/heads/", &old_branch_info.name);
782c2d65 952
1806c29f
NTND
953 if (opts->new_orphan_branch && opts->orphan_from_empty_tree) {
954 if (new_branch_info->name)
955 BUG("'switch --orphan' should never accept a commit as starting point");
956 new_branch_info->commit = NULL;
957 new_branch_info->name = "(empty)";
958 do_merge = 1;
959 }
960
c8a3ea1f
BW
961 if (!new_branch_info->name) {
962 new_branch_info->name = "HEAD";
963 new_branch_info->commit = old_branch_info.commit;
964 if (!new_branch_info->commit)
e8a8a4d7 965 die(_("You are on a branch yet to be born"));
c8a3ea1f 966 parse_commit_or_die(new_branch_info->commit);
65f099b3
NTND
967
968 if (opts->only_merge_on_switching_branches)
969 do_merge = 0;
782c2d65
DB
970 }
971
65f099b3 972 if (do_merge) {
fa655d84
BP
973 ret = merge_working_tree(opts, &old_branch_info, new_branch_info, &writeout_error);
974 if (ret) {
975 free(path_to_free);
976 return ret;
977 }
96ec7b1e 978 }
782c2d65 979
c8a3ea1f
BW
980 if (!opts->quiet && !old_branch_info.path && old_branch_info.commit && new_branch_info->commit != old_branch_info.commit)
981 orphaned_commit_warning(old_branch_info.commit, new_branch_info->commit);
77ebd56d 982
c8a3ea1f 983 update_refs_for_switch(opts, &old_branch_info, new_branch_info);
782c2d65 984
c8a3ea1f 985 ret = post_checkout_hook(old_branch_info.commit, new_branch_info->commit, 1);
96ec7b1e 986 free(path_to_free);
a2b4994c 987 return ret || writeout_error;
782c2d65
DB
988}
989
0cf8581e
JH
990static int git_checkout_config(const char *var, const char *value, void *cb)
991{
175f6e59
JS
992 if (!strcmp(var, "diff.ignoresubmodules")) {
993 struct checkout_opts *opts = cb;
994 handle_ignore_submodules_arg(&opts->diff_options, value);
995 return 0;
996 }
23b4c7bc 997
59556548 998 if (starts_with(var, "submodule."))
7463e2ec 999 return git_default_submodule_config(var, value, NULL);
23b4c7bc 1000
175f6e59 1001 return git_xmerge_config(var, value, NULL);
0cf8581e
JH
1002}
1003
7ab4ad00
NTND
1004static void setup_new_branch_info_and_source_tree(
1005 struct branch_info *new_branch_info,
1006 struct checkout_opts *opts,
1007 struct object_id *rev,
1008 const char *arg)
1009{
1010 struct tree **source_tree = &opts->source_tree;
1011 struct object_id branch_rev;
1012
1013 new_branch_info->name = arg;
1014 setup_branch_path(new_branch_info);
1015
1016 if (!check_refname_format(new_branch_info->path, 0) &&
1017 !read_ref(new_branch_info->path, &branch_rev))
1018 oidcpy(rev, &branch_rev);
1019 else
1020 new_branch_info->path = NULL; /* not an existing branch */
1021
1022 new_branch_info->commit = lookup_commit_reference_gently(the_repository, rev, 1);
1023 if (!new_branch_info->commit) {
1024 /* not a commit */
1025 *source_tree = parse_tree_indirect(rev);
1026 } else {
1027 parse_commit_or_die(new_branch_info->commit);
1028 *source_tree = get_commit_tree(new_branch_info->commit);
1029 }
1030}
1031
09ebad6f
JN
1032static int parse_branchname_arg(int argc, const char **argv,
1033 int dwim_new_local_branch_ok,
c8a3ea1f 1034 struct branch_info *new_branch_info,
10f102be 1035 struct checkout_opts *opts,
3c87aa94
ÆAB
1036 struct object_id *rev,
1037 int *dwim_remotes_matched)
09ebad6f 1038{
10f102be 1039 const char **new_branch = &opts->new_branch;
09ebad6f 1040 int argcount = 0;
09ebad6f 1041 const char *arg;
bca39695
MM
1042 int dash_dash_pos;
1043 int has_dash_dash = 0;
1044 int i;
09ebad6f
JN
1045
1046 /*
1047 * case 1: git checkout <ref> -- [<paths>]
1048 *
1049 * <ref> must be a valid tree, everything after the '--' must be
1050 * a path.
1051 *
1052 * case 2: git checkout -- [<paths>]
1053 *
1054 * everything after the '--' must be paths.
1055 *
a047fafc 1056 * case 3: git checkout <something> [--]
09ebad6f 1057 *
a047fafc
MM
1058 * (a) If <something> is a commit, that is to
1059 * switch to the branch or detach HEAD at it. As a special case,
1060 * if <something> is A...B (missing A or B means HEAD but you can
1061 * omit at most one side), and if there is a unique merge base
1062 * between A and B, A...B names that merge base.
09ebad6f 1063 *
a047fafc 1064 * (b) If <something> is _not_ a commit, either "--" is present
01689909 1065 * or <something> is not a path, no -t or -b was given, and
a047fafc 1066 * and there is a tracking branch whose name is <something>
8d7b558b
ÆAB
1067 * in one and only one remote (or if the branch exists on the
1068 * remote named in checkout.defaultRemote), then this is a
1069 * short-hand to fork local <something> from that
1070 * remote-tracking branch.
09ebad6f 1071 *
a047fafc
MM
1072 * (c) Otherwise, if "--" is present, treat it like case (1).
1073 *
1074 * (d) Otherwise :
1075 * - if it's a reference, treat it like case (1)
1076 * - else if it's a path, treat it like case (2)
1077 * - else: fail.
1078 *
1079 * case 4: git checkout <something> <paths>
1080 *
1081 * The first argument must not be ambiguous.
09ebad6f
JN
1082 * - If it's *only* a reference, treat it like case (1).
1083 * - If it's only a path, treat it like case (2).
1084 * - else: fail.
1085 *
1086 */
1087 if (!argc)
1088 return 0;
1089
5c06e269
NTND
1090 if (!opts->accept_pathspec) {
1091 if (argc > 1)
1092 die(_("only one reference expected"));
1093 has_dash_dash = 1; /* helps disambiguate */
1094 }
1095
09ebad6f 1096 arg = argv[0];
bca39695
MM
1097 dash_dash_pos = -1;
1098 for (i = 0; i < argc; i++) {
5c06e269 1099 if (opts->accept_pathspec && !strcmp(argv[i], "--")) {
bca39695
MM
1100 dash_dash_pos = i;
1101 break;
1102 }
1103 }
1104 if (dash_dash_pos == 0)
1105 return 1; /* case (2) */
1106 else if (dash_dash_pos == 1)
1107 has_dash_dash = 1; /* case (3) or (1) */
1108 else if (dash_dash_pos >= 2)
1109 die(_("only one reference expected, %d given."), dash_dash_pos);
0f086e6d 1110 opts->count_checkout_paths = !opts->quiet && !has_dash_dash;
09ebad6f
JN
1111
1112 if (!strcmp(arg, "-"))
1113 arg = "@{-1}";
1114
151b2911 1115 if (get_oid_mb(arg, rev)) {
a047fafc
MM
1116 /*
1117 * Either case (3) or (4), with <something> not being
1118 * a commit, or an attempt to use case (1) with an
1119 * invalid ref.
1120 *
1121 * It's likely an error, but we need to find out if
1122 * we should auto-create the branch, case (3).(b).
1123 */
1124 int recover_with_dwim = dwim_new_local_branch_ok;
1125
be4908f1
NTND
1126 int could_be_checkout_paths = !has_dash_dash &&
1127 check_filename(opts->prefix, arg);
1128
1129 if (!has_dash_dash && !no_wildcard(arg))
a047fafc 1130 recover_with_dwim = 0;
be4908f1 1131
a047fafc 1132 /*
5c06e269
NTND
1133 * Accept "git checkout foo", "git checkout foo --"
1134 * and "git switch foo" as candidates for dwim.
a047fafc
MM
1135 */
1136 if (!(argc == 1 && !has_dash_dash) &&
5c06e269
NTND
1137 !(argc == 2 && has_dash_dash) &&
1138 opts->accept_pathspec)
a047fafc
MM
1139 recover_with_dwim = 0;
1140
1141 if (recover_with_dwim) {
3c87aa94
ÆAB
1142 const char *remote = unique_tracking_name(arg, rev,
1143 dwim_remotes_matched);
a047fafc 1144 if (remote) {
be4908f1
NTND
1145 if (could_be_checkout_paths)
1146 die(_("'%s' could be both a local file and a tracking branch.\n"
1147 "Please use -- (and optionally --no-guess) to disambiguate"),
1148 arg);
a047fafc
MM
1149 *new_branch = arg;
1150 arg = remote;
1151 /* DWIMmed to create local branch, case (3).(b) */
1152 } else {
1153 recover_with_dwim = 0;
1154 }
1155 }
1156
1157 if (!recover_with_dwim) {
1158 if (has_dash_dash)
1159 die(_("invalid reference: %s"), arg);
09ebad6f
JN
1160 return argcount;
1161 }
1162 }
1163
1164 /* we can't end up being in (2) anymore, eat the argument */
1165 argcount++;
1166 argv++;
1167 argc--;
1168
7ab4ad00 1169 setup_new_branch_info_and_source_tree(new_branch_info, opts, rev, arg);
09ebad6f 1170
7ab4ad00 1171 if (!opts->source_tree) /* case (1): want a tree */
6c80cd29 1172 die(_("reference is not a tree: %s"), arg);
7ab4ad00 1173
7f82b24e 1174 if (!has_dash_dash) { /* case (3).(d) -> (1) */
09ebad6f
JN
1175 /*
1176 * Do not complain the most common case
1177 * git checkout branch
1178 * even if there happen to be a file called 'branch';
1179 * it would be extremely annoying.
1180 */
1181 if (argc)
b829b943 1182 verify_non_filename(opts->prefix, arg);
5c06e269 1183 } else if (opts->accept_pathspec) {
09ebad6f
JN
1184 argcount++;
1185 argv++;
1186 argc--;
1187 }
1188
1189 return argcount;
1190}
1191
a2b4994c 1192static int switch_unborn_to_new_branch(const struct checkout_opts *opts)
abe19980
JH
1193{
1194 int status;
1195 struct strbuf branch_ref = STRBUF_INIT;
1196
e27dd8ae
JH
1197 trace2_cmd_mode("unborn");
1198
8ced1aa0
CW
1199 if (!opts->new_branch)
1200 die(_("You are on a branch yet to be born"));
abe19980
JH
1201 strbuf_addf(&branch_ref, "refs/heads/%s", opts->new_branch);
1202 status = create_symref("HEAD", branch_ref.buf, "checkout -b");
1203 strbuf_release(&branch_ref);
afa8c07a
JK
1204 if (!opts->quiet)
1205 fprintf(stderr, _("Switched to a new branch '%s'\n"),
1206 opts->new_branch);
abe19980
JH
1207 return status;
1208}
1209
7968bef0
NTND
1210static void die_expecting_a_branch(const struct branch_info *branch_info)
1211{
1212 struct object_id oid;
1213 char *to_free;
1214
1215 if (dwim_ref(branch_info->name, strlen(branch_info->name), &oid, &to_free) == 1) {
1216 const char *ref = to_free;
1217
1218 if (skip_prefix(ref, "refs/tags/", &ref))
1219 die(_("a branch is expected, got tag '%s'"), ref);
1220 if (skip_prefix(ref, "refs/remotes/", &ref))
1221 die(_("a branch is expected, got remote branch '%s'"), ref);
1222 die(_("a branch is expected, got '%s'"), ref);
1223 }
1224 if (branch_info->commit)
1225 die(_("a branch is expected, got commit '%s'"), branch_info->name);
1226 /*
1227 * This case should never happen because we already die() on
1228 * non-commit, but just in case.
1229 */
1230 die(_("a branch is expected, got '%s'"), branch_info->name);
1231}
1232
c45f0f52
NTND
1233static void die_if_some_operation_in_progress(void)
1234{
1235 struct wt_status_state state;
1236
1237 memset(&state, 0, sizeof(state));
1238 wt_status_get_state(the_repository, &state, 0);
1239
1240 if (state.merge_in_progress)
1241 die(_("cannot switch branch while merging\n"
1242 "Consider \"git merge --quit\" "
1243 "or \"git worktree add\"."));
1244 if (state.am_in_progress)
1245 die(_("cannot switch branch in the middle of an am session\n"
1246 "Consider \"git am --quit\" "
1247 "or \"git worktree add\"."));
1248 if (state.rebase_interactive_in_progress || state.rebase_in_progress)
1249 die(_("cannot switch branch while rebasing\n"
1250 "Consider \"git rebase --quit\" "
1251 "or \"git worktree add\"."));
1252 if (state.cherry_pick_in_progress)
1253 die(_("cannot switch branch while cherry-picking\n"
1254 "Consider \"git cherry-pick --quit\" "
1255 "or \"git worktree add\"."));
1256 if (state.revert_in_progress)
1257 die(_("cannot switch branch while reverting\n"
1258 "Consider \"git revert --quit\" "
1259 "or \"git worktree add\"."));
1260 if (state.bisect_in_progress)
1261 die(_("cannot switch branch while bisecting\n"
1262 "Consider \"git bisect reset HEAD\" "
1263 "or \"git worktree add\"."));
1264}
1265
b6312c27 1266static int checkout_branch(struct checkout_opts *opts,
c8a3ea1f 1267 struct branch_info *new_branch_info)
b6312c27 1268{
817b345a 1269 if (opts->pathspec.nr)
b6312c27
NTND
1270 die(_("paths cannot be used with switching branches"));
1271
1272 if (opts->patch_mode)
1273 die(_("'%s' cannot be used with switching branches"),
1274 "--patch");
1275
091e04bc
TG
1276 if (!opts->overlay_mode)
1277 die(_("'%s' cannot be used with switching branches"),
1278 "--no-overlay");
1279
b6312c27
NTND
1280 if (opts->writeout_stage)
1281 die(_("'%s' cannot be used with switching branches"),
1282 "--ours/--theirs");
1283
1284 if (opts->force && opts->merge)
1285 die(_("'%s' cannot be used with '%s'"), "-f", "-m");
1286
3ec37ad1
NTND
1287 if (opts->discard_changes && opts->merge)
1288 die(_("'%s' cannot be used with '%s'"), "--discard-changes", "--merge");
1289
b6312c27
NTND
1290 if (opts->force_detach && opts->new_branch)
1291 die(_("'%s' cannot be used with '%s'"),
1292 "--detach", "-b/-B/--orphan");
1293
1294 if (opts->new_orphan_branch) {
1295 if (opts->track != BRANCH_TRACK_UNSPECIFIED)
1296 die(_("'%s' cannot be used with '%s'"), "--orphan", "-t");
1806c29f
NTND
1297 if (opts->orphan_from_empty_tree && new_branch_info->name)
1298 die(_("'%s' cannot take <start-point>"), "--orphan");
b6312c27
NTND
1299 } else if (opts->force_detach) {
1300 if (opts->track != BRANCH_TRACK_UNSPECIFIED)
1301 die(_("'%s' cannot be used with '%s'"), "--detach", "-t");
1302 } else if (opts->track == BRANCH_TRACK_UNSPECIFIED)
1303 opts->track = git_branch_track;
1304
c8a3ea1f 1305 if (new_branch_info->name && !new_branch_info->commit)
b6312c27 1306 die(_("Cannot switch branch to a non-commit '%s'"),
c8a3ea1f 1307 new_branch_info->name);
b6312c27 1308
e342c63a
NTND
1309 if (!opts->switch_branch_doing_nothing_is_ok &&
1310 !new_branch_info->name &&
1311 !opts->new_branch &&
1312 !opts->force_detach)
1313 die(_("missing branch or commit argument"));
1314
7968bef0
NTND
1315 if (!opts->implicit_detach &&
1316 !opts->force_detach &&
1317 !opts->new_branch &&
1318 !opts->new_branch_force &&
1319 new_branch_info->name &&
1320 !new_branch_info->path)
1321 die_expecting_a_branch(new_branch_info);
1322
c45f0f52
NTND
1323 if (!opts->can_switch_when_in_progress)
1324 die_if_some_operation_in_progress();
1325
c8a3ea1f 1326 if (new_branch_info->path && !opts->force_detach && !opts->new_branch &&
c265c533 1327 !opts->ignore_other_worktrees) {
e1c1ab9d 1328 int flag;
efbd4fdf 1329 char *head_ref = resolve_refdup("HEAD", 0, NULL, &flag);
e1c1ab9d 1330 if (head_ref &&
c8a3ea1f
BW
1331 (!(flag & REF_ISSYMREF) || strcmp(head_ref, new_branch_info->path)))
1332 die_if_checked_out(new_branch_info->path, 1);
e1c1ab9d
NTND
1333 free(head_ref);
1334 }
1335
c8a3ea1f 1336 if (!new_branch_info->commit && opts->new_branch) {
60af7691 1337 struct object_id rev;
b6312c27
NTND
1338 int flag;
1339
34c290a6 1340 if (!read_ref_full("HEAD", 0, &rev, &flag) &&
60af7691 1341 (flag & REF_ISSYMREF) && is_null_oid(&rev))
b6312c27
NTND
1342 return switch_unborn_to_new_branch(opts);
1343 }
c8a3ea1f 1344 return switch_branches(opts, new_branch_info);
b6312c27
NTND
1345}
1346
20871822
NTND
1347static struct option *add_common_options(struct checkout_opts *opts,
1348 struct option *prevopts)
782c2d65 1349{
782c2d65 1350 struct option options[] = {
b3edccb9 1351 OPT__QUIET(&opts->quiet, N_("suppress progress reporting")),
20871822
NTND
1352 { OPTION_CALLBACK, 0, "recurse-submodules", NULL,
1353 "checkout", "control recursive updating of submodules",
1354 PARSE_OPT_OPTARG, option_parse_recurse_submodules_worktree_updater },
1355 OPT_BOOL(0, "progress", &opts->show_progress, N_("force progress reporting")),
1356 OPT__FORCE(&opts->force, N_("force checkout (throw away local modifications)"),
1357 PARSE_OPT_NOCOMPLETE),
1358 OPT_BOOL('m', "merge", &opts->merge, N_("perform a 3-way merge with the new branch")),
1359 OPT_STRING(0, "conflict", &opts->conflict_style, N_("style"),
1360 N_("conflict style (merge or diff3)")),
1361 OPT_END()
1362 };
1363 struct option *newopts = parse_options_concat(prevopts, options);
1364 free(prevopts);
1365 return newopts;
1366}
1367
b7b5fce2
NTND
1368static struct option *add_common_switch_branch_options(
1369 struct checkout_opts *opts, struct option *prevopts)
20871822
NTND
1370{
1371 struct option options[] = {
163e3b29 1372 OPT_BOOL('d', "detach", &opts->force_detach, N_("detach HEAD at named commit")),
b3edccb9 1373 OPT_SET_INT('t', "track", &opts->track, N_("set upstream info for new branch"),
9ed36cfa 1374 BRANCH_TRACK_EXPLICIT),
b3edccb9 1375 OPT_STRING(0, "orphan", &opts->new_orphan_branch, N_("new-branch"), N_("new unparented branch")),
20871822
NTND
1376 OPT_BOOL_F(0, "overwrite-ignore", &opts->overwrite_ignore,
1377 N_("update ignored files (default)"),
1378 PARSE_OPT_NOCOMPLETE),
20871822
NTND
1379 OPT_BOOL(0, "ignore-other-worktrees", &opts->ignore_other_worktrees,
1380 N_("do not check if another worktree is holding the given ref")),
1381 OPT_END()
1382 };
1383 struct option *newopts = parse_options_concat(prevopts, options);
1384 free(prevopts);
1385 return newopts;
1386}
1387
1388static struct option *add_checkout_path_options(struct checkout_opts *opts,
1389 struct option *prevopts)
1390{
1391 struct option options[] = {
b3edccb9 1392 OPT_SET_INT_F('2', "ours", &opts->writeout_stage,
3fe735e7
NTND
1393 N_("checkout our version for unmerged files"),
1394 2, PARSE_OPT_NONEG),
b3edccb9 1395 OPT_SET_INT_F('3', "theirs", &opts->writeout_stage,
3fe735e7
NTND
1396 N_("checkout their version for unmerged files"),
1397 3, PARSE_OPT_NONEG),
b3edccb9
NTND
1398 OPT_BOOL('p', "patch", &opts->patch_mode, N_("select hunks interactively")),
1399 OPT_BOOL(0, "ignore-skip-worktree-bits", &opts->ignore_skipworktree,
08d595dc 1400 N_("do not limit pathspecs to sparse entries only")),
b3edccb9 1401 OPT_BOOL(0, "overlay", &opts->overlay_mode, N_("use overlay mode (default)")),
20871822 1402 OPT_END()
782c2d65 1403 };
20871822
NTND
1404 struct option *newopts = parse_options_concat(prevopts, options);
1405 free(prevopts);
1406 return newopts;
1407}
1408
d787d311
NTND
1409static int checkout_main(int argc, const char **argv, const char *prefix,
1410 struct checkout_opts *opts, struct option *options,
1411 const char * const usagestr[])
20871822 1412{
20871822
NTND
1413 struct branch_info new_branch_info;
1414 int dwim_remotes_matched = 0;
c9c935f6 1415 int parseopt_flags = 0;
782c2d65 1416
c8a3ea1f 1417 memset(&new_branch_info, 0, sizeof(new_branch_info));
b3edccb9
NTND
1418 opts->overwrite_ignore = 1;
1419 opts->prefix = prefix;
1420 opts->show_progress = -1;
1421 opts->overlay_mode = -1;
782c2d65 1422
b3edccb9 1423 git_config(git_checkout_config, opts);
782c2d65 1424
b3edccb9 1425 opts->track = BRANCH_TRACK_UNSPECIFIED;
782c2d65 1426
c9c935f6
NTND
1427 if (!opts->accept_pathspec && !opts->accept_ref)
1428 BUG("make up your mind, you need to take _something_");
1429 if (opts->accept_pathspec && opts->accept_ref)
1430 parseopt_flags = PARSE_OPT_KEEP_DASHDASH;
1431
1432 argc = parse_options(argc, argv, prefix, options,
1433 usagestr, parseopt_flags);
859fdaba 1434
b3edccb9
NTND
1435 if (opts->show_progress < 0) {
1436 if (opts->quiet)
1437 opts->show_progress = 0;
870ebdb9 1438 else
b3edccb9 1439 opts->show_progress = isatty(2);
870ebdb9
ECA
1440 }
1441
55cf704a 1442 if (opts->conflict_style) {
b3edccb9 1443 opts->merge = 1; /* implied */
55cf704a 1444 git_xmerge_config("merge.conflictstyle", opts->conflict_style, NULL);
b6312c27 1445 }
3ec37ad1
NTND
1446 if (opts->force)
1447 opts->discard_changes = 1;
02ac9837 1448
b3edccb9 1449 if ((!!opts->new_branch + !!opts->new_branch_force + !!opts->new_orphan_branch) > 1)
b6312c27 1450 die(_("-b, -B and --orphan are mutually exclusive"));
02ac9837 1451
b3edccb9 1452 if (opts->overlay_mode == 1 && opts->patch_mode)
091e04bc
TG
1453 die(_("-p and --overlay are mutually exclusive"));
1454
b6312c27
NTND
1455 /*
1456 * From here on, new_branch will contain the branch to be checked out,
1457 * and new_branch_force and new_orphan_branch will tell us which one of
1458 * -b/-B/--orphan is being used.
1459 */
b3edccb9
NTND
1460 if (opts->new_branch_force)
1461 opts->new_branch = opts->new_branch_force;
02ac9837 1462
b3edccb9
NTND
1463 if (opts->new_orphan_branch)
1464 opts->new_branch = opts->new_orphan_branch;
32669671 1465
b6312c27 1466 /* --track without -b/-B/--orphan should DWIM */
b3edccb9 1467 if (opts->track != BRANCH_TRACK_UNSPECIFIED && !opts->new_branch) {
9188ed89
AR
1468 const char *argv0 = argv[0];
1469 if (!argc || !strcmp(argv0, "--"))
1a07e59c 1470 die(_("--track needs a branch name"));
e3f1da98
RS
1471 skip_prefix(argv0, "refs/", &argv0);
1472 skip_prefix(argv0, "remotes/", &argv0);
9188ed89
AR
1473 argv0 = strchr(argv0, '/');
1474 if (!argv0 || !argv0[1])
1a07e59c 1475 die(_("missing branch name; try -b"));
b3edccb9 1476 opts->new_branch = argv0 + 1;
bb0ceb62
JS
1477 }
1478
859fdaba 1479 /*
09ebad6f
JN
1480 * Extract branch name from command line arguments, so
1481 * all that is left is pathspecs.
859fdaba 1482 *
09ebad6f 1483 * Handle
70c9ac2f 1484 *
09ebad6f
JN
1485 * 1) git checkout <tree> -- [<paths>]
1486 * 2) git checkout -- [<paths>]
1487 * 3) git checkout <something> [<paths>]
859fdaba 1488 *
09ebad6f
JN
1489 * including "last branch" syntax and DWIM-ery for names of
1490 * remote branches, erroring out for invalid or ambiguous cases.
859fdaba 1491 */
c9c935f6 1492 if (argc && opts->accept_ref) {
60af7691 1493 struct object_id rev;
09ebad6f 1494 int dwim_ok =
b3edccb9 1495 !opts->patch_mode &&
ccb111b3 1496 opts->dwim_new_local_branch &&
b3edccb9
NTND
1497 opts->track == BRANCH_TRACK_UNSPECIFIED &&
1498 !opts->new_branch;
f8bd36a4 1499 int n = parse_branchname_arg(argc, argv, dwim_ok,
b3edccb9 1500 &new_branch_info, opts, &rev,
3c87aa94 1501 &dwim_remotes_matched);
09ebad6f
JN
1502 argv += n;
1503 argc -= n;
c9c935f6
NTND
1504 } else if (!opts->accept_ref && opts->from_treeish) {
1505 struct object_id rev;
1506
1507 if (get_oid_mb(opts->from_treeish, &rev))
1508 die(_("could not resolve %s"), opts->from_treeish);
1509
1510 setup_new_branch_info_and_source_tree(&new_branch_info,
1511 opts, &rev,
1512 opts->from_treeish);
1513
1514 if (!opts->source_tree)
1515 die(_("reference is not a tree: %s"), opts->from_treeish);
782c2d65
DB
1516 }
1517
782c2d65 1518 if (argc) {
b3edccb9
NTND
1519 parse_pathspec(&opts->pathspec, 0,
1520 opts->patch_mode ? PATHSPEC_PREFIX_ORIGIN : 0,
480ca644 1521 prefix, argv);
301e42ed 1522
b3edccb9 1523 if (!opts->pathspec.nr)
e8a8a4d7 1524 die(_("invalid path specification"));
301e42ed 1525
b6312c27
NTND
1526 /*
1527 * Try to give more helpful suggestion.
1528 * new_branch && argc > 1 will be caught later.
1529 */
b3edccb9 1530 if (opts->new_branch && argc == 1)
6c486862 1531 die(_("'%s' is not a commit and a branch '%s' cannot be created from it"),
b3edccb9 1532 argv[0], opts->new_branch);
782c2d65 1533
b3edccb9 1534 if (opts->force_detach)
b6312c27
NTND
1535 die(_("git checkout: --detach does not take a path argument '%s'"),
1536 argv[0]);
32669671 1537
b3edccb9 1538 if (1 < !!opts->writeout_stage + !!opts->force + !!opts->merge)
b6312c27
NTND
1539 die(_("git checkout: --ours/--theirs, --force and --merge are incompatible when\n"
1540 "checking out of the index."));
782c2d65
DB
1541 }
1542
b3edccb9 1543 if (opts->new_branch) {
f285a2d7 1544 struct strbuf buf = STRBUF_INIT;
55c4a673 1545
b3edccb9
NTND
1546 if (opts->new_branch_force)
1547 opts->branch_exists = validate_branchname(opts->new_branch, &buf);
bc1c9c0e 1548 else
b3edccb9
NTND
1549 opts->branch_exists =
1550 validate_new_branchname(opts->new_branch, &buf, 0);
352eadc4
DB
1551 strbuf_release(&buf);
1552 }
1553
886e1084 1554 UNLEAK(opts);
b3edccb9
NTND
1555 if (opts->patch_mode || opts->pathspec.nr) {
1556 int ret = checkout_paths(opts, new_branch_info.name);
ad8d5104
ÆAB
1557 if (ret && dwim_remotes_matched > 1 &&
1558 advice_checkout_ambiguous_remote_branch_name)
1559 advise(_("'%s' matched more than one remote tracking branch.\n"
1560 "We found %d remotes with a reference that matched. So we fell back\n"
1561 "on trying to resolve the argument as a path, but failed there too!\n"
1562 "\n"
1563 "If you meant to check out a remote tracking branch on, e.g. 'origin',\n"
1564 "you can do so by fully qualifying the name with the --track option:\n"
1565 "\n"
8d7b558b
ÆAB
1566 " git checkout --track origin/<name>\n"
1567 "\n"
1568 "If you'd like to always have checkouts of an ambiguous <name> prefer\n"
1569 "one remote, e.g. the 'origin' remote, consider setting\n"
1570 "checkout.defaultRemote=origin in your config."),
ad8d5104
ÆAB
1571 argv[0],
1572 dwim_remotes_matched);
1c550553
ÆAB
1573 return ret;
1574 } else {
b3edccb9 1575 return checkout_branch(opts, &new_branch_info);
1c550553 1576 }
782c2d65 1577}
d787d311
NTND
1578
1579int cmd_checkout(int argc, const char **argv, const char *prefix)
1580{
1581 struct checkout_opts opts;
b7b5fce2
NTND
1582 struct option *options;
1583 struct option checkout_options[] = {
1584 OPT_STRING('b', NULL, &opts.new_branch, N_("branch"),
1585 N_("create and checkout a new branch")),
1586 OPT_STRING('B', NULL, &opts.new_branch_force, N_("branch"),
1587 N_("create/reset and checkout a branch")),
492ededc 1588 OPT_BOOL('l', NULL, &opts.new_branch_log, N_("create reflog for new branch")),
ccb111b3
NTND
1589 OPT_BOOL(0, "guess", &opts.dwim_new_local_branch,
1590 N_("second guess 'git checkout <no-such-branch>' (default)")),
b7b5fce2
NTND
1591 OPT_END()
1592 };
d787d311
NTND
1593 int ret;
1594
1595 memset(&opts, 0, sizeof(opts));
ccb111b3 1596 opts.dwim_new_local_branch = 1;
e342c63a 1597 opts.switch_branch_doing_nothing_is_ok = 1;
65f099b3 1598 opts.only_merge_on_switching_branches = 0;
c9c935f6 1599 opts.accept_ref = 1;
5c06e269 1600 opts.accept_pathspec = 1;
7968bef0 1601 opts.implicit_detach = 1;
c45f0f52 1602 opts.can_switch_when_in_progress = 1;
1806c29f 1603 opts.orphan_from_empty_tree = 0;
d787d311 1604
b7b5fce2 1605 options = parse_options_dup(checkout_options);
d787d311 1606 options = add_common_options(&opts, options);
b7b5fce2 1607 options = add_common_switch_branch_options(&opts, options);
d787d311
NTND
1608 options = add_checkout_path_options(&opts, options);
1609
1610 ret = checkout_main(argc, argv, prefix, &opts,
1611 options, checkout_usage);
1612 FREE_AND_NULL(options);
1613 return ret;
1614}
1615
1616int cmd_switch(int argc, const char **argv, const char *prefix)
1617{
1618 struct checkout_opts opts;
1619 struct option *options = NULL;
b7b5fce2
NTND
1620 struct option switch_options[] = {
1621 OPT_STRING('c', "create", &opts.new_branch, N_("branch"),
1622 N_("create and switch to a new branch")),
1623 OPT_STRING('C', "force-create", &opts.new_branch_force, N_("branch"),
1624 N_("create/reset and switch to a branch")),
ccb111b3
NTND
1625 OPT_BOOL(0, "guess", &opts.dwim_new_local_branch,
1626 N_("second guess 'git switch <no-such-branch>'")),
3ec37ad1
NTND
1627 OPT_BOOL(0, "discard-changes", &opts.discard_changes,
1628 N_("throw away local modifications")),
b7b5fce2
NTND
1629 OPT_END()
1630 };
d787d311
NTND
1631 int ret;
1632
1633 memset(&opts, 0, sizeof(opts));
ccb111b3 1634 opts.dwim_new_local_branch = 1;
c9c935f6 1635 opts.accept_ref = 1;
5c06e269 1636 opts.accept_pathspec = 0;
e342c63a 1637 opts.switch_branch_doing_nothing_is_ok = 0;
65f099b3 1638 opts.only_merge_on_switching_branches = 1;
7968bef0 1639 opts.implicit_detach = 0;
c45f0f52 1640 opts.can_switch_when_in_progress = 0;
1806c29f 1641 opts.orphan_from_empty_tree = 1;
d787d311 1642
b7b5fce2 1643 options = parse_options_dup(switch_options);
d787d311 1644 options = add_common_options(&opts, options);
b7b5fce2 1645 options = add_common_switch_branch_options(&opts, options);
d787d311
NTND
1646
1647 ret = checkout_main(argc, argv, prefix, &opts,
1648 options, switch_branch_usage);
1649 FREE_AND_NULL(options);
1650 return ret;
1651}
46e91b66
NTND
1652
1653int cmd_restore(int argc, const char **argv, const char *prefix)
1654{
1655 struct checkout_opts opts;
c9c935f6
NTND
1656 struct option *options;
1657 struct option restore_options[] = {
1658 OPT_STRING('s', "source", &opts.from_treeish, "<tree-ish>",
1659 N_("where the checkout from")),
1660 OPT_END()
1661 };
46e91b66
NTND
1662 int ret;
1663
1664 memset(&opts, 0, sizeof(opts));
c9c935f6 1665 opts.accept_ref = 0;
46e91b66
NTND
1666 opts.accept_pathspec = 1;
1667
c9c935f6 1668 options = parse_options_dup(restore_options);
46e91b66
NTND
1669 options = add_common_options(&opts, options);
1670 options = add_checkout_path_options(&opts, options);
1671
1672 ret = checkout_main(argc, argv, prefix, &opts,
1673 options, restore_usage);
1674 FREE_AND_NULL(options);
1675 return ret;
1676}