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