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