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