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