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