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