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