]> git.ipfire.org Git - thirdparty/git.git/blame - builtin/checkout.c
checkout: support checking out into a new working directory
[thirdparty/git.git] / builtin / checkout.c
CommitLineData
782c2d65 1#include "builtin.h"
697cc8ef 2#include "lockfile.h"
782c2d65
DB
3#include "parse-options.h"
4#include "refs.h"
5#include "commit.h"
6#include "tree.h"
7#include "tree-walk.h"
b9d37a54 8#include "cache-tree.h"
782c2d65
DB
9#include "unpack-trees.h"
10#include "dir.h"
11#include "run-command.h"
12#include "merge-recursive.h"
13#include "branch.h"
14#include "diff.h"
15#include "revision.h"
79a1e6b4 16#include "remote.h"
0cf8581e
JH
17#include "blob.h"
18#include "xdiff-interface.h"
19#include "ll-merge.h"
cfc5789a 20#include "resolve-undo.h"
175f6e59 21#include "submodule.h"
7bf0b017 22#include "argv-array.h"
782c2d65
DB
23
24static const char * const checkout_usage[] = {
e05a1093
NTND
25 N_("git checkout [options] <branch>"),
26 N_("git checkout [options] [<branch>] -- <file>..."),
782c2d65
DB
27 NULL,
28};
29
db941099 30struct checkout_opts {
e51e3057 31 int patch_mode;
db941099
JH
32 int quiet;
33 int merge;
34 int force;
32669671 35 int force_detach;
38901a48 36 int writeout_stage;
c1d7036b 37 int overwrite_ignore;
08d595dc 38 int ignore_skipworktree;
db941099
JH
39
40 const char *new_branch;
02ac9837 41 const char *new_branch_force;
9db5ebf4 42 const char *new_orphan_branch;
db941099
JH
43 int new_branch_log;
44 enum branch_track track;
175f6e59 45 struct diff_options diff_options;
e51e3057
NTND
46
47 int branch_exists;
48 const char *prefix;
817b345a 49 struct pathspec pathspec;
e51e3057 50 struct tree *source_tree;
529fef20
NTND
51
52 const char *new_worktree;
53 const char **saved_argv;
54 int new_worktree_mode;
db941099
JH
55};
56
782c2d65
DB
57static int post_checkout_hook(struct commit *old, struct commit *new,
58 int changed)
59{
15048f8a
BP
60 return run_hook_le(NULL, "post-checkout",
61 sha1_to_hex(old ? old->object.sha1 : null_sha1),
62 sha1_to_hex(new ? new->object.sha1 : null_sha1),
63 changed ? "1" : "0", NULL);
2292ce47
SB
64 /* "new" can be NULL when checking out from the index before
65 a commit exists. */
ae98a008 66
782c2d65
DB
67}
68
69static int update_some(const unsigned char *sha1, const char *base, int baselen,
671f0707 70 const char *pathname, unsigned mode, int stage, void *context)
782c2d65
DB
71{
72 int len;
73 struct cache_entry *ce;
74
782c2d65
DB
75 if (S_ISDIR(mode))
76 return READ_TREE_RECURSIVE;
77
78 len = baselen + strlen(pathname);
79 ce = xcalloc(1, cache_entry_size(len));
80 hashcpy(ce->sha1, sha1);
81 memcpy(ce->name, base, baselen);
82 memcpy(ce->name + baselen, pathname, len - baselen);
b60e188c
TG
83 ce->ce_flags = create_ce_flags(0) | CE_UPDATE;
84 ce->ce_namelen = len;
782c2d65
DB
85 ce->ce_mode = create_ce_mode(mode);
86 add_cache_entry(ce, ADD_CACHE_OK_TO_ADD | ADD_CACHE_OK_TO_REPLACE);
87 return 0;
88}
89
18e4f405 90static int read_tree_some(struct tree *tree, const struct pathspec *pathspec)
782c2d65 91{
18e4f405 92 read_tree_recursive(tree, "", 0, 0, pathspec, update_some, NULL);
782c2d65 93
782c2d65
DB
94 /* update the index with the given tree's info
95 * for all args, expanding wildcards, and exit
96 * with any non-zero return code.
97 */
98 return 0;
99}
100
9c5e6c80 101static int skip_same_name(const struct cache_entry *ce, int pos)
8fdcf312
JH
102{
103 while (++pos < active_nr &&
104 !strcmp(active_cache[pos]->name, ce->name))
105 ; /* skip */
106 return pos;
107}
108
9c5e6c80 109static int check_stage(int stage, const struct cache_entry *ce, int pos)
38901a48
JH
110{
111 while (pos < active_nr &&
112 !strcmp(active_cache[pos]->name, ce->name)) {
113 if (ce_stage(active_cache[pos]) == stage)
114 return 0;
115 pos++;
116 }
9f97ab08
ÆAB
117 if (stage == 2)
118 return error(_("path '%s' does not have our version"), ce->name);
119 else
120 return error(_("path '%s' does not have their version"), ce->name);
38901a48
JH
121}
122
9c5e6c80 123static int check_stages(unsigned stages, const struct cache_entry *ce, int pos)
0cf8581e 124{
fbbccd0a
JH
125 unsigned seen = 0;
126 const char *name = ce->name;
127
128 while (pos < active_nr) {
129 ce = active_cache[pos];
130 if (strcmp(name, ce->name))
131 break;
132 seen |= (1 << ce_stage(ce));
133 pos++;
134 }
135 if ((stages & seen) != stages)
136 return error(_("path '%s' does not have all necessary versions"),
137 name);
0cf8581e
JH
138 return 0;
139}
140
38901a48
JH
141static int checkout_stage(int stage, struct cache_entry *ce, int pos,
142 struct checkout *state)
143{
144 while (pos < active_nr &&
145 !strcmp(active_cache[pos]->name, ce->name)) {
146 if (ce_stage(active_cache[pos]) == stage)
147 return checkout_entry(active_cache[pos], state, NULL);
148 pos++;
149 }
9f97ab08
ÆAB
150 if (stage == 2)
151 return error(_("path '%s' does not have our version"), ce->name);
152 else
153 return error(_("path '%s' does not have their version"), ce->name);
38901a48 154}
8fdcf312 155
0cf8581e
JH
156static int checkout_merged(int pos, struct checkout *state)
157{
158 struct cache_entry *ce = active_cache[pos];
159 const char *path = ce->name;
160 mmfile_t ancestor, ours, theirs;
161 int status;
162 unsigned char sha1[20];
163 mmbuffer_t result_buf;
fbbccd0a 164 unsigned char threeway[3][20];
335c6e40 165 unsigned mode = 0;
0cf8581e 166
fbbccd0a
JH
167 memset(threeway, 0, sizeof(threeway));
168 while (pos < active_nr) {
169 int stage;
170 stage = ce_stage(ce);
171 if (!stage || strcmp(path, ce->name))
172 break;
173 hashcpy(threeway[stage - 1], ce->sha1);
174 if (stage == 2)
175 mode = create_ce_mode(ce->ce_mode);
176 pos++;
177 ce = active_cache[pos];
178 }
179 if (is_null_sha1(threeway[1]) || is_null_sha1(threeway[2]))
180 return error(_("path '%s' does not have necessary versions"), path);
0cf8581e 181
fbbccd0a
JH
182 read_mmblob(&ancestor, threeway[0]);
183 read_mmblob(&ours, threeway[1]);
184 read_mmblob(&theirs, threeway[2]);
0cf8581e 185
18b037a5
JN
186 /*
187 * NEEDSWORK: re-create conflicts from merges with
188 * merge.renormalize set, too
189 */
f0531a29 190 status = ll_merge(&result_buf, path, &ancestor, "base",
712516bc 191 &ours, "ours", &theirs, "theirs", NULL);
0cf8581e
JH
192 free(ancestor.ptr);
193 free(ours.ptr);
194 free(theirs.ptr);
195 if (status < 0 || !result_buf.ptr) {
196 free(result_buf.ptr);
e8a8a4d7 197 return error(_("path '%s': cannot merge"), path);
0cf8581e
JH
198 }
199
200 /*
201 * NEEDSWORK:
202 * There is absolutely no reason to write this as a blob object
3ea3c215 203 * and create a phony cache entry just to leak. This hack is
0cf8581e
JH
204 * primarily to get to the write_entry() machinery that massages
205 * the contents to work-tree format and writes out which only
206 * allows it for a cache entry. The code in write_entry() needs
207 * to be refactored to allow us to feed a <buffer, size, mode>
208 * instead of a cache entry. Such a refactoring would help
209 * merge_recursive as well (it also writes the merge result to the
210 * object database even when it may contain conflicts).
211 */
212 if (write_sha1_file(result_buf.ptr, result_buf.size,
213 blob_type, sha1))
e8a8a4d7 214 die(_("Unable to add merge result for '%s'"), path);
fbbccd0a 215 ce = make_cache_entry(mode, sha1, path, 2, 0);
048f2762 216 if (!ce)
e8a8a4d7 217 die(_("make_cache_entry failed for path '%s'"), path);
0cf8581e
JH
218 status = checkout_entry(ce, state, NULL);
219 return status;
220}
8fdcf312 221
b6312c27
NTND
222static int checkout_paths(const struct checkout_opts *opts,
223 const char *revision)
782c2d65
DB
224{
225 int pos;
226 struct checkout state;
227 static char *ps_matched;
228 unsigned char rev[20];
229 int flag;
230 struct commit *head;
d2b3691b 231 int errs = 0;
b6312c27
NTND
232 struct lock_file *lock_file;
233
234 if (opts->track != BRANCH_TRACK_UNSPECIFIED)
235 die(_("'%s' cannot be used with updating paths"), "--track");
236
237 if (opts->new_branch_log)
238 die(_("'%s' cannot be used with updating paths"), "-l");
239
240 if (opts->force && opts->patch_mode)
241 die(_("'%s' cannot be used with updating paths"), "-f");
242
243 if (opts->force_detach)
244 die(_("'%s' cannot be used with updating paths"), "--detach");
245
246 if (opts->merge && opts->patch_mode)
247 die(_("'%s' cannot be used with %s"), "--merge", "--patch");
248
249 if (opts->force && opts->merge)
250 die(_("'%s' cannot be used with %s"), "-f", "-m");
251
252 if (opts->new_branch)
253 die(_("Cannot update paths and switch to branch '%s' at the same time."),
254 opts->new_branch);
255
529fef20
NTND
256 if (opts->new_worktree)
257 die(_("'%s' cannot be used with updating paths"), "--to");
258
b6312c27
NTND
259 if (opts->patch_mode)
260 return run_add_interactive(revision, "--patch=checkout",
480ca644 261 &opts->pathspec);
b6312c27
NTND
262
263 lock_file = xcalloc(1, sizeof(struct lock_file));
75336878 264
03b86647 265 hold_locked_index(lock_file, 1);
5ab2a2da 266 if (read_cache_preload(&opts->pathspec) < 0)
e8a8a4d7 267 return error(_("corrupt index file"));
75336878 268
e51e3057 269 if (opts->source_tree)
18e4f405 270 read_tree_some(opts->source_tree, &opts->pathspec);
75336878 271
817b345a 272 ps_matched = xcalloc(1, opts->pathspec.nr);
782c2d65 273
e721c154
NTND
274 /*
275 * Make sure all pathspecs participated in locating the paths
276 * to be checked out.
277 */
782c2d65
DB
278 for (pos = 0; pos < active_nr; pos++) {
279 struct cache_entry *ce = active_cache[pos];
e721c154 280 ce->ce_flags &= ~CE_MATCHED;
08d595dc
NTND
281 if (!opts->ignore_skipworktree && ce_skip_worktree(ce))
282 continue;
e51e3057 283 if (opts->source_tree && !(ce->ce_flags & CE_UPDATE))
e721c154
NTND
284 /*
285 * "git checkout tree-ish -- path", but this entry
286 * is in the original index; it will not be checked
287 * out to the working tree and it does not matter
288 * if pathspec matched this entry. We will not do
289 * anything to this entry at all.
290 */
0a1283bc 291 continue;
e721c154
NTND
292 /*
293 * Either this entry came from the tree-ish we are
294 * checking the paths out of, or we are checking out
295 * of the index.
296 *
297 * If it comes from the tree-ish, we already know it
298 * matches the pathspec and could just stamp
299 * CE_MATCHED to it from update_some(). But we still
300 * need ps_matched and read_tree_recursive (and
301 * eventually tree_entry_interesting) cannot fill
302 * ps_matched yet. Once it can, we can avoid calling
303 * match_pathspec() for _all_ entries when
304 * opts->source_tree != NULL.
305 */
429bb40a 306 if (ce_path_match(ce, &opts->pathspec, ps_matched))
e721c154 307 ce->ce_flags |= CE_MATCHED;
782c2d65
DB
308 }
309
17ddc66e 310 if (report_path_error(ps_matched, &opts->pathspec, opts->prefix)) {
e721c154 311 free(ps_matched);
782c2d65 312 return 1;
e721c154
NTND
313 }
314 free(ps_matched);
782c2d65 315
4421a823
JH
316 /* "checkout -m path" to recreate conflicted state */
317 if (opts->merge)
e721c154 318 unmerge_marked_index(&the_index);
4421a823 319
8fdcf312
JH
320 /* Any unmerged paths? */
321 for (pos = 0; pos < active_nr; pos++) {
9c5e6c80 322 const struct cache_entry *ce = active_cache[pos];
e721c154 323 if (ce->ce_flags & CE_MATCHED) {
8fdcf312
JH
324 if (!ce_stage(ce))
325 continue;
db941099 326 if (opts->force) {
e8a8a4d7 327 warning(_("path '%s' is unmerged"), ce->name);
f9022075
SB
328 } else if (opts->writeout_stage) {
329 errs |= check_stage(opts->writeout_stage, ce, pos);
0cf8581e 330 } else if (opts->merge) {
fbbccd0a 331 errs |= check_stages((1<<2) | (1<<3), ce, pos);
db941099
JH
332 } else {
333 errs = 1;
e8a8a4d7 334 error(_("path '%s' is unmerged"), ce->name);
db941099 335 }
8fdcf312
JH
336 pos = skip_same_name(ce, pos) - 1;
337 }
338 }
339 if (errs)
340 return 1;
341
d2b3691b 342 /* Now we are committed to check them out */
782c2d65
DB
343 memset(&state, 0, sizeof(state));
344 state.force = 1;
345 state.refresh_cache = 1;
d4a2024a 346 state.istate = &the_index;
782c2d65
DB
347 for (pos = 0; pos < active_nr; pos++) {
348 struct cache_entry *ce = active_cache[pos];
e721c154 349 if (ce->ce_flags & CE_MATCHED) {
8fdcf312
JH
350 if (!ce_stage(ce)) {
351 errs |= checkout_entry(ce, &state, NULL);
352 continue;
353 }
f9022075
SB
354 if (opts->writeout_stage)
355 errs |= checkout_stage(opts->writeout_stage, ce, pos, &state);
356 else if (opts->merge)
0cf8581e 357 errs |= checkout_merged(pos, &state);
8fdcf312 358 pos = skip_same_name(ce, pos) - 1;
782c2d65
DB
359 }
360 }
361
03b86647 362 if (write_locked_index(&the_index, lock_file, COMMIT_LOCK))
e8a8a4d7 363 die(_("unable to write new index file"));
75336878 364
7695d118 365 read_ref_full("HEAD", 0, rev, &flag);
782c2d65
DB
366 head = lookup_commit_reference_gently(rev, 1);
367
d2b3691b
JH
368 errs |= post_checkout_hook(head, head, 0);
369 return errs;
782c2d65
DB
370}
371
a2b4994c
NTND
372static void show_local_changes(struct object *head,
373 const struct diff_options *opts)
782c2d65
DB
374{
375 struct rev_info rev;
376 /* I think we want full paths, even if we're in a subdirectory. */
377 init_revisions(&rev, NULL);
175f6e59 378 rev.diffopt.flags = opts->flags;
782c2d65 379 rev.diffopt.output_format |= DIFF_FORMAT_NAME_STATUS;
28452655 380 diff_setup_done(&rev.diffopt);
782c2d65
DB
381 add_pending_object(&rev, head, NULL);
382 run_diff_index(&rev, 0);
383}
384
b3c0494a 385static void describe_detached_head(const char *msg, struct commit *commit)
782c2d65 386{
f285a2d7 387 struct strbuf sb = STRBUF_INIT;
3c621839
JK
388 if (!parse_commit(commit))
389 pp_commit_easy(CMIT_FMT_ONELINE, commit, &sb);
782c2d65
DB
390 fprintf(stderr, "%s %s... %s\n", msg,
391 find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV), sb.buf);
392 strbuf_release(&sb);
393}
394
a2b4994c
NTND
395static int reset_tree(struct tree *tree, const struct checkout_opts *o,
396 int worktree, int *writeout_error)
782c2d65
DB
397{
398 struct unpack_trees_options opts;
399 struct tree_desc tree_desc;
bc052d7f 400
782c2d65
DB
401 memset(&opts, 0, sizeof(opts));
402 opts.head_idx = -1;
6286a08d
JH
403 opts.update = worktree;
404 opts.skip_unmerged = !worktree;
782c2d65
DB
405 opts.reset = 1;
406 opts.merge = 1;
407 opts.fn = oneway_merge;
e9fc64c6 408 opts.verbose_update = !o->quiet && isatty(2);
34110cd4
LT
409 opts.src_index = &the_index;
410 opts.dst_index = &the_index;
782c2d65
DB
411 parse_tree(tree);
412 init_tree_desc(&tree_desc, tree->buffer, tree->size);
291d823e
JH
413 switch (unpack_trees(1, &tree_desc, &opts)) {
414 case -2:
a2b4994c 415 *writeout_error = 1;
291d823e
JH
416 /*
417 * We return 0 nevertheless, as the index is all right
418 * and more importantly we have made best efforts to
419 * update paths in the work tree, and we cannot revert
420 * them.
421 */
422 case 0:
423 return 0;
424 default:
84a5750b 425 return 128;
291d823e 426 }
782c2d65
DB
427}
428
782c2d65
DB
429struct branch_info {
430 const char *name; /* The short name used */
431 const char *path; /* The full name of a real branch */
432 struct commit *commit; /* The named commit */
433};
434
435static void setup_branch_path(struct branch_info *branch)
436{
f285a2d7 437 struct strbuf buf = STRBUF_INIT;
ae5a6c36 438
a552de75
JH
439 strbuf_branchname(&buf, branch->name);
440 if (strcmp(buf.buf, branch->name))
ae5a6c36 441 branch->name = xstrdup(buf.buf);
a552de75 442 strbuf_splice(&buf, 0, 0, "refs/heads/", 11);
782c2d65
DB
443 branch->path = strbuf_detach(&buf, NULL);
444}
445
a2b4994c
NTND
446static int merge_working_tree(const struct checkout_opts *opts,
447 struct branch_info *old,
448 struct branch_info *new,
449 int *writeout_error)
782c2d65
DB
450{
451 int ret;
452 struct lock_file *lock_file = xcalloc(1, sizeof(struct lock_file));
b96524f8 453
03b86647 454 hold_locked_index(lock_file, 1);
53996fe5 455 if (read_cache_preload(NULL) < 0)
e8a8a4d7 456 return error(_("corrupt index file"));
782c2d65 457
cfc5789a 458 resolve_undo_clear();
782c2d65 459 if (opts->force) {
a2b4994c 460 ret = reset_tree(new->commit->tree, opts, 1, writeout_error);
782c2d65
DB
461 if (ret)
462 return ret;
463 } else {
464 struct tree_desc trees[2];
465 struct tree *tree;
466 struct unpack_trees_options topts;
bc052d7f 467
782c2d65
DB
468 memset(&topts, 0, sizeof(topts));
469 topts.head_idx = -1;
34110cd4
LT
470 topts.src_index = &the_index;
471 topts.dst_index = &the_index;
782c2d65 472
e294030f 473 setup_unpack_trees_porcelain(&topts, "checkout");
8ccba008 474
782c2d65
DB
475 refresh_cache(REFRESH_QUIET);
476
477 if (unmerged_cache()) {
e8a8a4d7 478 error(_("you need to resolve your current index first"));
04c9e11f 479 return 1;
782c2d65 480 }
04c9e11f
JH
481
482 /* 2-way merge to the new branch */
fa7b3c2f 483 topts.initial_checkout = is_cache_unborn();
04c9e11f
JH
484 topts.update = 1;
485 topts.merge = 1;
64da3ae5 486 topts.gently = opts->merge && old->commit;
e9fc64c6 487 topts.verbose_update = !opts->quiet && isatty(2);
04c9e11f 488 topts.fn = twoway_merge;
c1d7036b
NTND
489 if (opts->overwrite_ignore) {
490 topts.dir = xcalloc(1, sizeof(*topts.dir));
491 topts.dir->flags |= DIR_SHOW_IGNORED;
492 setup_standard_excludes(topts.dir);
493 }
529fef20 494 tree = parse_tree_indirect(old->commit && !opts->new_worktree_mode ?
cc580af8 495 old->commit->object.sha1 :
dab0d410 496 EMPTY_TREE_SHA1_BIN);
04c9e11f
JH
497 init_tree_desc(&trees[0], tree->buffer, tree->size);
498 tree = parse_tree_indirect(new->commit->object.sha1);
499 init_tree_desc(&trees[1], tree->buffer, tree->size);
500
291d823e 501 ret = unpack_trees(2, trees, &topts);
49d833dc 502 if (ret == -1) {
782c2d65
DB
503 /*
504 * Unpack couldn't do a trivial merge; either
505 * give up or do a real merge, depending on
506 * whether the merge flag was used.
507 */
508 struct tree *result;
509 struct tree *work;
8a2fce18 510 struct merge_options o;
782c2d65
DB
511 if (!opts->merge)
512 return 1;
64da3ae5
JH
513
514 /*
515 * Without old->commit, the below is the same as
516 * the two-tree unpack we already tried and failed.
517 */
518 if (!old->commit)
519 return 1;
782c2d65
DB
520
521 /* Do more real merge */
522
523 /*
524 * We update the index fully, then write the
525 * tree from the index, then merge the new
526 * branch with the current tree, with the old
527 * branch as the base. Then we reset the index
528 * (but not the working tree) to the new
529 * branch, leaving the working tree as the
530 * merged version, but skipping unmerged
531 * entries in the index.
532 */
533
7ae02a30 534 add_files_to_cache(NULL, NULL, 0);
7610fa57
JN
535 /*
536 * NEEDSWORK: carrying over local changes
537 * when branches have different end-of-line
538 * normalization (or clean+smudge rules) is
539 * a pain; plumb in an option to set
540 * o.renormalize?
541 */
8a2fce18
MV
542 init_merge_options(&o);
543 o.verbosity = 0;
544 work = write_tree_from_memory(&o);
782c2d65 545
a2b4994c
NTND
546 ret = reset_tree(new->commit->tree, opts, 1,
547 writeout_error);
782c2d65
DB
548 if (ret)
549 return ret;
c4151629 550 o.ancestor = old->name;
8a2fce18
MV
551 o.branch1 = new->name;
552 o.branch2 = "local";
553 merge_trees(&o, new->commit->tree, work,
554 old->commit->tree, &result);
a2b4994c
NTND
555 ret = reset_tree(new->commit->tree, opts, 0,
556 writeout_error);
84a5750b
JH
557 if (ret)
558 return ret;
782c2d65
DB
559 }
560 }
561
aecf567c
DT
562 if (!active_cache_tree)
563 active_cache_tree = cache_tree();
564
565 if (!cache_tree_fully_valid(active_cache_tree))
3fd13cbc 566 cache_tree_update(&the_index, WRITE_TREE_SILENT | WRITE_TREE_REPAIR);
aecf567c 567
03b86647 568 if (write_locked_index(&the_index, lock_file, COMMIT_LOCK))
e8a8a4d7 569 die(_("unable to write new index file"));
782c2d65 570
7fe4a728 571 if (!opts->force && !opts->quiet)
175f6e59 572 show_local_changes(&new->commit->object, &opts->diff_options);
782c2d65
DB
573
574 return 0;
575}
576
6d21bf96 577static void report_tracking(struct branch_info *new)
79a1e6b4 578{
6d21bf96 579 struct strbuf sb = STRBUF_INIT;
b56fca07 580 struct branch *branch = branch_get(new->name);
79a1e6b4 581
6d21bf96 582 if (!format_tracking_info(branch, &sb))
79a1e6b4 583 return;
6d21bf96
JH
584 fputs(sb.buf, stdout);
585 strbuf_release(&sb);
b0030db3 586}
79a1e6b4 587
a2b4994c 588static void update_refs_for_switch(const struct checkout_opts *opts,
782c2d65
DB
589 struct branch_info *old,
590 struct branch_info *new)
591{
f285a2d7 592 struct strbuf msg = STRBUF_INIT;
3bed291a 593 const char *old_desc, *reflog_msg;
782c2d65 594 if (opts->new_branch) {
3631bf77
EM
595 if (opts->new_orphan_branch) {
596 if (opts->new_branch_log && !log_all_ref_updates) {
597 int temp;
1a83c240
NTND
598 struct strbuf log_file = STRBUF_INIT;
599 int ret;
600 const char *ref_name;
3631bf77 601
1a83c240 602 ref_name = mkpath("refs/heads/%s", opts->new_orphan_branch);
3631bf77
EM
603 temp = log_all_ref_updates;
604 log_all_ref_updates = 1;
1a83c240
NTND
605 ret = log_ref_setup(ref_name, &log_file);
606 log_all_ref_updates = temp;
607 strbuf_release(&log_file);
608 if (ret) {
e8a8a4d7 609 fprintf(stderr, _("Can not do reflog for '%s'\n"),
3631bf77 610 opts->new_orphan_branch);
3631bf77
EM
611 return;
612 }
3631bf77
EM
613 }
614 }
615 else
02ac9837
TRC
616 create_branch(old->name, opts->new_branch, new->name,
617 opts->new_branch_force ? 1 : 0,
39bd6f72
JN
618 opts->new_branch_log,
619 opts->new_branch_force ? 1 : 0,
f9a482e6 620 opts->quiet,
39bd6f72 621 opts->track);
782c2d65
DB
622 new->name = opts->new_branch;
623 setup_branch_path(new);
624 }
625
782c2d65 626 old_desc = old->name;
323e00fd 627 if (!old_desc && old->commit)
782c2d65 628 old_desc = sha1_to_hex(old->commit->object.sha1);
3bed291a
RR
629
630 reflog_msg = getenv("GIT_REFLOG_ACTION");
631 if (!reflog_msg)
632 strbuf_addf(&msg, "checkout: moving from %s to %s",
633 old_desc ? old_desc : "(invalid)", new->name);
634 else
635 strbuf_insert(&msg, 0, reflog_msg, strlen(reflog_msg));
782c2d65 636
f8bd36a4
JN
637 if (!strcmp(new->name, "HEAD") && !new->path && !opts->force_detach) {
638 /* Nothing to do. */
639 } else if (opts->force_detach || !new->path) { /* No longer on any branch. */
640 update_ref(msg.buf, "HEAD", new->commit->object.sha1, NULL,
f4124112 641 REF_NODEREF, UPDATE_REFS_DIE_ON_ERR);
f8bd36a4
JN
642 if (!opts->quiet) {
643 if (old->path && advice_detached_head)
2857093b 644 detach_advice(new->name);
6c80cd29 645 describe_detached_head(_("HEAD is now at"), new->commit);
f8bd36a4
JN
646 }
647 } else if (new->path) { /* Switch branches. */
782c2d65
DB
648 create_symref("HEAD", new->path, msg.buf);
649 if (!opts->quiet) {
08eaa4be 650 if (old->path && !strcmp(new->path, old->path)) {
39bd6f72
JN
651 if (opts->new_branch_force)
652 fprintf(stderr, _("Reset branch '%s'\n"),
653 new->name);
654 else
655 fprintf(stderr, _("Already on '%s'\n"),
656 new->name);
08eaa4be
ÆAB
657 } else if (opts->new_branch) {
658 if (opts->branch_exists)
659 fprintf(stderr, _("Switched to and reset branch '%s'\n"), new->name);
660 else
661 fprintf(stderr, _("Switched to a new branch '%s'\n"), new->name);
662 } else {
e8a8a4d7 663 fprintf(stderr, _("Switched to branch '%s'\n"),
09a0ec58 664 new->name);
08eaa4be 665 }
782c2d65 666 }
3631bf77 667 if (old->path && old->name) {
482b8f32 668 if (!ref_exists(old->path) && reflog_exists(old->path))
4da58835 669 delete_reflog(old->path);
3631bf77 670 }
782c2d65
DB
671 }
672 remove_branch_state();
673 strbuf_release(&msg);
32669671
JH
674 if (!opts->quiet &&
675 (new->path || (!opts->force_detach && !strcmp(new->name, "HEAD"))))
6d21bf96 676 report_tracking(new);
782c2d65
DB
677}
678
468224e5
RS
679static int add_pending_uninteresting_ref(const char *refname,
680 const unsigned char *sha1,
681 int flags, void *cb_data)
8e2dc6ac 682{
add416a6 683 add_pending_sha1(cb_data, refname, sha1, UNINTERESTING);
5c08dc48
JK
684 return 0;
685}
8e2dc6ac
JH
686
687static void describe_one_orphan(struct strbuf *sb, struct commit *commit)
688{
0be240cc
JK
689 strbuf_addstr(sb, " ");
690 strbuf_addstr(sb,
691 find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV));
692 strbuf_addch(sb, ' ');
3c621839
JK
693 if (!parse_commit(commit))
694 pp_commit_easy(CMIT_FMT_ONELINE, commit, sb);
8e2dc6ac
JH
695 strbuf_addch(sb, '\n');
696}
697
698#define ORPHAN_CUTOFF 4
699static void suggest_reattach(struct commit *commit, struct rev_info *revs)
700{
701 struct commit *c, *last = NULL;
702 struct strbuf sb = STRBUF_INIT;
703 int lost = 0;
704 while ((c = get_revision(revs)) != NULL) {
705 if (lost < ORPHAN_CUTOFF)
706 describe_one_orphan(&sb, c);
707 last = c;
708 lost++;
709 }
710 if (ORPHAN_CUTOFF < lost) {
711 int more = lost - ORPHAN_CUTOFF;
712 if (more == 1)
713 describe_one_orphan(&sb, last);
714 else
f06f08b7 715 strbuf_addf(&sb, _(" ... and %d more.\n"), more);
8e2dc6ac
JH
716 }
717
718 fprintf(stderr,
f06f08b7
ÆAB
719 Q_(
720 /* The singular version */
721 "Warning: you are leaving %d commit behind, "
722 "not connected to\n"
723 "any of your branches:\n\n"
0faf2474 724 "%s\n",
f06f08b7
ÆAB
725 /* The plural version */
726 "Warning: you are leaving %d commits behind, "
8e2dc6ac
JH
727 "not connected to\n"
728 "any of your branches:\n\n"
f807b3dc 729 "%s\n",
f06f08b7
ÆAB
730 /* Give ngettext() the count */
731 lost),
732 lost,
f807b3dc 733 sb.buf);
8e2dc6ac 734 strbuf_release(&sb);
f807b3dc
JH
735
736 if (advice_detached_head)
737 fprintf(stderr,
0faf2474 738 _(
f807b3dc
JH
739 "If you want to keep them by creating a new branch, "
740 "this may be a good time\nto do so with:\n\n"
0faf2474 741 " git branch new_branch_name %s\n\n"),
d6e14660 742 find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV));
8e2dc6ac
JH
743}
744
745/*
746 * We are about to leave commit that was at the tip of a detached
747 * HEAD. If it is not reachable from any ref, this is the last chance
748 * for the user to do so without resorting to reflog.
749 */
5d886395 750static void orphaned_commit_warning(struct commit *old, struct commit *new)
8e2dc6ac 751{
8e2dc6ac 752 struct rev_info revs;
5d886395 753 struct object *object = &old->object;
10621419 754 struct object_array refs;
8e2dc6ac
JH
755
756 init_revisions(&revs, NULL);
468224e5
RS
757 setup_revisions(0, NULL, &revs, NULL);
758
759 object->flags &= ~UNINTERESTING;
760 add_pending_object(&revs, object, sha1_to_hex(object->sha1));
761
762 for_each_ref(add_pending_uninteresting_ref, &revs);
5d886395 763 add_pending_sha1(&revs, "HEAD", new->object.sha1, UNINTERESTING);
468224e5 764
10621419
RS
765 refs = revs.pending;
766 revs.leak_pending = 1;
767
8e2dc6ac 768 if (prepare_revision_walk(&revs))
6c80cd29 769 die(_("internal error in revision walk"));
5d886395
JS
770 if (!(old->object.flags & UNINTERESTING))
771 suggest_reattach(old, &revs);
8e2dc6ac 772 else
5d886395 773 describe_detached_head(_("Previous HEAD position was"), old);
5c08dc48 774
86a0a408 775 clear_commit_marks_for_object_array(&refs, ALL_REV_FLAGS);
10621419 776 free(refs.objects);
8e2dc6ac
JH
777}
778
e51e3057
NTND
779static int switch_branches(const struct checkout_opts *opts,
780 struct branch_info *new)
782c2d65
DB
781{
782 int ret = 0;
783 struct branch_info old;
96ec7b1e 784 void *path_to_free;
782c2d65 785 unsigned char rev[20];
a2b4994c 786 int flag, writeout_error = 0;
782c2d65 787 memset(&old, 0, sizeof(old));
7695d118 788 old.path = path_to_free = resolve_refdup("HEAD", 0, rev, &flag);
782c2d65 789 old.commit = lookup_commit_reference_gently(rev, 1);
96ec7b1e 790 if (!(flag & REF_ISSYMREF))
782c2d65
DB
791 old.path = NULL;
792
95b567c7
JK
793 if (old.path)
794 skip_prefix(old.path, "refs/heads/", &old.name);
782c2d65
DB
795
796 if (!new->name) {
797 new->name = "HEAD";
798 new->commit = old.commit;
799 if (!new->commit)
e8a8a4d7 800 die(_("You are on a branch yet to be born"));
683ff884 801 parse_commit_or_die(new->commit);
782c2d65
DB
802 }
803
a2b4994c 804 ret = merge_working_tree(opts, &old, new, &writeout_error);
96ec7b1e
NTND
805 if (ret) {
806 free(path_to_free);
782c2d65 807 return ret;
96ec7b1e 808 }
782c2d65 809
529fef20
NTND
810 if (!opts->quiet && !old.path && old.commit &&
811 new->commit != old.commit && !opts->new_worktree_mode)
5d886395 812 orphaned_commit_warning(old.commit, new->commit);
77ebd56d 813
782c2d65
DB
814 update_refs_for_switch(opts, &old, new);
815
291d823e 816 ret = post_checkout_hook(old.commit, new->commit, 1);
96ec7b1e 817 free(path_to_free);
a2b4994c 818 return ret || writeout_error;
782c2d65
DB
819}
820
529fef20
NTND
821static int prepare_linked_checkout(const struct checkout_opts *opts,
822 struct branch_info *new)
823{
824 struct strbuf sb_git = STRBUF_INIT, sb_repo = STRBUF_INIT;
825 struct strbuf sb = STRBUF_INIT;
826 const char *path = opts->new_worktree, *name;
827 struct stat st;
828 struct child_process cp;
829 int counter = 0, len;
830
831 if (!new->commit)
832 die(_("no branch specified"));
833 if (file_exists(path))
834 die(_("'%s' already exists"), path);
835
836 len = strlen(path);
837 while (len && is_dir_sep(path[len - 1]))
838 len--;
839
840 for (name = path + len - 1; name > path; name--)
841 if (is_dir_sep(*name)) {
842 name++;
843 break;
844 }
845 strbuf_addstr(&sb_repo,
846 git_path("worktrees/%.*s", (int)(path + len - name), name));
847 len = sb_repo.len;
848 if (safe_create_leading_directories_const(sb_repo.buf))
849 die_errno(_("could not create leading directories of '%s'"),
850 sb_repo.buf);
851 while (!stat(sb_repo.buf, &st)) {
852 counter++;
853 strbuf_setlen(&sb_repo, len);
854 strbuf_addf(&sb_repo, "%d", counter);
855 }
856 name = strrchr(sb_repo.buf, '/') + 1;
857 if (mkdir(sb_repo.buf, 0777))
858 die_errno(_("could not create directory of '%s'"), sb_repo.buf);
859
860 strbuf_addf(&sb_git, "%s/.git", path);
861 if (safe_create_leading_directories_const(sb_git.buf))
862 die_errno(_("could not create leading directories of '%s'"),
863 sb_git.buf);
864
865 write_file(sb_git.buf, 1, "gitdir: %s/worktrees/%s\n",
866 real_path(get_git_common_dir()), name);
867 /*
868 * This is to keep resolve_ref() happy. We need a valid HEAD
869 * or is_git_directory() will reject the directory. Any valid
870 * value would do because this value will be ignored and
871 * replaced at the next (real) checkout.
872 */
873 strbuf_addf(&sb, "%s/HEAD", sb_repo.buf);
874 write_file(sb.buf, 1, "%s\n", sha1_to_hex(new->commit->object.sha1));
875 strbuf_reset(&sb);
876 strbuf_addf(&sb, "%s/commondir", sb_repo.buf);
877 write_file(sb.buf, 1, "../..\n");
878
879 if (!opts->quiet)
880 fprintf_ln(stderr, _("Enter %s (identifier %s)"), path, name);
881
882 setenv("GIT_CHECKOUT_NEW_WORKTREE", "1", 1);
883 setenv(GIT_DIR_ENVIRONMENT, sb_git.buf, 1);
884 setenv(GIT_WORK_TREE_ENVIRONMENT, path, 1);
885 memset(&cp, 0, sizeof(cp));
886 cp.git_cmd = 1;
887 cp.argv = opts->saved_argv;
888 return run_command(&cp);
889}
890
0cf8581e
JH
891static int git_checkout_config(const char *var, const char *value, void *cb)
892{
175f6e59
JS
893 if (!strcmp(var, "diff.ignoresubmodules")) {
894 struct checkout_opts *opts = cb;
895 handle_ignore_submodules_arg(&opts->diff_options, value);
896 return 0;
897 }
23b4c7bc 898
59556548 899 if (starts_with(var, "submodule."))
23b4c7bc
JL
900 return parse_submodule_config_option(var, value);
901
175f6e59 902 return git_xmerge_config(var, value, NULL);
0cf8581e
JH
903}
904
70c9ac2f 905struct tracking_name_data {
fa83a33b
JH
906 /* const */ char *src_ref;
907 char *dst_ref;
908 unsigned char *dst_sha1;
70c9ac2f
JH
909 int unique;
910};
911
fa83a33b 912static int check_tracking_name(struct remote *remote, void *cb_data)
70c9ac2f
JH
913{
914 struct tracking_name_data *cb = cb_data;
fa83a33b
JH
915 struct refspec query;
916 memset(&query, 0, sizeof(struct refspec));
917 query.src = cb->src_ref;
918 if (remote_find_tracking(remote, &query) ||
2c484202
BC
919 get_sha1(query.dst, cb->dst_sha1)) {
920 free(query.dst);
70c9ac2f 921 return 0;
2c484202 922 }
fa83a33b 923 if (cb->dst_ref) {
2c484202 924 free(query.dst);
70c9ac2f
JH
925 cb->unique = 0;
926 return 0;
927 }
2c484202 928 cb->dst_ref = query.dst;
70c9ac2f
JH
929 return 0;
930}
931
fa83a33b 932static const char *unique_tracking_name(const char *name, unsigned char *sha1)
70c9ac2f 933{
fa83a33b
JH
934 struct tracking_name_data cb_data = { NULL, NULL, NULL, 1 };
935 char src_ref[PATH_MAX];
936 snprintf(src_ref, PATH_MAX, "refs/heads/%s", name);
937 cb_data.src_ref = src_ref;
938 cb_data.dst_sha1 = sha1;
939 for_each_remote(check_tracking_name, &cb_data);
70c9ac2f 940 if (cb_data.unique)
fa83a33b
JH
941 return cb_data.dst_ref;
942 free(cb_data.dst_ref);
70c9ac2f
JH
943 return NULL;
944}
4f353658 945
09ebad6f
JN
946static int parse_branchname_arg(int argc, const char **argv,
947 int dwim_new_local_branch_ok,
948 struct branch_info *new,
949 struct tree **source_tree,
950 unsigned char rev[20],
951 const char **new_branch)
952{
953 int argcount = 0;
954 unsigned char branch_rev[20];
955 const char *arg;
bca39695
MM
956 int dash_dash_pos;
957 int has_dash_dash = 0;
958 int i;
09ebad6f
JN
959
960 /*
961 * case 1: git checkout <ref> -- [<paths>]
962 *
963 * <ref> must be a valid tree, everything after the '--' must be
964 * a path.
965 *
966 * case 2: git checkout -- [<paths>]
967 *
968 * everything after the '--' must be paths.
969 *
a047fafc 970 * case 3: git checkout <something> [--]
09ebad6f 971 *
a047fafc
MM
972 * (a) If <something> is a commit, that is to
973 * switch to the branch or detach HEAD at it. As a special case,
974 * if <something> is A...B (missing A or B means HEAD but you can
975 * omit at most one side), and if there is a unique merge base
976 * between A and B, A...B names that merge base.
09ebad6f 977 *
a047fafc 978 * (b) If <something> is _not_ a commit, either "--" is present
01689909 979 * or <something> is not a path, no -t or -b was given, and
a047fafc
MM
980 * and there is a tracking branch whose name is <something>
981 * in one and only one remote, then this is a short-hand to
982 * fork local <something> from that remote-tracking branch.
09ebad6f 983 *
a047fafc
MM
984 * (c) Otherwise, if "--" is present, treat it like case (1).
985 *
986 * (d) Otherwise :
987 * - if it's a reference, treat it like case (1)
988 * - else if it's a path, treat it like case (2)
989 * - else: fail.
990 *
991 * case 4: git checkout <something> <paths>
992 *
993 * The first argument must not be ambiguous.
09ebad6f
JN
994 * - If it's *only* a reference, treat it like case (1).
995 * - If it's only a path, treat it like case (2).
996 * - else: fail.
997 *
998 */
999 if (!argc)
1000 return 0;
1001
09ebad6f 1002 arg = argv[0];
bca39695
MM
1003 dash_dash_pos = -1;
1004 for (i = 0; i < argc; i++) {
1005 if (!strcmp(argv[i], "--")) {
1006 dash_dash_pos = i;
1007 break;
1008 }
1009 }
1010 if (dash_dash_pos == 0)
1011 return 1; /* case (2) */
1012 else if (dash_dash_pos == 1)
1013 has_dash_dash = 1; /* case (3) or (1) */
1014 else if (dash_dash_pos >= 2)
1015 die(_("only one reference expected, %d given."), dash_dash_pos);
09ebad6f
JN
1016
1017 if (!strcmp(arg, "-"))
1018 arg = "@{-1}";
1019
1020 if (get_sha1_mb(arg, rev)) {
a047fafc
MM
1021 /*
1022 * Either case (3) or (4), with <something> not being
1023 * a commit, or an attempt to use case (1) with an
1024 * invalid ref.
1025 *
1026 * It's likely an error, but we need to find out if
1027 * we should auto-create the branch, case (3).(b).
1028 */
1029 int recover_with_dwim = dwim_new_local_branch_ok;
1030
1031 if (check_filename(NULL, arg) && !has_dash_dash)
1032 recover_with_dwim = 0;
1033 /*
1034 * Accept "git checkout foo" and "git checkout foo --"
1035 * as candidates for dwim.
1036 */
1037 if (!(argc == 1 && !has_dash_dash) &&
1038 !(argc == 2 && has_dash_dash))
1039 recover_with_dwim = 0;
1040
1041 if (recover_with_dwim) {
fa83a33b 1042 const char *remote = unique_tracking_name(arg, rev);
a047fafc
MM
1043 if (remote) {
1044 *new_branch = arg;
1045 arg = remote;
1046 /* DWIMmed to create local branch, case (3).(b) */
1047 } else {
1048 recover_with_dwim = 0;
1049 }
1050 }
1051
1052 if (!recover_with_dwim) {
1053 if (has_dash_dash)
1054 die(_("invalid reference: %s"), arg);
09ebad6f
JN
1055 return argcount;
1056 }
1057 }
1058
1059 /* we can't end up being in (2) anymore, eat the argument */
1060 argcount++;
1061 argv++;
1062 argc--;
1063
1064 new->name = arg;
1065 setup_branch_path(new);
1066
8d9c5010 1067 if (!check_refname_format(new->path, 0) &&
c6893323 1068 !read_ref(new->path, branch_rev))
09ebad6f
JN
1069 hashcpy(rev, branch_rev);
1070 else
1071 new->path = NULL; /* not an existing branch */
1072
1073 new->commit = lookup_commit_reference_gently(rev, 1);
1074 if (!new->commit) {
1075 /* not a commit */
1076 *source_tree = parse_tree_indirect(rev);
1077 } else {
683ff884 1078 parse_commit_or_die(new->commit);
09ebad6f
JN
1079 *source_tree = new->commit->tree;
1080 }
1081
1082 if (!*source_tree) /* case (1): want a tree */
6c80cd29 1083 die(_("reference is not a tree: %s"), arg);
a047fafc 1084 if (!has_dash_dash) {/* case (3).(d) -> (1) */
09ebad6f
JN
1085 /*
1086 * Do not complain the most common case
1087 * git checkout branch
1088 * even if there happen to be a file called 'branch';
1089 * it would be extremely annoying.
1090 */
1091 if (argc)
1092 verify_non_filename(NULL, arg);
1093 } else {
1094 argcount++;
1095 argv++;
1096 argc--;
1097 }
1098
1099 return argcount;
1100}
1101
a2b4994c 1102static int switch_unborn_to_new_branch(const struct checkout_opts *opts)
abe19980
JH
1103{
1104 int status;
1105 struct strbuf branch_ref = STRBUF_INIT;
1106
8ced1aa0
CW
1107 if (!opts->new_branch)
1108 die(_("You are on a branch yet to be born"));
abe19980
JH
1109 strbuf_addf(&branch_ref, "refs/heads/%s", opts->new_branch);
1110 status = create_symref("HEAD", branch_ref.buf, "checkout -b");
1111 strbuf_release(&branch_ref);
afa8c07a
JK
1112 if (!opts->quiet)
1113 fprintf(stderr, _("Switched to a new branch '%s'\n"),
1114 opts->new_branch);
abe19980
JH
1115 return status;
1116}
1117
b6312c27
NTND
1118static int checkout_branch(struct checkout_opts *opts,
1119 struct branch_info *new)
1120{
817b345a 1121 if (opts->pathspec.nr)
b6312c27
NTND
1122 die(_("paths cannot be used with switching branches"));
1123
1124 if (opts->patch_mode)
1125 die(_("'%s' cannot be used with switching branches"),
1126 "--patch");
1127
1128 if (opts->writeout_stage)
1129 die(_("'%s' cannot be used with switching branches"),
1130 "--ours/--theirs");
1131
1132 if (opts->force && opts->merge)
1133 die(_("'%s' cannot be used with '%s'"), "-f", "-m");
1134
1135 if (opts->force_detach && opts->new_branch)
1136 die(_("'%s' cannot be used with '%s'"),
1137 "--detach", "-b/-B/--orphan");
1138
1139 if (opts->new_orphan_branch) {
1140 if (opts->track != BRANCH_TRACK_UNSPECIFIED)
1141 die(_("'%s' cannot be used with '%s'"), "--orphan", "-t");
1142 } else if (opts->force_detach) {
1143 if (opts->track != BRANCH_TRACK_UNSPECIFIED)
1144 die(_("'%s' cannot be used with '%s'"), "--detach", "-t");
1145 } else if (opts->track == BRANCH_TRACK_UNSPECIFIED)
1146 opts->track = git_branch_track;
1147
1148 if (new->name && !new->commit)
1149 die(_("Cannot switch branch to a non-commit '%s'"),
1150 new->name);
1151
529fef20
NTND
1152 if (opts->new_worktree)
1153 return prepare_linked_checkout(opts, new);
1154
b6312c27
NTND
1155 if (!new->commit && opts->new_branch) {
1156 unsigned char rev[20];
1157 int flag;
1158
7695d118 1159 if (!read_ref_full("HEAD", 0, rev, &flag) &&
b6312c27
NTND
1160 (flag & REF_ISSYMREF) && is_null_sha1(rev))
1161 return switch_unborn_to_new_branch(opts);
1162 }
1163 return switch_branches(opts, new);
1164}
1165
782c2d65
DB
1166int cmd_checkout(int argc, const char **argv, const char *prefix)
1167{
1168 struct checkout_opts opts;
782c2d65 1169 struct branch_info new;
eac5a401 1170 char *conflict_style = NULL;
46148dd7 1171 int dwim_new_local_branch = 1;
782c2d65 1172 struct option options[] = {
e05a1093
NTND
1173 OPT__QUIET(&opts.quiet, N_("suppress progress reporting")),
1174 OPT_STRING('b', NULL, &opts.new_branch, N_("branch"),
1175 N_("create and checkout a new branch")),
1176 OPT_STRING('B', NULL, &opts.new_branch_force, N_("branch"),
1177 N_("create/reset and checkout a branch")),
d5d09d47
SB
1178 OPT_BOOL('l', NULL, &opts.new_branch_log, N_("create reflog for new branch")),
1179 OPT_BOOL(0, "detach", &opts.force_detach, N_("detach the HEAD at named commit")),
e05a1093 1180 OPT_SET_INT('t', "track", &opts.track, N_("set upstream info for new branch"),
9ed36cfa 1181 BRANCH_TRACK_EXPLICIT),
e703d711 1182 OPT_STRING(0, "orphan", &opts.new_orphan_branch, N_("new-branch"), N_("new unparented branch")),
e05a1093 1183 OPT_SET_INT('2', "ours", &opts.writeout_stage, N_("checkout our version for unmerged files"),
38901a48 1184 2),
e05a1093 1185 OPT_SET_INT('3', "theirs", &opts.writeout_stage, N_("checkout their version for unmerged files"),
38901a48 1186 3),
e05a1093 1187 OPT__FORCE(&opts.force, N_("force checkout (throw away local modifications)")),
d5d09d47
SB
1188 OPT_BOOL('m', "merge", &opts.merge, N_("perform a 3-way merge with the new branch")),
1189 OPT_BOOL(0, "overwrite-ignore", &opts.overwrite_ignore, N_("update ignored files (default)")),
e05a1093
NTND
1190 OPT_STRING(0, "conflict", &conflict_style, N_("style"),
1191 N_("conflict style (merge or diff3)")),
d5d09d47 1192 OPT_BOOL('p', "patch", &opts.patch_mode, N_("select hunks interactively")),
08d595dc
NTND
1193 OPT_BOOL(0, "ignore-skip-worktree-bits", &opts.ignore_skipworktree,
1194 N_("do not limit pathspecs to sparse entries only")),
4741edd5
SB
1195 OPT_HIDDEN_BOOL(0, "guess", &dwim_new_local_branch,
1196 N_("second guess 'git checkout no-such-branch'")),
529fef20
NTND
1197 OPT_FILENAME(0, "to", &opts.new_worktree,
1198 N_("check a branch out in a separate working directory")),
b249b552 1199 OPT_END(),
782c2d65
DB
1200 };
1201
1202 memset(&opts, 0, sizeof(opts));
1203 memset(&new, 0, sizeof(new));
c1d7036b 1204 opts.overwrite_ignore = 1;
e51e3057 1205 opts.prefix = prefix;
782c2d65 1206
529fef20
NTND
1207 opts.saved_argv = xmalloc(sizeof(const char *) * (argc + 2));
1208 memcpy(opts.saved_argv, argv, sizeof(const char *) * (argc + 1));
1209
23b4c7bc 1210 gitmodules_config();
175f6e59 1211 git_config(git_checkout_config, &opts);
782c2d65 1212
9188ed89 1213 opts.track = BRANCH_TRACK_UNSPECIFIED;
782c2d65 1214
37782920 1215 argc = parse_options(argc, argv, prefix, options, checkout_usage,
f5242ebf 1216 PARSE_OPT_KEEP_DASHDASH);
859fdaba 1217
529fef20
NTND
1218 /* recursive execution from checkout_new_worktree() */
1219 opts.new_worktree_mode = getenv("GIT_CHECKOUT_NEW_WORKTREE") != NULL;
1220 if (opts.new_worktree_mode)
1221 opts.new_worktree = NULL;
1222
b6312c27
NTND
1223 if (conflict_style) {
1224 opts.merge = 1; /* implied */
1225 git_xmerge_config("merge.conflictstyle", conflict_style, NULL);
1226 }
02ac9837 1227
b6312c27
NTND
1228 if ((!!opts.new_branch + !!opts.new_branch_force + !!opts.new_orphan_branch) > 1)
1229 die(_("-b, -B and --orphan are mutually exclusive"));
02ac9837 1230
b6312c27
NTND
1231 /*
1232 * From here on, new_branch will contain the branch to be checked out,
1233 * and new_branch_force and new_orphan_branch will tell us which one of
1234 * -b/-B/--orphan is being used.
1235 */
02ac9837
TRC
1236 if (opts.new_branch_force)
1237 opts.new_branch = opts.new_branch_force;
1238
b6312c27
NTND
1239 if (opts.new_orphan_branch)
1240 opts.new_branch = opts.new_orphan_branch;
32669671 1241
b6312c27
NTND
1242 /* --track without -b/-B/--orphan should DWIM */
1243 if (opts.track != BRANCH_TRACK_UNSPECIFIED && !opts.new_branch) {
9188ed89
AR
1244 const char *argv0 = argv[0];
1245 if (!argc || !strcmp(argv0, "--"))
e8a8a4d7 1246 die (_("--track needs a branch name"));
e3f1da98
RS
1247 skip_prefix(argv0, "refs/", &argv0);
1248 skip_prefix(argv0, "remotes/", &argv0);
9188ed89
AR
1249 argv0 = strchr(argv0, '/');
1250 if (!argv0 || !argv0[1])
e8a8a4d7 1251 die (_("Missing branch name; try -b"));
9188ed89 1252 opts.new_branch = argv0 + 1;
bb0ceb62
JS
1253 }
1254
859fdaba 1255 /*
09ebad6f
JN
1256 * Extract branch name from command line arguments, so
1257 * all that is left is pathspecs.
859fdaba 1258 *
09ebad6f 1259 * Handle
70c9ac2f 1260 *
09ebad6f
JN
1261 * 1) git checkout <tree> -- [<paths>]
1262 * 2) git checkout -- [<paths>]
1263 * 3) git checkout <something> [<paths>]
859fdaba 1264 *
09ebad6f
JN
1265 * including "last branch" syntax and DWIM-ery for names of
1266 * remote branches, erroring out for invalid or ambiguous cases.
859fdaba 1267 */
782c2d65 1268 if (argc) {
e51e3057 1269 unsigned char rev[20];
09ebad6f 1270 int dwim_ok =
e51e3057 1271 !opts.patch_mode &&
09ebad6f
JN
1272 dwim_new_local_branch &&
1273 opts.track == BRANCH_TRACK_UNSPECIFIED &&
1274 !opts.new_branch;
f8bd36a4 1275 int n = parse_branchname_arg(argc, argv, dwim_ok,
e51e3057
NTND
1276 &new, &opts.source_tree,
1277 rev, &opts.new_branch);
09ebad6f
JN
1278 argv += n;
1279 argc -= n;
782c2d65
DB
1280 }
1281
782c2d65 1282 if (argc) {
480ca644
NTND
1283 parse_pathspec(&opts.pathspec, 0,
1284 opts.patch_mode ? PATHSPEC_PREFIX_ORIGIN : 0,
1285 prefix, argv);
301e42ed 1286
817b345a 1287 if (!opts.pathspec.nr)
e8a8a4d7 1288 die(_("invalid path specification"));
301e42ed 1289
b6312c27
NTND
1290 /*
1291 * Try to give more helpful suggestion.
1292 * new_branch && argc > 1 will be caught later.
1293 */
1294 if (opts.new_branch && argc == 1)
1295 die(_("Cannot update paths and switch to branch '%s' at the same time.\n"
1296 "Did you intend to checkout '%s' which can not be resolved as commit?"),
1297 opts.new_branch, argv[0]);
782c2d65 1298
32669671 1299 if (opts.force_detach)
b6312c27
NTND
1300 die(_("git checkout: --detach does not take a path argument '%s'"),
1301 argv[0]);
32669671 1302
0cf8581e 1303 if (1 < !!opts.writeout_stage + !!opts.force + !!opts.merge)
b6312c27
NTND
1304 die(_("git checkout: --ours/--theirs, --force and --merge are incompatible when\n"
1305 "checking out of the index."));
782c2d65
DB
1306 }
1307
352eadc4 1308 if (opts.new_branch) {
f285a2d7 1309 struct strbuf buf = STRBUF_INIT;
55c4a673 1310
b6312c27
NTND
1311 opts.branch_exists =
1312 validate_new_branchname(opts.new_branch, &buf,
1313 !!opts.new_branch_force,
1314 !!opts.new_branch_force);
55c4a673 1315
352eadc4
DB
1316 strbuf_release(&buf);
1317 }
1318
817b345a 1319 if (opts.patch_mode || opts.pathspec.nr)
b6312c27
NTND
1320 return checkout_paths(&opts, new.name);
1321 else
1322 return checkout_branch(&opts, &new);
782c2d65 1323}