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