]> git.ipfire.org Git - thirdparty/git.git/blame - builtin/checkout.c
Sync with 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);
2841e8f8 527
183fb44f
NTND
528 /*
529 * Allow updating the index when checking out from the index.
530 * This is to save new stat info.
531 */
532 if (opts->checkout_worktree && !opts->checkout_index && !opts->source_tree)
533 checkout_index = 1;
534 else
535 checkout_index = opts->checkout_index;
0f086e6d 536
183fb44f
NTND
537 if (checkout_index) {
538 if (write_locked_index(&the_index, &lock_file, COMMIT_LOCK))
539 die(_("unable to write new index file"));
540 } else {
541 /*
542 * NEEDSWORK: if --worktree is not specified, we
543 * should save stat info of checked out files in the
544 * index to avoid the next (potentially costly)
545 * refresh. But it's a bit tricker to do...
546 */
547 rollback_lock_file(&lock_file);
0f086e6d 548 }
782c2d65 549
34c290a6 550 read_ref_full("HEAD", 0, &rev, NULL);
21e1ee8f 551 head = lookup_commit_reference_gently(the_repository, &rev, 1);
782c2d65 552
d2b3691b
JH
553 errs |= post_checkout_hook(head, head, 0);
554 return errs;
782c2d65
DB
555}
556
a2b4994c
NTND
557static void show_local_changes(struct object *head,
558 const struct diff_options *opts)
782c2d65
DB
559{
560 struct rev_info rev;
561 /* I think we want full paths, even if we're in a subdirectory. */
2abf3503 562 repo_init_revisions(the_repository, &rev, NULL);
175f6e59 563 rev.diffopt.flags = opts->flags;
782c2d65 564 rev.diffopt.output_format |= DIFF_FORMAT_NAME_STATUS;
28452655 565 diff_setup_done(&rev.diffopt);
782c2d65
DB
566 add_pending_object(&rev, head, NULL);
567 run_diff_index(&rev, 0);
568}
569
b3c0494a 570static void describe_detached_head(const char *msg, struct commit *commit)
782c2d65 571{
f285a2d7 572 struct strbuf sb = STRBUF_INIT;
ca69d4d5 573
3c621839
JK
574 if (!parse_commit(commit))
575 pp_commit_easy(CMIT_FMT_ONELINE, commit, &sb);
ca69d4d5
AR
576 if (print_sha1_ellipsis()) {
577 fprintf(stderr, "%s %s... %s\n", msg,
aab9583f 578 find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV), sb.buf);
ca69d4d5
AR
579 } else {
580 fprintf(stderr, "%s %s %s\n", msg,
aab9583f 581 find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV), sb.buf);
ca69d4d5 582 }
782c2d65
DB
583 strbuf_release(&sb);
584}
585
a2b4994c
NTND
586static int reset_tree(struct tree *tree, const struct checkout_opts *o,
587 int worktree, int *writeout_error)
782c2d65
DB
588{
589 struct unpack_trees_options opts;
590 struct tree_desc tree_desc;
bc052d7f 591
782c2d65
DB
592 memset(&opts, 0, sizeof(opts));
593 opts.head_idx = -1;
6286a08d
JH
594 opts.update = worktree;
595 opts.skip_unmerged = !worktree;
782c2d65
DB
596 opts.reset = 1;
597 opts.merge = 1;
598 opts.fn = oneway_merge;
870ebdb9 599 opts.verbose_update = o->show_progress;
34110cd4
LT
600 opts.src_index = &the_index;
601 opts.dst_index = &the_index;
782c2d65
DB
602 parse_tree(tree);
603 init_tree_desc(&tree_desc, tree->buffer, tree->size);
291d823e
JH
604 switch (unpack_trees(1, &tree_desc, &opts)) {
605 case -2:
a2b4994c 606 *writeout_error = 1;
291d823e
JH
607 /*
608 * We return 0 nevertheless, as the index is all right
609 * and more importantly we have made best efforts to
610 * update paths in the work tree, and we cannot revert
611 * them.
612 */
1cf01a34 613 /* fallthrough */
291d823e
JH
614 case 0:
615 return 0;
616 default:
84a5750b 617 return 128;
291d823e 618 }
782c2d65
DB
619}
620
782c2d65
DB
621struct branch_info {
622 const char *name; /* The short name used */
623 const char *path; /* The full name of a real branch */
624 struct commit *commit; /* The named commit */
5883034c
NTND
625 /*
626 * if not null the branch is detached because it's already
627 * checked out in this checkout
628 */
629 char *checkout;
782c2d65
DB
630};
631
632static void setup_branch_path(struct branch_info *branch)
633{
f285a2d7 634 struct strbuf buf = STRBUF_INIT;
ae5a6c36 635
fd4692ff 636 strbuf_branchname(&buf, branch->name, INTERPRET_BRANCH_LOCAL);
a552de75 637 if (strcmp(buf.buf, branch->name))
ae5a6c36 638 branch->name = xstrdup(buf.buf);
a552de75 639 strbuf_splice(&buf, 0, 0, "refs/heads/", 11);
782c2d65
DB
640 branch->path = strbuf_detach(&buf, NULL);
641}
642
a2b4994c 643static int merge_working_tree(const struct checkout_opts *opts,
c8a3ea1f
BW
644 struct branch_info *old_branch_info,
645 struct branch_info *new_branch_info,
a2b4994c 646 int *writeout_error)
782c2d65
DB
647{
648 int ret;
837e34eb 649 struct lock_file lock_file = LOCK_INIT;
1806c29f 650 struct tree *new_tree;
b96524f8 651
837e34eb 652 hold_locked_index(&lock_file, LOCK_DIE_ON_ERROR);
53996fe5 653 if (read_cache_preload(NULL) < 0)
e923a8ab 654 return error(_("index file corrupt"));
782c2d65 655
cfc5789a 656 resolve_undo_clear();
1806c29f
NTND
657 if (opts->new_orphan_branch && opts->orphan_from_empty_tree) {
658 if (new_branch_info->commit)
659 BUG("'switch --orphan' should never accept a commit as starting point");
660 new_tree = parse_tree_indirect(the_hash_algo->empty_tree);
661 } else
662 new_tree = get_commit_tree(new_branch_info->commit);
3ec37ad1 663 if (opts->discard_changes) {
1806c29f 664 ret = reset_tree(new_tree, opts, 1, writeout_error);
782c2d65
DB
665 if (ret)
666 return ret;
667 } else {
668 struct tree_desc trees[2];
669 struct tree *tree;
670 struct unpack_trees_options topts;
bc052d7f 671
782c2d65
DB
672 memset(&topts, 0, sizeof(topts));
673 topts.head_idx = -1;
34110cd4
LT
674 topts.src_index = &the_index;
675 topts.dst_index = &the_index;
782c2d65 676
e294030f 677 setup_unpack_trees_porcelain(&topts, "checkout");
8ccba008 678
782c2d65
DB
679 refresh_cache(REFRESH_QUIET);
680
681 if (unmerged_cache()) {
e8a8a4d7 682 error(_("you need to resolve your current index first"));
04c9e11f 683 return 1;
782c2d65 684 }
04c9e11f
JH
685
686 /* 2-way merge to the new branch */
fa7b3c2f 687 topts.initial_checkout = is_cache_unborn();
04c9e11f
JH
688 topts.update = 1;
689 topts.merge = 1;
b165fac8 690 topts.quiet = opts->merge && old_branch_info->commit;
870ebdb9 691 topts.verbose_update = opts->show_progress;
04c9e11f 692 topts.fn = twoway_merge;
c1d7036b
NTND
693 if (opts->overwrite_ignore) {
694 topts.dir = xcalloc(1, sizeof(*topts.dir));
695 topts.dir->flags |= DIR_SHOW_IGNORED;
696 setup_standard_excludes(topts.dir);
697 }
c8a3ea1f
BW
698 tree = parse_tree_indirect(old_branch_info->commit ?
699 &old_branch_info->commit->object.oid :
eb0ccfd7 700 the_hash_algo->empty_tree);
04c9e11f 701 init_tree_desc(&trees[0], tree->buffer, tree->size);
1806c29f
NTND
702 parse_tree(new_tree);
703 tree = new_tree;
04c9e11f
JH
704 init_tree_desc(&trees[1], tree->buffer, tree->size);
705
291d823e 706 ret = unpack_trees(2, trees, &topts);
1c41d280 707 clear_unpack_trees_porcelain(&topts);
49d833dc 708 if (ret == -1) {
782c2d65
DB
709 /*
710 * Unpack couldn't do a trivial merge; either
711 * give up or do a real merge, depending on
712 * whether the merge flag was used.
713 */
782c2d65 714 struct tree *work;
6eff409e 715 struct tree *old_tree;
8a2fce18 716 struct merge_options o;
a7256deb 717 struct strbuf sb = STRBUF_INIT;
65c01c64 718 struct strbuf old_commit_shortname = STRBUF_INIT;
a7256deb 719
782c2d65
DB
720 if (!opts->merge)
721 return 1;
64da3ae5
JH
722
723 /*
c8a3ea1f 724 * Without old_branch_info->commit, the below is the same as
64da3ae5
JH
725 * the two-tree unpack we already tried and failed.
726 */
c8a3ea1f 727 if (!old_branch_info->commit)
64da3ae5 728 return 1;
6eff409e
NTND
729 old_tree = get_commit_tree(old_branch_info->commit);
730
731 if (repo_index_has_changes(the_repository, old_tree, &sb))
732 die(_("cannot continue with staged changes in "
733 "the following files:\n%s"), sb.buf);
734 strbuf_release(&sb);
782c2d65
DB
735
736 /* Do more real merge */
737
738 /*
739 * We update the index fully, then write the
740 * tree from the index, then merge the new
741 * branch with the current tree, with the old
742 * branch as the base. Then we reset the index
743 * (but not the working tree) to the new
744 * branch, leaving the working tree as the
745 * merged version, but skipping unmerged
746 * entries in the index.
747 */
748
610d55af 749 add_files_to_cache(NULL, NULL, 0);
7610fa57
JN
750 /*
751 * NEEDSWORK: carrying over local changes
752 * when branches have different end-of-line
753 * normalization (or clean+smudge rules) is
754 * a pain; plumb in an option to set
755 * o.renormalize?
756 */
0d6caa2d 757 init_merge_options(&o, the_repository);
8a2fce18 758 o.verbosity = 0;
724dd767 759 work = write_in_core_index_as_tree(the_repository);
782c2d65 760
1806c29f 761 ret = reset_tree(new_tree,
2e27bd77 762 opts, 1,
a2b4994c 763 writeout_error);
782c2d65
DB
764 if (ret)
765 return ret;
c8a3ea1f 766 o.ancestor = old_branch_info->name;
65c01c64
EN
767 if (old_branch_info->name == NULL) {
768 strbuf_add_unique_abbrev(&old_commit_shortname,
769 &old_branch_info->commit->object.oid,
770 DEFAULT_ABBREV);
771 o.ancestor = old_commit_shortname.buf;
772 }
c8a3ea1f 773 o.branch1 = new_branch_info->name;
8a2fce18 774 o.branch2 = "local";
2e27bd77 775 ret = merge_trees(&o,
1806c29f 776 new_tree,
2e27bd77 777 work,
b4db8a2b 778 old_tree);
f241ff0d
JS
779 if (ret < 0)
780 exit(128);
1806c29f 781 ret = reset_tree(new_tree,
2e27bd77 782 opts, 0,
a2b4994c 783 writeout_error);
548009c0 784 strbuf_release(&o.obuf);
65c01c64 785 strbuf_release(&old_commit_shortname);
84a5750b
JH
786 if (ret)
787 return ret;
782c2d65
DB
788 }
789 }
790
aecf567c
DT
791 if (!active_cache_tree)
792 active_cache_tree = cache_tree();
793
794 if (!cache_tree_fully_valid(active_cache_tree))
3fd13cbc 795 cache_tree_update(&the_index, WRITE_TREE_SILENT | WRITE_TREE_REPAIR);
aecf567c 796
837e34eb 797 if (write_locked_index(&the_index, &lock_file, COMMIT_LOCK))
e8a8a4d7 798 die(_("unable to write new index file"));
782c2d65 799
1806c29f 800 if (!opts->discard_changes && !opts->quiet && new_branch_info->commit)
c8a3ea1f 801 show_local_changes(&new_branch_info->commit->object, &opts->diff_options);
782c2d65
DB
802
803 return 0;
804}
805
c8a3ea1f 806static void report_tracking(struct branch_info *new_branch_info)
79a1e6b4 807{
6d21bf96 808 struct strbuf sb = STRBUF_INIT;
c8a3ea1f 809 struct branch *branch = branch_get(new_branch_info->name);
79a1e6b4 810
f39a757d 811 if (!format_tracking_info(branch, &sb, AHEAD_BEHIND_FULL))
79a1e6b4 812 return;
6d21bf96
JH
813 fputs(sb.buf, stdout);
814 strbuf_release(&sb);
b0030db3 815}
79a1e6b4 816
a2b4994c 817static void update_refs_for_switch(const struct checkout_opts *opts,
c8a3ea1f
BW
818 struct branch_info *old_branch_info,
819 struct branch_info *new_branch_info)
782c2d65 820{
f285a2d7 821 struct strbuf msg = STRBUF_INIT;
3bed291a 822 const char *old_desc, *reflog_msg;
782c2d65 823 if (opts->new_branch) {
3631bf77 824 if (opts->new_orphan_branch) {
341fb286
CW
825 char *refname;
826
827 refname = mkpathdup("refs/heads/%s", opts->new_orphan_branch);
828 if (opts->new_branch_log &&
829 !should_autocreate_reflog(refname)) {
1a83c240 830 int ret;
a4c653df 831 struct strbuf err = STRBUF_INIT;
3631bf77 832
abd0cd3a 833 ret = safe_create_reflog(refname, 1, &err);
1a83c240 834 if (ret) {
a4c653df
DT
835 fprintf(stderr, _("Can not do reflog for '%s': %s\n"),
836 opts->new_orphan_branch, err.buf);
837 strbuf_release(&err);
341fb286 838 free(refname);
3631bf77
EM
839 return;
840 }
abd0cd3a 841 strbuf_release(&err);
3631bf77 842 }
341fb286 843 free(refname);
3631bf77
EM
844 }
845 else
4edce172
NTND
846 create_branch(the_repository,
847 opts->new_branch, new_branch_info->name,
02ac9837 848 opts->new_branch_force ? 1 : 0,
39bd6f72 849 opts->new_branch_force ? 1 : 0,
e2bbd0cc 850 opts->new_branch_log,
f9a482e6 851 opts->quiet,
39bd6f72 852 opts->track);
c8a3ea1f
BW
853 new_branch_info->name = opts->new_branch;
854 setup_branch_path(new_branch_info);
782c2d65
DB
855 }
856
c8a3ea1f
BW
857 old_desc = old_branch_info->name;
858 if (!old_desc && old_branch_info->commit)
859 old_desc = oid_to_hex(&old_branch_info->commit->object.oid);
3bed291a
RR
860
861 reflog_msg = getenv("GIT_REFLOG_ACTION");
862 if (!reflog_msg)
863 strbuf_addf(&msg, "checkout: moving from %s to %s",
c8a3ea1f 864 old_desc ? old_desc : "(invalid)", new_branch_info->name);
3bed291a
RR
865 else
866 strbuf_insert(&msg, 0, reflog_msg, strlen(reflog_msg));
782c2d65 867
c8a3ea1f 868 if (!strcmp(new_branch_info->name, "HEAD") && !new_branch_info->path && !opts->force_detach) {
f8bd36a4 869 /* Nothing to do. */
c8a3ea1f
BW
870 } else if (opts->force_detach || !new_branch_info->path) { /* No longer on any branch. */
871 update_ref(msg.buf, "HEAD", &new_branch_info->commit->object.oid, NULL,
91774afc 872 REF_NO_DEREF, UPDATE_REFS_DIE_ON_ERR);
f8bd36a4 873 if (!opts->quiet) {
c8a3ea1f 874 if (old_branch_info->path &&
779b88a9 875 advice_detached_head && !opts->force_detach)
c8a3ea1f
BW
876 detach_advice(new_branch_info->name);
877 describe_detached_head(_("HEAD is now at"), new_branch_info->commit);
f8bd36a4 878 }
c8a3ea1f
BW
879 } else if (new_branch_info->path) { /* Switch branches. */
880 if (create_symref("HEAD", new_branch_info->path, msg.buf) < 0)
4636f651 881 die(_("unable to update HEAD"));
782c2d65 882 if (!opts->quiet) {
c8a3ea1f 883 if (old_branch_info->path && !strcmp(new_branch_info->path, old_branch_info->path)) {
39bd6f72
JN
884 if (opts->new_branch_force)
885 fprintf(stderr, _("Reset branch '%s'\n"),
c8a3ea1f 886 new_branch_info->name);
39bd6f72
JN
887 else
888 fprintf(stderr, _("Already on '%s'\n"),
c8a3ea1f 889 new_branch_info->name);
08eaa4be
ÆAB
890 } else if (opts->new_branch) {
891 if (opts->branch_exists)
c8a3ea1f 892 fprintf(stderr, _("Switched to and reset branch '%s'\n"), new_branch_info->name);
08eaa4be 893 else
c8a3ea1f 894 fprintf(stderr, _("Switched to a new branch '%s'\n"), new_branch_info->name);
08eaa4be 895 } else {
e8a8a4d7 896 fprintf(stderr, _("Switched to branch '%s'\n"),
c8a3ea1f 897 new_branch_info->name);
08eaa4be 898 }
782c2d65 899 }
c8a3ea1f
BW
900 if (old_branch_info->path && old_branch_info->name) {
901 if (!ref_exists(old_branch_info->path) && reflog_exists(old_branch_info->path))
902 delete_reflog(old_branch_info->path);
3631bf77 903 }
782c2d65 904 }
f4a4b9ac 905 remove_branch_state(the_repository, !opts->quiet);
782c2d65 906 strbuf_release(&msg);
32669671 907 if (!opts->quiet &&
c8a3ea1f
BW
908 (new_branch_info->path || (!opts->force_detach && !strcmp(new_branch_info->name, "HEAD"))))
909 report_tracking(new_branch_info);
782c2d65
DB
910}
911
468224e5 912static int add_pending_uninteresting_ref(const char *refname,
fcb615f5 913 const struct object_id *oid,
468224e5 914 int flags, void *cb_data)
8e2dc6ac 915{
a58a1b01 916 add_pending_oid(cb_data, refname, oid, UNINTERESTING);
5c08dc48
JK
917 return 0;
918}
8e2dc6ac
JH
919
920static void describe_one_orphan(struct strbuf *sb, struct commit *commit)
921{
0be240cc 922 strbuf_addstr(sb, " ");
30e677e0 923 strbuf_add_unique_abbrev(sb, &commit->object.oid, DEFAULT_ABBREV);
0be240cc 924 strbuf_addch(sb, ' ');
3c621839
JK
925 if (!parse_commit(commit))
926 pp_commit_easy(CMIT_FMT_ONELINE, commit, sb);
8e2dc6ac
JH
927 strbuf_addch(sb, '\n');
928}
929
930#define ORPHAN_CUTOFF 4
931static void suggest_reattach(struct commit *commit, struct rev_info *revs)
932{
933 struct commit *c, *last = NULL;
934 struct strbuf sb = STRBUF_INIT;
935 int lost = 0;
936 while ((c = get_revision(revs)) != NULL) {
937 if (lost < ORPHAN_CUTOFF)
938 describe_one_orphan(&sb, c);
939 last = c;
940 lost++;
941 }
942 if (ORPHAN_CUTOFF < lost) {
943 int more = lost - ORPHAN_CUTOFF;
944 if (more == 1)
945 describe_one_orphan(&sb, last);
946 else
f06f08b7 947 strbuf_addf(&sb, _(" ... and %d more.\n"), more);
8e2dc6ac
JH
948 }
949
950 fprintf(stderr,
f06f08b7
ÆAB
951 Q_(
952 /* The singular version */
953 "Warning: you are leaving %d commit behind, "
954 "not connected to\n"
955 "any of your branches:\n\n"
0faf2474 956 "%s\n",
f06f08b7
ÆAB
957 /* The plural version */
958 "Warning: you are leaving %d commits behind, "
8e2dc6ac
JH
959 "not connected to\n"
960 "any of your branches:\n\n"
f807b3dc 961 "%s\n",
f06f08b7
ÆAB
962 /* Give ngettext() the count */
963 lost),
964 lost,
f807b3dc 965 sb.buf);
8e2dc6ac 966 strbuf_release(&sb);
f807b3dc
JH
967
968 if (advice_detached_head)
969 fprintf(stderr,
fc792ca8
TS
970 Q_(
971 /* The singular version */
972 "If you want to keep it by creating a new branch, "
973 "this may be a good time\nto do so with:\n\n"
974 " git branch <new-branch-name> %s\n\n",
975 /* The plural version */
f807b3dc
JH
976 "If you want to keep them by creating a new branch, "
977 "this may be a good time\nto do so with:\n\n"
fc792ca8
TS
978 " git branch <new-branch-name> %s\n\n",
979 /* Give ngettext() the count */
980 lost),
aab9583f 981 find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV));
8e2dc6ac
JH
982}
983
984/*
985 * We are about to leave commit that was at the tip of a detached
986 * HEAD. If it is not reachable from any ref, this is the last chance
987 * for the user to do so without resorting to reflog.
988 */
c8a3ea1f 989static void orphaned_commit_warning(struct commit *old_commit, struct commit *new_commit)
8e2dc6ac 990{
8e2dc6ac 991 struct rev_info revs;
c8a3ea1f 992 struct object *object = &old_commit->object;
8e2dc6ac 993
2abf3503 994 repo_init_revisions(the_repository, &revs, NULL);
468224e5
RS
995 setup_revisions(0, NULL, &revs, NULL);
996
997 object->flags &= ~UNINTERESTING;
f2fd0760 998 add_pending_object(&revs, object, oid_to_hex(&object->oid));
468224e5 999
fcb615f5 1000 for_each_ref(add_pending_uninteresting_ref, &revs);
1806c29f
NTND
1001 if (new_commit)
1002 add_pending_oid(&revs, "HEAD",
1003 &new_commit->object.oid,
1004 UNINTERESTING);
468224e5 1005
8e2dc6ac 1006 if (prepare_revision_walk(&revs))
6c80cd29 1007 die(_("internal error in revision walk"));
c8a3ea1f
BW
1008 if (!(old_commit->object.flags & UNINTERESTING))
1009 suggest_reattach(old_commit, &revs);
8e2dc6ac 1010 else
c8a3ea1f 1011 describe_detached_head(_("Previous HEAD position was"), old_commit);
5c08dc48 1012
b2ccdf7f 1013 /* Clean up objects used, as they will be reused. */
a9a03fa0 1014 clear_commit_marks_all(ALL_REV_FLAGS);
8e2dc6ac
JH
1015}
1016
e51e3057 1017static int switch_branches(const struct checkout_opts *opts,
c8a3ea1f 1018 struct branch_info *new_branch_info)
782c2d65
DB
1019{
1020 int ret = 0;
c8a3ea1f 1021 struct branch_info old_branch_info;
96ec7b1e 1022 void *path_to_free;
60af7691 1023 struct object_id rev;
a2b4994c 1024 int flag, writeout_error = 0;
65f099b3 1025 int do_merge = 1;
e27dd8ae
JH
1026
1027 trace2_cmd_mode("branch");
1028
c8a3ea1f
BW
1029 memset(&old_branch_info, 0, sizeof(old_branch_info));
1030 old_branch_info.path = path_to_free = resolve_refdup("HEAD", 0, &rev, &flag);
1031 if (old_branch_info.path)
21e1ee8f 1032 old_branch_info.commit = lookup_commit_reference_gently(the_repository, &rev, 1);
96ec7b1e 1033 if (!(flag & REF_ISSYMREF))
c8a3ea1f 1034 old_branch_info.path = NULL;
782c2d65 1035
c8a3ea1f
BW
1036 if (old_branch_info.path)
1037 skip_prefix(old_branch_info.path, "refs/heads/", &old_branch_info.name);
782c2d65 1038
1806c29f
NTND
1039 if (opts->new_orphan_branch && opts->orphan_from_empty_tree) {
1040 if (new_branch_info->name)
1041 BUG("'switch --orphan' should never accept a commit as starting point");
1042 new_branch_info->commit = NULL;
1043 new_branch_info->name = "(empty)";
1044 do_merge = 1;
1045 }
1046
c8a3ea1f
BW
1047 if (!new_branch_info->name) {
1048 new_branch_info->name = "HEAD";
1049 new_branch_info->commit = old_branch_info.commit;
1050 if (!new_branch_info->commit)
e8a8a4d7 1051 die(_("You are on a branch yet to be born"));
c8a3ea1f 1052 parse_commit_or_die(new_branch_info->commit);
65f099b3
NTND
1053
1054 if (opts->only_merge_on_switching_branches)
1055 do_merge = 0;
782c2d65
DB
1056 }
1057
65f099b3 1058 if (do_merge) {
fa655d84
BP
1059 ret = merge_working_tree(opts, &old_branch_info, new_branch_info, &writeout_error);
1060 if (ret) {
1061 free(path_to_free);
1062 return ret;
1063 }
96ec7b1e 1064 }
782c2d65 1065
c8a3ea1f
BW
1066 if (!opts->quiet && !old_branch_info.path && old_branch_info.commit && new_branch_info->commit != old_branch_info.commit)
1067 orphaned_commit_warning(old_branch_info.commit, new_branch_info->commit);
77ebd56d 1068
c8a3ea1f 1069 update_refs_for_switch(opts, &old_branch_info, new_branch_info);
782c2d65 1070
c8a3ea1f 1071 ret = post_checkout_hook(old_branch_info.commit, new_branch_info->commit, 1);
96ec7b1e 1072 free(path_to_free);
a2b4994c 1073 return ret || writeout_error;
782c2d65
DB
1074}
1075
0cf8581e
JH
1076static int git_checkout_config(const char *var, const char *value, void *cb)
1077{
175f6e59
JS
1078 if (!strcmp(var, "diff.ignoresubmodules")) {
1079 struct checkout_opts *opts = cb;
1080 handle_ignore_submodules_arg(&opts->diff_options, value);
1081 return 0;
1082 }
23b4c7bc 1083
59556548 1084 if (starts_with(var, "submodule."))
7463e2ec 1085 return git_default_submodule_config(var, value, NULL);
23b4c7bc 1086
175f6e59 1087 return git_xmerge_config(var, value, NULL);
0cf8581e
JH
1088}
1089
7ab4ad00
NTND
1090static void setup_new_branch_info_and_source_tree(
1091 struct branch_info *new_branch_info,
1092 struct checkout_opts *opts,
1093 struct object_id *rev,
1094 const char *arg)
1095{
1096 struct tree **source_tree = &opts->source_tree;
1097 struct object_id branch_rev;
1098
1099 new_branch_info->name = arg;
1100 setup_branch_path(new_branch_info);
1101
1102 if (!check_refname_format(new_branch_info->path, 0) &&
1103 !read_ref(new_branch_info->path, &branch_rev))
1104 oidcpy(rev, &branch_rev);
1105 else
1106 new_branch_info->path = NULL; /* not an existing branch */
1107
1108 new_branch_info->commit = lookup_commit_reference_gently(the_repository, rev, 1);
1109 if (!new_branch_info->commit) {
1110 /* not a commit */
1111 *source_tree = parse_tree_indirect(rev);
1112 } else {
1113 parse_commit_or_die(new_branch_info->commit);
1114 *source_tree = get_commit_tree(new_branch_info->commit);
1115 }
1116}
1117
09ebad6f
JN
1118static int parse_branchname_arg(int argc, const char **argv,
1119 int dwim_new_local_branch_ok,
c8a3ea1f 1120 struct branch_info *new_branch_info,
10f102be 1121 struct checkout_opts *opts,
3c87aa94
ÆAB
1122 struct object_id *rev,
1123 int *dwim_remotes_matched)
09ebad6f 1124{
10f102be 1125 const char **new_branch = &opts->new_branch;
09ebad6f 1126 int argcount = 0;
09ebad6f 1127 const char *arg;
bca39695
MM
1128 int dash_dash_pos;
1129 int has_dash_dash = 0;
1130 int i;
09ebad6f
JN
1131
1132 /*
1133 * case 1: git checkout <ref> -- [<paths>]
1134 *
1135 * <ref> must be a valid tree, everything after the '--' must be
1136 * a path.
1137 *
1138 * case 2: git checkout -- [<paths>]
1139 *
1140 * everything after the '--' must be paths.
1141 *
a047fafc 1142 * case 3: git checkout <something> [--]
09ebad6f 1143 *
a047fafc
MM
1144 * (a) If <something> is a commit, that is to
1145 * switch to the branch or detach HEAD at it. As a special case,
1146 * if <something> is A...B (missing A or B means HEAD but you can
1147 * omit at most one side), and if there is a unique merge base
1148 * between A and B, A...B names that merge base.
09ebad6f 1149 *
a047fafc 1150 * (b) If <something> is _not_ a commit, either "--" is present
01689909 1151 * or <something> is not a path, no -t or -b was given, and
a047fafc 1152 * and there is a tracking branch whose name is <something>
8d7b558b
ÆAB
1153 * in one and only one remote (or if the branch exists on the
1154 * remote named in checkout.defaultRemote), then this is a
1155 * short-hand to fork local <something> from that
1156 * remote-tracking branch.
09ebad6f 1157 *
a047fafc
MM
1158 * (c) Otherwise, if "--" is present, treat it like case (1).
1159 *
1160 * (d) Otherwise :
1161 * - if it's a reference, treat it like case (1)
1162 * - else if it's a path, treat it like case (2)
1163 * - else: fail.
1164 *
1165 * case 4: git checkout <something> <paths>
1166 *
1167 * The first argument must not be ambiguous.
09ebad6f
JN
1168 * - If it's *only* a reference, treat it like case (1).
1169 * - If it's only a path, treat it like case (2).
1170 * - else: fail.
1171 *
1172 */
1173 if (!argc)
1174 return 0;
1175
5c06e269
NTND
1176 if (!opts->accept_pathspec) {
1177 if (argc > 1)
1178 die(_("only one reference expected"));
1179 has_dash_dash = 1; /* helps disambiguate */
1180 }
1181
09ebad6f 1182 arg = argv[0];
bca39695
MM
1183 dash_dash_pos = -1;
1184 for (i = 0; i < argc; i++) {
5c06e269 1185 if (opts->accept_pathspec && !strcmp(argv[i], "--")) {
bca39695
MM
1186 dash_dash_pos = i;
1187 break;
1188 }
1189 }
1190 if (dash_dash_pos == 0)
1191 return 1; /* case (2) */
1192 else if (dash_dash_pos == 1)
1193 has_dash_dash = 1; /* case (3) or (1) */
1194 else if (dash_dash_pos >= 2)
1195 die(_("only one reference expected, %d given."), dash_dash_pos);
0f086e6d 1196 opts->count_checkout_paths = !opts->quiet && !has_dash_dash;
09ebad6f
JN
1197
1198 if (!strcmp(arg, "-"))
1199 arg = "@{-1}";
1200
151b2911 1201 if (get_oid_mb(arg, rev)) {
a047fafc
MM
1202 /*
1203 * Either case (3) or (4), with <something> not being
1204 * a commit, or an attempt to use case (1) with an
1205 * invalid ref.
1206 *
1207 * It's likely an error, but we need to find out if
1208 * we should auto-create the branch, case (3).(b).
1209 */
1210 int recover_with_dwim = dwim_new_local_branch_ok;
1211
be4908f1
NTND
1212 int could_be_checkout_paths = !has_dash_dash &&
1213 check_filename(opts->prefix, arg);
1214
1215 if (!has_dash_dash && !no_wildcard(arg))
a047fafc 1216 recover_with_dwim = 0;
be4908f1 1217
a047fafc 1218 /*
5c06e269
NTND
1219 * Accept "git checkout foo", "git checkout foo --"
1220 * and "git switch foo" as candidates for dwim.
a047fafc
MM
1221 */
1222 if (!(argc == 1 && !has_dash_dash) &&
5c06e269
NTND
1223 !(argc == 2 && has_dash_dash) &&
1224 opts->accept_pathspec)
a047fafc
MM
1225 recover_with_dwim = 0;
1226
1227 if (recover_with_dwim) {
3c87aa94
ÆAB
1228 const char *remote = unique_tracking_name(arg, rev,
1229 dwim_remotes_matched);
a047fafc 1230 if (remote) {
be4908f1
NTND
1231 if (could_be_checkout_paths)
1232 die(_("'%s' could be both a local file and a tracking branch.\n"
1233 "Please use -- (and optionally --no-guess) to disambiguate"),
1234 arg);
a047fafc
MM
1235 *new_branch = arg;
1236 arg = remote;
1237 /* DWIMmed to create local branch, case (3).(b) */
1238 } else {
1239 recover_with_dwim = 0;
1240 }
1241 }
1242
1243 if (!recover_with_dwim) {
1244 if (has_dash_dash)
1245 die(_("invalid reference: %s"), arg);
09ebad6f
JN
1246 return argcount;
1247 }
1248 }
1249
1250 /* we can't end up being in (2) anymore, eat the argument */
1251 argcount++;
1252 argv++;
1253 argc--;
1254
7ab4ad00 1255 setup_new_branch_info_and_source_tree(new_branch_info, opts, rev, arg);
09ebad6f 1256
7ab4ad00 1257 if (!opts->source_tree) /* case (1): want a tree */
6c80cd29 1258 die(_("reference is not a tree: %s"), arg);
7ab4ad00 1259
7f82b24e 1260 if (!has_dash_dash) { /* case (3).(d) -> (1) */
09ebad6f
JN
1261 /*
1262 * Do not complain the most common case
1263 * git checkout branch
1264 * even if there happen to be a file called 'branch';
1265 * it would be extremely annoying.
1266 */
1267 if (argc)
b829b943 1268 verify_non_filename(opts->prefix, arg);
5c06e269 1269 } else if (opts->accept_pathspec) {
09ebad6f
JN
1270 argcount++;
1271 argv++;
1272 argc--;
1273 }
1274
1275 return argcount;
1276}
1277
a2b4994c 1278static int switch_unborn_to_new_branch(const struct checkout_opts *opts)
abe19980
JH
1279{
1280 int status;
1281 struct strbuf branch_ref = STRBUF_INIT;
1282
e27dd8ae
JH
1283 trace2_cmd_mode("unborn");
1284
8ced1aa0
CW
1285 if (!opts->new_branch)
1286 die(_("You are on a branch yet to be born"));
abe19980
JH
1287 strbuf_addf(&branch_ref, "refs/heads/%s", opts->new_branch);
1288 status = create_symref("HEAD", branch_ref.buf, "checkout -b");
1289 strbuf_release(&branch_ref);
afa8c07a
JK
1290 if (!opts->quiet)
1291 fprintf(stderr, _("Switched to a new branch '%s'\n"),
1292 opts->new_branch);
abe19980
JH
1293 return status;
1294}
1295
7968bef0
NTND
1296static void die_expecting_a_branch(const struct branch_info *branch_info)
1297{
1298 struct object_id oid;
1299 char *to_free;
1300
1301 if (dwim_ref(branch_info->name, strlen(branch_info->name), &oid, &to_free) == 1) {
1302 const char *ref = to_free;
1303
1304 if (skip_prefix(ref, "refs/tags/", &ref))
1305 die(_("a branch is expected, got tag '%s'"), ref);
1306 if (skip_prefix(ref, "refs/remotes/", &ref))
1307 die(_("a branch is expected, got remote branch '%s'"), ref);
1308 die(_("a branch is expected, got '%s'"), ref);
1309 }
1310 if (branch_info->commit)
1311 die(_("a branch is expected, got commit '%s'"), branch_info->name);
1312 /*
1313 * This case should never happen because we already die() on
1314 * non-commit, but just in case.
1315 */
1316 die(_("a branch is expected, got '%s'"), branch_info->name);
1317}
1318
c45f0f52
NTND
1319static void die_if_some_operation_in_progress(void)
1320{
1321 struct wt_status_state state;
1322
1323 memset(&state, 0, sizeof(state));
1324 wt_status_get_state(the_repository, &state, 0);
1325
1326 if (state.merge_in_progress)
1327 die(_("cannot switch branch while merging\n"
1328 "Consider \"git merge --quit\" "
1329 "or \"git worktree add\"."));
1330 if (state.am_in_progress)
1331 die(_("cannot switch branch in the middle of an am session\n"
1332 "Consider \"git am --quit\" "
1333 "or \"git worktree add\"."));
1334 if (state.rebase_interactive_in_progress || state.rebase_in_progress)
1335 die(_("cannot switch branch while rebasing\n"
1336 "Consider \"git rebase --quit\" "
1337 "or \"git worktree add\"."));
1338 if (state.cherry_pick_in_progress)
1339 die(_("cannot switch branch while cherry-picking\n"
1340 "Consider \"git cherry-pick --quit\" "
1341 "or \"git worktree add\"."));
1342 if (state.revert_in_progress)
1343 die(_("cannot switch branch while reverting\n"
1344 "Consider \"git revert --quit\" "
1345 "or \"git worktree add\"."));
1346 if (state.bisect_in_progress)
d16dc428 1347 warning(_("you are switching branch while bisecting"));
c45f0f52
NTND
1348}
1349
b6312c27 1350static int checkout_branch(struct checkout_opts *opts,
c8a3ea1f 1351 struct branch_info *new_branch_info)
b6312c27 1352{
817b345a 1353 if (opts->pathspec.nr)
b6312c27
NTND
1354 die(_("paths cannot be used with switching branches"));
1355
1356 if (opts->patch_mode)
1357 die(_("'%s' cannot be used with switching branches"),
1358 "--patch");
1359
a6cfb9ba 1360 if (opts->overlay_mode != -1)
091e04bc 1361 die(_("'%s' cannot be used with switching branches"),
a6cfb9ba 1362 "--[no]-overlay");
091e04bc 1363
b6312c27
NTND
1364 if (opts->writeout_stage)
1365 die(_("'%s' cannot be used with switching branches"),
1366 "--ours/--theirs");
1367
1368 if (opts->force && opts->merge)
1369 die(_("'%s' cannot be used with '%s'"), "-f", "-m");
1370
3ec37ad1
NTND
1371 if (opts->discard_changes && opts->merge)
1372 die(_("'%s' cannot be used with '%s'"), "--discard-changes", "--merge");
1373
b6312c27
NTND
1374 if (opts->force_detach && opts->new_branch)
1375 die(_("'%s' cannot be used with '%s'"),
1376 "--detach", "-b/-B/--orphan");
1377
1378 if (opts->new_orphan_branch) {
1379 if (opts->track != BRANCH_TRACK_UNSPECIFIED)
1380 die(_("'%s' cannot be used with '%s'"), "--orphan", "-t");
1806c29f
NTND
1381 if (opts->orphan_from_empty_tree && new_branch_info->name)
1382 die(_("'%s' cannot take <start-point>"), "--orphan");
b6312c27
NTND
1383 } else if (opts->force_detach) {
1384 if (opts->track != BRANCH_TRACK_UNSPECIFIED)
1385 die(_("'%s' cannot be used with '%s'"), "--detach", "-t");
1386 } else if (opts->track == BRANCH_TRACK_UNSPECIFIED)
1387 opts->track = git_branch_track;
1388
c8a3ea1f 1389 if (new_branch_info->name && !new_branch_info->commit)
b6312c27 1390 die(_("Cannot switch branch to a non-commit '%s'"),
c8a3ea1f 1391 new_branch_info->name);
b6312c27 1392
e342c63a
NTND
1393 if (!opts->switch_branch_doing_nothing_is_ok &&
1394 !new_branch_info->name &&
1395 !opts->new_branch &&
1396 !opts->force_detach)
1397 die(_("missing branch or commit argument"));
1398
7968bef0
NTND
1399 if (!opts->implicit_detach &&
1400 !opts->force_detach &&
1401 !opts->new_branch &&
1402 !opts->new_branch_force &&
1403 new_branch_info->name &&
1404 !new_branch_info->path)
1405 die_expecting_a_branch(new_branch_info);
1406
c45f0f52
NTND
1407 if (!opts->can_switch_when_in_progress)
1408 die_if_some_operation_in_progress();
1409
c8a3ea1f 1410 if (new_branch_info->path && !opts->force_detach && !opts->new_branch &&
c265c533 1411 !opts->ignore_other_worktrees) {
e1c1ab9d 1412 int flag;
efbd4fdf 1413 char *head_ref = resolve_refdup("HEAD", 0, NULL, &flag);
e1c1ab9d 1414 if (head_ref &&
c8a3ea1f
BW
1415 (!(flag & REF_ISSYMREF) || strcmp(head_ref, new_branch_info->path)))
1416 die_if_checked_out(new_branch_info->path, 1);
e1c1ab9d
NTND
1417 free(head_ref);
1418 }
1419
c8a3ea1f 1420 if (!new_branch_info->commit && opts->new_branch) {
60af7691 1421 struct object_id rev;
b6312c27
NTND
1422 int flag;
1423
34c290a6 1424 if (!read_ref_full("HEAD", 0, &rev, &flag) &&
60af7691 1425 (flag & REF_ISSYMREF) && is_null_oid(&rev))
b6312c27
NTND
1426 return switch_unborn_to_new_branch(opts);
1427 }
c8a3ea1f 1428 return switch_branches(opts, new_branch_info);
b6312c27
NTND
1429}
1430
20871822
NTND
1431static struct option *add_common_options(struct checkout_opts *opts,
1432 struct option *prevopts)
782c2d65 1433{
782c2d65 1434 struct option options[] = {
b3edccb9 1435 OPT__QUIET(&opts->quiet, N_("suppress progress reporting")),
20871822
NTND
1436 { OPTION_CALLBACK, 0, "recurse-submodules", NULL,
1437 "checkout", "control recursive updating of submodules",
1438 PARSE_OPT_OPTARG, option_parse_recurse_submodules_worktree_updater },
1439 OPT_BOOL(0, "progress", &opts->show_progress, N_("force progress reporting")),
20871822
NTND
1440 OPT_BOOL('m', "merge", &opts->merge, N_("perform a 3-way merge with the new branch")),
1441 OPT_STRING(0, "conflict", &opts->conflict_style, N_("style"),
1442 N_("conflict style (merge or diff3)")),
1443 OPT_END()
1444 };
1445 struct option *newopts = parse_options_concat(prevopts, options);
1446 free(prevopts);
1447 return newopts;
1448}
1449
b7b5fce2
NTND
1450static struct option *add_common_switch_branch_options(
1451 struct checkout_opts *opts, struct option *prevopts)
20871822
NTND
1452{
1453 struct option options[] = {
163e3b29 1454 OPT_BOOL('d', "detach", &opts->force_detach, N_("detach HEAD at named commit")),
b3edccb9 1455 OPT_SET_INT('t', "track", &opts->track, N_("set upstream info for new branch"),
9ed36cfa 1456 BRANCH_TRACK_EXPLICIT),
a5e5f399
NTND
1457 OPT__FORCE(&opts->force, N_("force checkout (throw away local modifications)"),
1458 PARSE_OPT_NOCOMPLETE),
b3edccb9 1459 OPT_STRING(0, "orphan", &opts->new_orphan_branch, N_("new-branch"), N_("new unparented branch")),
20871822
NTND
1460 OPT_BOOL_F(0, "overwrite-ignore", &opts->overwrite_ignore,
1461 N_("update ignored files (default)"),
1462 PARSE_OPT_NOCOMPLETE),
20871822
NTND
1463 OPT_BOOL(0, "ignore-other-worktrees", &opts->ignore_other_worktrees,
1464 N_("do not check if another worktree is holding the given ref")),
1465 OPT_END()
1466 };
1467 struct option *newopts = parse_options_concat(prevopts, options);
1468 free(prevopts);
1469 return newopts;
1470}
1471
1472static struct option *add_checkout_path_options(struct checkout_opts *opts,
1473 struct option *prevopts)
1474{
1475 struct option options[] = {
b3edccb9 1476 OPT_SET_INT_F('2', "ours", &opts->writeout_stage,
3fe735e7
NTND
1477 N_("checkout our version for unmerged files"),
1478 2, PARSE_OPT_NONEG),
b3edccb9 1479 OPT_SET_INT_F('3', "theirs", &opts->writeout_stage,
3fe735e7
NTND
1480 N_("checkout their version for unmerged files"),
1481 3, PARSE_OPT_NONEG),
b3edccb9
NTND
1482 OPT_BOOL('p', "patch", &opts->patch_mode, N_("select hunks interactively")),
1483 OPT_BOOL(0, "ignore-skip-worktree-bits", &opts->ignore_skipworktree,
08d595dc 1484 N_("do not limit pathspecs to sparse entries only")),
a9aecc7a
AM
1485 OPT_PATHSPEC_FROM_FILE(&opts->pathspec_from_file),
1486 OPT_PATHSPEC_FILE_NUL(&opts->pathspec_file_nul),
20871822 1487 OPT_END()
782c2d65 1488 };
20871822
NTND
1489 struct option *newopts = parse_options_concat(prevopts, options);
1490 free(prevopts);
1491 return newopts;
1492}
1493
d787d311
NTND
1494static int checkout_main(int argc, const char **argv, const char *prefix,
1495 struct checkout_opts *opts, struct option *options,
1496 const char * const usagestr[])
20871822 1497{
20871822
NTND
1498 struct branch_info new_branch_info;
1499 int dwim_remotes_matched = 0;
c9c935f6 1500 int parseopt_flags = 0;
782c2d65 1501
c8a3ea1f 1502 memset(&new_branch_info, 0, sizeof(new_branch_info));
b3edccb9
NTND
1503 opts->overwrite_ignore = 1;
1504 opts->prefix = prefix;
1505 opts->show_progress = -1;
782c2d65 1506
b3edccb9 1507 git_config(git_checkout_config, opts);
782c2d65 1508
b3edccb9 1509 opts->track = BRANCH_TRACK_UNSPECIFIED;
782c2d65 1510
c9c935f6
NTND
1511 if (!opts->accept_pathspec && !opts->accept_ref)
1512 BUG("make up your mind, you need to take _something_");
1513 if (opts->accept_pathspec && opts->accept_ref)
1514 parseopt_flags = PARSE_OPT_KEEP_DASHDASH;
782c2d65 1515
c9c935f6
NTND
1516 argc = parse_options(argc, argv, prefix, options,
1517 usagestr, parseopt_flags);
859fdaba 1518
b3edccb9
NTND
1519 if (opts->show_progress < 0) {
1520 if (opts->quiet)
1521 opts->show_progress = 0;
870ebdb9 1522 else
b3edccb9 1523 opts->show_progress = isatty(2);
870ebdb9
ECA
1524 }
1525
55cf704a 1526 if (opts->conflict_style) {
b3edccb9 1527 opts->merge = 1; /* implied */
55cf704a 1528 git_xmerge_config("merge.conflictstyle", opts->conflict_style, NULL);
b6312c27 1529 }
a5e5f399 1530 if (opts->force) {
3ec37ad1 1531 opts->discard_changes = 1;
a5e5f399
NTND
1532 opts->ignore_unmerged_opt = "--force";
1533 opts->ignore_unmerged = 1;
b6312c27 1534 }
02ac9837 1535
b3edccb9 1536 if ((!!opts->new_branch + !!opts->new_branch_force + !!opts->new_orphan_branch) > 1)
b6312c27 1537 die(_("-b, -B and --orphan are mutually exclusive"));
02ac9837 1538
b3edccb9 1539 if (opts->overlay_mode == 1 && opts->patch_mode)
091e04bc
TG
1540 die(_("-p and --overlay are mutually exclusive"));
1541
183fb44f
NTND
1542 if (opts->checkout_index >= 0 || opts->checkout_worktree >= 0) {
1543 if (opts->checkout_index < 0)
1544 opts->checkout_index = 0;
1545 if (opts->checkout_worktree < 0)
1546 opts->checkout_worktree = 0;
1547 } else {
1548 if (opts->checkout_index < 0)
1549 opts->checkout_index = -opts->checkout_index - 1;
1550 if (opts->checkout_worktree < 0)
1551 opts->checkout_worktree = -opts->checkout_worktree - 1;
1552 }
1553 if (opts->checkout_index < 0 || opts->checkout_worktree < 0)
1554 BUG("these flags should be non-negative by now");
3a733ce5
NTND
1555 /*
1556 * convenient shortcut: "git restore --staged" equals
1557 * "git restore --staged --source HEAD"
1558 */
1559 if (!opts->from_treeish && opts->checkout_index && !opts->checkout_worktree)
1560 opts->from_treeish = "HEAD";
183fb44f 1561
b6312c27
NTND
1562 /*
1563 * From here on, new_branch will contain the branch to be checked out,
1564 * and new_branch_force and new_orphan_branch will tell us which one of
1565 * -b/-B/--orphan is being used.
1566 */
b3edccb9
NTND
1567 if (opts->new_branch_force)
1568 opts->new_branch = opts->new_branch_force;
02ac9837 1569
b3edccb9
NTND
1570 if (opts->new_orphan_branch)
1571 opts->new_branch = opts->new_orphan_branch;
32669671 1572
b6312c27 1573 /* --track without -b/-B/--orphan should DWIM */
b3edccb9 1574 if (opts->track != BRANCH_TRACK_UNSPECIFIED && !opts->new_branch) {
9188ed89
AR
1575 const char *argv0 = argv[0];
1576 if (!argc || !strcmp(argv0, "--"))
1a07e59c 1577 die(_("--track needs a branch name"));
e3f1da98
RS
1578 skip_prefix(argv0, "refs/", &argv0);
1579 skip_prefix(argv0, "remotes/", &argv0);
9188ed89
AR
1580 argv0 = strchr(argv0, '/');
1581 if (!argv0 || !argv0[1])
1a07e59c 1582 die(_("missing branch name; try -b"));
b3edccb9 1583 opts->new_branch = argv0 + 1;
bb0ceb62
JS
1584 }
1585
859fdaba 1586 /*
09ebad6f
JN
1587 * Extract branch name from command line arguments, so
1588 * all that is left is pathspecs.
859fdaba 1589 *
09ebad6f 1590 * Handle
70c9ac2f 1591 *
09ebad6f
JN
1592 * 1) git checkout <tree> -- [<paths>]
1593 * 2) git checkout -- [<paths>]
1594 * 3) git checkout <something> [<paths>]
859fdaba 1595 *
09ebad6f
JN
1596 * including "last branch" syntax and DWIM-ery for names of
1597 * remote branches, erroring out for invalid or ambiguous cases.
859fdaba 1598 */
c9c935f6 1599 if (argc && opts->accept_ref) {
60af7691 1600 struct object_id rev;
09ebad6f 1601 int dwim_ok =
b3edccb9 1602 !opts->patch_mode &&
ccb111b3 1603 opts->dwim_new_local_branch &&
b3edccb9
NTND
1604 opts->track == BRANCH_TRACK_UNSPECIFIED &&
1605 !opts->new_branch;
f8bd36a4 1606 int n = parse_branchname_arg(argc, argv, dwim_ok,
b3edccb9 1607 &new_branch_info, opts, &rev,
3c87aa94 1608 &dwim_remotes_matched);
09ebad6f
JN
1609 argv += n;
1610 argc -= n;
c9c935f6
NTND
1611 } else if (!opts->accept_ref && opts->from_treeish) {
1612 struct object_id rev;
1613
1614 if (get_oid_mb(opts->from_treeish, &rev))
1615 die(_("could not resolve %s"), opts->from_treeish);
1616
1617 setup_new_branch_info_and_source_tree(&new_branch_info,
1618 opts, &rev,
1619 opts->from_treeish);
1620
1621 if (!opts->source_tree)
1622 die(_("reference is not a tree: %s"), opts->from_treeish);
782c2d65
DB
1623 }
1624
782c2d65 1625 if (argc) {
b3edccb9
NTND
1626 parse_pathspec(&opts->pathspec, 0,
1627 opts->patch_mode ? PATHSPEC_PREFIX_ORIGIN : 0,
480ca644 1628 prefix, argv);
301e42ed 1629
b3edccb9 1630 if (!opts->pathspec.nr)
e8a8a4d7 1631 die(_("invalid path specification"));
301e42ed 1632
b6312c27
NTND
1633 /*
1634 * Try to give more helpful suggestion.
1635 * new_branch && argc > 1 will be caught later.
1636 */
b3edccb9 1637 if (opts->new_branch && argc == 1)
6c486862 1638 die(_("'%s' is not a commit and a branch '%s' cannot be created from it"),
b3edccb9 1639 argv[0], opts->new_branch);
782c2d65 1640
b3edccb9 1641 if (opts->force_detach)
b6312c27
NTND
1642 die(_("git checkout: --detach does not take a path argument '%s'"),
1643 argv[0]);
a9aecc7a
AM
1644 }
1645
1646 if (opts->pathspec_from_file) {
1647 if (opts->pathspec.nr)
1648 die(_("--pathspec-from-file is incompatible with pathspec arguments"));
1649
1650 if (opts->force_detach)
1651 die(_("--pathspec-from-file is incompatible with --detach"));
32669671 1652
a9aecc7a
AM
1653 if (opts->patch_mode)
1654 die(_("--pathspec-from-file is incompatible with --patch"));
1655
1656 parse_pathspec_file(&opts->pathspec, 0,
1657 0,
1658 prefix, opts->pathspec_from_file, opts->pathspec_file_nul);
1659 } else if (opts->pathspec_file_nul) {
1660 die(_("--pathspec-file-nul requires --pathspec-from-file"));
1661 }
1662
1663 if (opts->pathspec.nr) {
b3edccb9 1664 if (1 < !!opts->writeout_stage + !!opts->force + !!opts->merge)
b6312c27
NTND
1665 die(_("git checkout: --ours/--theirs, --force and --merge are incompatible when\n"
1666 "checking out of the index."));
a9aecc7a
AM
1667 } else {
1668 if (opts->accept_pathspec && !opts->empty_pathspec_ok &&
1669 !opts->patch_mode) /* patch mode is special */
1670 die(_("you must specify path(s) to restore"));
782c2d65
DB
1671 }
1672
b3edccb9 1673 if (opts->new_branch) {
f285a2d7 1674 struct strbuf buf = STRBUF_INIT;
55c4a673 1675
b3edccb9
NTND
1676 if (opts->new_branch_force)
1677 opts->branch_exists = validate_branchname(opts->new_branch, &buf);
bc1c9c0e 1678 else
b3edccb9
NTND
1679 opts->branch_exists =
1680 validate_new_branchname(opts->new_branch, &buf, 0);
352eadc4
DB
1681 strbuf_release(&buf);
1682 }
1683
886e1084 1684 UNLEAK(opts);
b3edccb9
NTND
1685 if (opts->patch_mode || opts->pathspec.nr) {
1686 int ret = checkout_paths(opts, new_branch_info.name);
ad8d5104
ÆAB
1687 if (ret && dwim_remotes_matched > 1 &&
1688 advice_checkout_ambiguous_remote_branch_name)
1689 advise(_("'%s' matched more than one remote tracking branch.\n"
1690 "We found %d remotes with a reference that matched. So we fell back\n"
1691 "on trying to resolve the argument as a path, but failed there too!\n"
1692 "\n"
1693 "If you meant to check out a remote tracking branch on, e.g. 'origin',\n"
1694 "you can do so by fully qualifying the name with the --track option:\n"
1695 "\n"
8d7b558b
ÆAB
1696 " git checkout --track origin/<name>\n"
1697 "\n"
1698 "If you'd like to always have checkouts of an ambiguous <name> prefer\n"
1699 "one remote, e.g. the 'origin' remote, consider setting\n"
1700 "checkout.defaultRemote=origin in your config."),
ad8d5104
ÆAB
1701 argv[0],
1702 dwim_remotes_matched);
1c550553
ÆAB
1703 return ret;
1704 } else {
b3edccb9 1705 return checkout_branch(opts, &new_branch_info);
1c550553 1706 }
782c2d65 1707}
d787d311
NTND
1708
1709int cmd_checkout(int argc, const char **argv, const char *prefix)
1710{
1711 struct checkout_opts opts;
b7b5fce2
NTND
1712 struct option *options;
1713 struct option checkout_options[] = {
1714 OPT_STRING('b', NULL, &opts.new_branch, N_("branch"),
1715 N_("create and checkout a new branch")),
1716 OPT_STRING('B', NULL, &opts.new_branch_force, N_("branch"),
1717 N_("create/reset and checkout a branch")),
492ededc 1718 OPT_BOOL('l', NULL, &opts.new_branch_log, N_("create reflog for new branch")),
ccb111b3
NTND
1719 OPT_BOOL(0, "guess", &opts.dwim_new_local_branch,
1720 N_("second guess 'git checkout <no-such-branch>' (default)")),
a6cfb9ba 1721 OPT_BOOL(0, "overlay", &opts.overlay_mode, N_("use overlay mode (default)")),
b7b5fce2
NTND
1722 OPT_END()
1723 };
d787d311
NTND
1724 int ret;
1725
1726 memset(&opts, 0, sizeof(opts));
ccb111b3 1727 opts.dwim_new_local_branch = 1;
e342c63a 1728 opts.switch_branch_doing_nothing_is_ok = 1;
65f099b3 1729 opts.only_merge_on_switching_branches = 0;
c9c935f6 1730 opts.accept_ref = 1;
5c06e269 1731 opts.accept_pathspec = 1;
7968bef0 1732 opts.implicit_detach = 1;
c45f0f52 1733 opts.can_switch_when_in_progress = 1;
1806c29f 1734 opts.orphan_from_empty_tree = 0;
be8ed502 1735 opts.empty_pathspec_ok = 1;
a6cfb9ba 1736 opts.overlay_mode = -1;
183fb44f
NTND
1737 opts.checkout_index = -2; /* default on */
1738 opts.checkout_worktree = -2; /* default on */
d787d311 1739
31367762
DS
1740 if (argc == 3 && !strcmp(argv[1], "-b")) {
1741 /*
1742 * User ran 'git checkout -b <branch>' and expects
1743 * the same behavior as 'git switch -c <branch>'.
1744 */
1745 opts.switch_branch_doing_nothing_is_ok = 0;
1746 opts.only_merge_on_switching_branches = 1;
1747 }
1748
b7b5fce2 1749 options = parse_options_dup(checkout_options);
d787d311 1750 options = add_common_options(&opts, options);
b7b5fce2 1751 options = add_common_switch_branch_options(&opts, options);
d787d311
NTND
1752 options = add_checkout_path_options(&opts, options);
1753
1754 ret = checkout_main(argc, argv, prefix, &opts,
1755 options, checkout_usage);
1756 FREE_AND_NULL(options);
1757 return ret;
1758}
1759
1760int cmd_switch(int argc, const char **argv, const char *prefix)
1761{
1762 struct checkout_opts opts;
1763 struct option *options = NULL;
b7b5fce2
NTND
1764 struct option switch_options[] = {
1765 OPT_STRING('c', "create", &opts.new_branch, N_("branch"),
1766 N_("create and switch to a new branch")),
1767 OPT_STRING('C', "force-create", &opts.new_branch_force, N_("branch"),
1768 N_("create/reset and switch to a branch")),
ccb111b3
NTND
1769 OPT_BOOL(0, "guess", &opts.dwim_new_local_branch,
1770 N_("second guess 'git switch <no-such-branch>'")),
3ec37ad1
NTND
1771 OPT_BOOL(0, "discard-changes", &opts.discard_changes,
1772 N_("throw away local modifications")),
b7b5fce2
NTND
1773 OPT_END()
1774 };
d787d311
NTND
1775 int ret;
1776
1777 memset(&opts, 0, sizeof(opts));
ccb111b3 1778 opts.dwim_new_local_branch = 1;
c9c935f6 1779 opts.accept_ref = 1;
5c06e269 1780 opts.accept_pathspec = 0;
e342c63a 1781 opts.switch_branch_doing_nothing_is_ok = 0;
65f099b3 1782 opts.only_merge_on_switching_branches = 1;
7968bef0 1783 opts.implicit_detach = 0;
c45f0f52 1784 opts.can_switch_when_in_progress = 0;
1806c29f 1785 opts.orphan_from_empty_tree = 1;
a6cfb9ba 1786 opts.overlay_mode = -1;
d787d311 1787
b7b5fce2 1788 options = parse_options_dup(switch_options);
d787d311 1789 options = add_common_options(&opts, options);
b7b5fce2 1790 options = add_common_switch_branch_options(&opts, options);
d787d311
NTND
1791
1792 ret = checkout_main(argc, argv, prefix, &opts,
1793 options, switch_branch_usage);
1794 FREE_AND_NULL(options);
1795 return ret;
1796}
46e91b66
NTND
1797
1798int cmd_restore(int argc, const char **argv, const char *prefix)
1799{
1800 struct checkout_opts opts;
c9c935f6
NTND
1801 struct option *options;
1802 struct option restore_options[] = {
1803 OPT_STRING('s', "source", &opts.from_treeish, "<tree-ish>",
182f59da 1804 N_("which tree-ish to checkout from")),
183fb44f
NTND
1805 OPT_BOOL('S', "staged", &opts.checkout_index,
1806 N_("restore the index")),
1807 OPT_BOOL('W', "worktree", &opts.checkout_worktree,
1808 N_("restore the working tree (default)")),
a5e5f399
NTND
1809 OPT_BOOL(0, "ignore-unmerged", &opts.ignore_unmerged,
1810 N_("ignore unmerged entries")),
a6cfb9ba 1811 OPT_BOOL(0, "overlay", &opts.overlay_mode, N_("use overlay mode")),
c9c935f6
NTND
1812 OPT_END()
1813 };
46e91b66
NTND
1814 int ret;
1815
1816 memset(&opts, 0, sizeof(opts));
c9c935f6 1817 opts.accept_ref = 0;
46e91b66 1818 opts.accept_pathspec = 1;
be8ed502 1819 opts.empty_pathspec_ok = 0;
a6cfb9ba 1820 opts.overlay_mode = 0;
183fb44f
NTND
1821 opts.checkout_index = -1; /* default off */
1822 opts.checkout_worktree = -2; /* default on */
a5e5f399 1823 opts.ignore_unmerged_opt = "--ignore-unmerged";
46e91b66 1824
c9c935f6 1825 options = parse_options_dup(restore_options);
46e91b66
NTND
1826 options = add_common_options(&opts, options);
1827 options = add_checkout_path_options(&opts, options);
1828
1829 ret = checkout_main(argc, argv, prefix, &opts,
1830 options, restore_usage);
1831 FREE_AND_NULL(options);
1832 return ret;
1833}