checkout.c 36.5 KB
Newer Older
D
Daniel Barkalow 已提交
1
#include "builtin.h"
2
#include "config.h"
3
#include "checkout.h"
4
#include "lockfile.h"
D
Daniel Barkalow 已提交
5 6 7 8 9
#include "parse-options.h"
#include "refs.h"
#include "commit.h"
#include "tree.h"
#include "tree-walk.h"
10
#include "cache-tree.h"
D
Daniel Barkalow 已提交
11 12 13 14 15 16 17
#include "unpack-trees.h"
#include "dir.h"
#include "run-command.h"
#include "merge-recursive.h"
#include "branch.h"
#include "diff.h"
#include "revision.h"
18
#include "remote.h"
19 20 21
#include "blob.h"
#include "xdiff-interface.h"
#include "ll-merge.h"
22
#include "resolve-undo.h"
23
#include "submodule-config.h"
24
#include "submodule.h"
D
Daniel Barkalow 已提交
25 26

static const char * const checkout_usage[] = {
27 28
	N_("git checkout [<options>] <branch>"),
	N_("git checkout [<options>] [<branch>] -- <file>..."),
D
Daniel Barkalow 已提交
29 30 31
	NULL,
};

32
struct checkout_opts {
33
	int patch_mode;
34 35 36
	int quiet;
	int merge;
	int force;
37
	int force_detach;
38
	int writeout_stage;
39
	int overwrite_ignore;
40
	int ignore_skipworktree;
41
	int ignore_other_worktrees;
42
	int show_progress;
43 44

	const char *new_branch;
T
Tay Ray Chuan 已提交
45
	const char *new_branch_force;
46
	const char *new_orphan_branch;
47 48
	int new_branch_log;
	enum branch_track track;
49
	struct diff_options diff_options;
50 51 52

	int branch_exists;
	const char *prefix;
53
	struct pathspec pathspec;
54
	struct tree *source_tree;
55 56
};

57
static int post_checkout_hook(struct commit *old_commit, struct commit *new_commit,
D
Daniel Barkalow 已提交
58 59
			      int changed)
{
60
	return run_hook_le(NULL, "post-checkout",
61 62
			   oid_to_hex(old_commit ? &old_commit->object.oid : &null_oid),
			   oid_to_hex(new_commit ? &new_commit->object.oid : &null_oid),
63
			   changed ? "1" : "0", NULL);
64
	/* "new_commit" can be NULL when checking out from the index before
65
	   a commit exists. */
66

D
Daniel Barkalow 已提交
67 68
}

69
static int update_some(const unsigned char *sha1, struct strbuf *base,
70
		const char *pathname, unsigned mode, int stage, void *context)
D
Daniel Barkalow 已提交
71 72 73
{
	int len;
	struct cache_entry *ce;
74
	int pos;
D
Daniel Barkalow 已提交
75 76 77 78

	if (S_ISDIR(mode))
		return READ_TREE_RECURSIVE;

79
	len = base->len + strlen(pathname);
D
Daniel Barkalow 已提交
80
	ce = xcalloc(1, cache_entry_size(len));
81
	hashcpy(ce->oid.hash, sha1);
82 83
	memcpy(ce->name, base->buf, base->len);
	memcpy(ce->name + base->len, pathname, len - base->len);
84 85
	ce->ce_flags = create_ce_flags(0) | CE_UPDATE;
	ce->ce_namelen = len;
D
Daniel Barkalow 已提交
86
	ce->ce_mode = create_ce_mode(mode);
87 88 89 90 91 92 93 94 95 96

	/*
	 * If the entry is the same as the current index, we can leave the old
	 * entry in place. Whether it is UPTODATE or not, checkout_entry will
	 * do the right thing.
	 */
	pos = cache_name_pos(ce->name, ce->ce_namelen);
	if (pos >= 0) {
		struct cache_entry *old = active_cache[pos];
		if (ce->ce_mode == old->ce_mode &&
97
		    !oidcmp(&ce->oid, &old->oid)) {
98 99 100 101 102 103
			old->ce_flags |= CE_UPDATE;
			free(ce);
			return 0;
		}
	}

D
Daniel Barkalow 已提交
104 105 106 107
	add_cache_entry(ce, ADD_CACHE_OK_TO_ADD | ADD_CACHE_OK_TO_REPLACE);
	return 0;
}

108
static int read_tree_some(struct tree *tree, const struct pathspec *pathspec)
D
Daniel Barkalow 已提交
109
{
110
	read_tree_recursive(tree, "", 0, 0, pathspec, update_some, NULL);
D
Daniel Barkalow 已提交
111 112 113 114 115 116 117 118

	/* update the index with the given tree's info
	 * for all args, expanding wildcards, and exit
	 * with any non-zero return code.
	 */
	return 0;
}

119
static int skip_same_name(const struct cache_entry *ce, int pos)
120 121 122 123 124 125 126
{
	while (++pos < active_nr &&
	       !strcmp(active_cache[pos]->name, ce->name))
		; /* skip */
	return pos;
}

127
static int check_stage(int stage, const struct cache_entry *ce, int pos)
128 129 130 131 132 133 134
{
	while (pos < active_nr &&
	       !strcmp(active_cache[pos]->name, ce->name)) {
		if (ce_stage(active_cache[pos]) == stage)
			return 0;
		pos++;
	}
135 136 137 138
	if (stage == 2)
		return error(_("path '%s' does not have our version"), ce->name);
	else
		return error(_("path '%s' does not have their version"), ce->name);
139 140
}

141
static int check_stages(unsigned stages, const struct cache_entry *ce, int pos)
142
{
143 144 145 146 147 148 149 150 151 152 153 154 155
	unsigned seen = 0;
	const char *name = ce->name;

	while (pos < active_nr) {
		ce = active_cache[pos];
		if (strcmp(name, ce->name))
			break;
		seen |= (1 << ce_stage(ce));
		pos++;
	}
	if ((stages & seen) != stages)
		return error(_("path '%s' does not have all necessary versions"),
			     name);
156 157 158
	return 0;
}

159 160
static int checkout_stage(int stage, const struct cache_entry *ce, int pos,
			  const struct checkout *state)
161 162 163 164 165 166 167
{
	while (pos < active_nr &&
	       !strcmp(active_cache[pos]->name, ce->name)) {
		if (ce_stage(active_cache[pos]) == stage)
			return checkout_entry(active_cache[pos], state, NULL);
		pos++;
	}
168 169 170 171
	if (stage == 2)
		return error(_("path '%s' does not have our version"), ce->name);
	else
		return error(_("path '%s' does not have their version"), ce->name);
172
}
173

174
static int checkout_merged(int pos, const struct checkout *state)
175 176 177 178 179
{
	struct cache_entry *ce = active_cache[pos];
	const char *path = ce->name;
	mmfile_t ancestor, ours, theirs;
	int status;
180
	struct object_id oid;
181
	mmbuffer_t result_buf;
182
	struct object_id threeway[3];
183
	unsigned mode = 0;
184

185 186 187 188 189 190
	memset(threeway, 0, sizeof(threeway));
	while (pos < active_nr) {
		int stage;
		stage = ce_stage(ce);
		if (!stage || strcmp(path, ce->name))
			break;
191
		oidcpy(&threeway[stage - 1], &ce->oid);
192 193 194 195 196
		if (stage == 2)
			mode = create_ce_mode(ce->ce_mode);
		pos++;
		ce = active_cache[pos];
	}
197
	if (is_null_oid(&threeway[1]) || is_null_oid(&threeway[2]))
198
		return error(_("path '%s' does not have necessary versions"), path);
199

200 201 202
	read_mmblob(&ancestor, &threeway[0]);
	read_mmblob(&ours, &threeway[1]);
	read_mmblob(&theirs, &threeway[2]);
203

204 205 206 207
	/*
	 * NEEDSWORK: re-create conflicts from merges with
	 * merge.renormalize set, too
	 */
208
	status = ll_merge(&result_buf, path, &ancestor, "base",
209
			  &ours, "ours", &theirs, "theirs", NULL);
210 211 212 213 214
	free(ancestor.ptr);
	free(ours.ptr);
	free(theirs.ptr);
	if (status < 0 || !result_buf.ptr) {
		free(result_buf.ptr);
215
		return error(_("path '%s': cannot merge"), path);
216 217 218 219 220
	}

	/*
	 * NEEDSWORK:
	 * There is absolutely no reason to write this as a blob object
J
Johannes Schindelin 已提交
221 222 223 224 225 226 227 228
	 * and create a phony cache entry.  This hack is primarily to get
	 * to the write_entry() machinery that massages the contents to
	 * work-tree format and writes out which only allows it for a
	 * cache entry.  The code in write_entry() needs to be refactored
	 * to allow us to feed a <buffer, size, mode> instead of a cache
	 * entry.  Such a refactoring would help merge_recursive as well
	 * (it also writes the merge result to the object database even
	 * when it may contain conflicts).
229 230
	 */
	if (write_sha1_file(result_buf.ptr, result_buf.size,
231
			    blob_type, oid.hash))
232
		die(_("Unable to add merge result for '%s'"), path);
J
Junio C Hamano 已提交
233
	free(result_buf.ptr);
234
	ce = make_cache_entry(mode, oid.hash, path, 2, 0);
235
	if (!ce)
236
		die(_("make_cache_entry failed for path '%s'"), path);
237
	status = checkout_entry(ce, state, NULL);
J
Johannes Schindelin 已提交
238
	free(ce);
239 240
	return status;
}
241

242 243
static int checkout_paths(const struct checkout_opts *opts,
			  const char *revision)
D
Daniel Barkalow 已提交
244 245
{
	int pos;
R
René Scharfe 已提交
246
	struct checkout state = CHECKOUT_INIT;
D
Daniel Barkalow 已提交
247
	static char *ps_matched;
248
	struct object_id rev;
D
Daniel Barkalow 已提交
249
	struct commit *head;
250
	int errs = 0;
251
	struct lock_file lock_file = LOCK_INIT;
252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276

	if (opts->track != BRANCH_TRACK_UNSPECIFIED)
		die(_("'%s' cannot be used with updating paths"), "--track");

	if (opts->new_branch_log)
		die(_("'%s' cannot be used with updating paths"), "-l");

	if (opts->force && opts->patch_mode)
		die(_("'%s' cannot be used with updating paths"), "-f");

	if (opts->force_detach)
		die(_("'%s' cannot be used with updating paths"), "--detach");

	if (opts->merge && opts->patch_mode)
		die(_("'%s' cannot be used with %s"), "--merge", "--patch");

	if (opts->force && opts->merge)
		die(_("'%s' cannot be used with %s"), "-f", "-m");

	if (opts->new_branch)
		die(_("Cannot update paths and switch to branch '%s' at the same time."),
		    opts->new_branch);

	if (opts->patch_mode)
		return run_add_interactive(revision, "--patch=checkout",
277
					   &opts->pathspec);
278

279
	hold_locked_index(&lock_file, LOCK_DIE_ON_ERROR);
280
	if (read_cache_preload(&opts->pathspec) < 0)
V
Vasco Almeida 已提交
281
		return error(_("index file corrupt"));
282

283
	if (opts->source_tree)
284
		read_tree_some(opts->source_tree, &opts->pathspec);
285

286
	ps_matched = xcalloc(opts->pathspec.nr, 1);
D
Daniel Barkalow 已提交
287

288 289 290 291
	/*
	 * Make sure all pathspecs participated in locating the paths
	 * to be checked out.
	 */
D
Daniel Barkalow 已提交
292 293
	for (pos = 0; pos < active_nr; pos++) {
		struct cache_entry *ce = active_cache[pos];
294
		ce->ce_flags &= ~CE_MATCHED;
295 296
		if (!opts->ignore_skipworktree && ce_skip_worktree(ce))
			continue;
297
		if (opts->source_tree && !(ce->ce_flags & CE_UPDATE))
298 299 300 301 302 303 304
			/*
			 * "git checkout tree-ish -- path", but this entry
			 * is in the original index; it will not be checked
			 * out to the working tree and it does not matter
			 * if pathspec matched this entry.  We will not do
			 * anything to this entry at all.
			 */
305
			continue;
306 307 308 309 310 311 312 313 314 315 316 317 318 319
		/*
		 * Either this entry came from the tree-ish we are
		 * checking the paths out of, or we are checking out
		 * of the index.
		 *
		 * If it comes from the tree-ish, we already know it
		 * matches the pathspec and could just stamp
		 * CE_MATCHED to it from update_some(). But we still
		 * need ps_matched and read_tree_recursive (and
		 * eventually tree_entry_interesting) cannot fill
		 * ps_matched yet. Once it can, we can avoid calling
		 * match_pathspec() for _all_ entries when
		 * opts->source_tree != NULL.
		 */
320
		if (ce_path_match(ce, &opts->pathspec, ps_matched))
321
			ce->ce_flags |= CE_MATCHED;
D
Daniel Barkalow 已提交
322 323
	}

324
	if (report_path_error(ps_matched, &opts->pathspec, opts->prefix)) {
325
		free(ps_matched);
D
Daniel Barkalow 已提交
326
		return 1;
327 328
	}
	free(ps_matched);
D
Daniel Barkalow 已提交
329

330 331
	/* "checkout -m path" to recreate conflicted state */
	if (opts->merge)
332
		unmerge_marked_index(&the_index);
333

334 335
	/* Any unmerged paths? */
	for (pos = 0; pos < active_nr; pos++) {
336
		const struct cache_entry *ce = active_cache[pos];
337
		if (ce->ce_flags & CE_MATCHED) {
338 339
			if (!ce_stage(ce))
				continue;
340
			if (opts->force) {
341
				warning(_("path '%s' is unmerged"), ce->name);
342 343
			} else if (opts->writeout_stage) {
				errs |= check_stage(opts->writeout_stage, ce, pos);
344
			} else if (opts->merge) {
345
				errs |= check_stages((1<<2) | (1<<3), ce, pos);
346 347
			} else {
				errs = 1;
348
				error(_("path '%s' is unmerged"), ce->name);
349
			}
350 351 352 353 354 355
			pos = skip_same_name(ce, pos) - 1;
		}
	}
	if (errs)
		return 1;

356
	/* Now we are committed to check them out */
D
Daniel Barkalow 已提交
357 358
	state.force = 1;
	state.refresh_cache = 1;
359
	state.istate = &the_index;
360 361

	enable_delayed_checkout(&state);
D
Daniel Barkalow 已提交
362 363
	for (pos = 0; pos < active_nr; pos++) {
		struct cache_entry *ce = active_cache[pos];
364
		if (ce->ce_flags & CE_MATCHED) {
365 366 367 368
			if (!ce_stage(ce)) {
				errs |= checkout_entry(ce, &state, NULL);
				continue;
			}
369 370 371
			if (opts->writeout_stage)
				errs |= checkout_stage(opts->writeout_stage, ce, pos, &state);
			else if (opts->merge)
372
				errs |= checkout_merged(pos, &state);
373
			pos = skip_same_name(ce, pos) - 1;
D
Daniel Barkalow 已提交
374 375
		}
	}
376
	errs |= finish_delayed_checkout(&state);
D
Daniel Barkalow 已提交
377

378
	if (write_locked_index(&the_index, &lock_file, COMMIT_LOCK))
379
		die(_("unable to write new index file"));
380

381
	read_ref_full("HEAD", 0, &rev, NULL);
382
	head = lookup_commit_reference_gently(&rev, 1);
D
Daniel Barkalow 已提交
383

384 385
	errs |= post_checkout_hook(head, head, 0);
	return errs;
D
Daniel Barkalow 已提交
386 387
}

388 389
static void show_local_changes(struct object *head,
			       const struct diff_options *opts)
D
Daniel Barkalow 已提交
390 391 392 393
{
	struct rev_info rev;
	/* I think we want full paths, even if we're in a subdirectory. */
	init_revisions(&rev, NULL);
394
	rev.diffopt.flags = opts->flags;
D
Daniel Barkalow 已提交
395
	rev.diffopt.output_format |= DIFF_FORMAT_NAME_STATUS;
T
Thomas Rast 已提交
396
	diff_setup_done(&rev.diffopt);
D
Daniel Barkalow 已提交
397 398 399 400
	add_pending_object(&rev, head, NULL);
	run_diff_index(&rev, 0);
}

401
static void describe_detached_head(const char *msg, struct commit *commit)
D
Daniel Barkalow 已提交
402
{
403
	struct strbuf sb = STRBUF_INIT;
404

405 406
	if (!parse_commit(commit))
		pp_commit_easy(CMIT_FMT_ONELINE, commit, &sb);
407 408 409 410 411 412 413
	if (print_sha1_ellipsis()) {
		fprintf(stderr, "%s %s... %s\n", msg,
			find_unique_abbrev(commit->object.oid.hash, DEFAULT_ABBREV), sb.buf);
	} else {
		fprintf(stderr, "%s %s %s\n", msg,
			find_unique_abbrev(commit->object.oid.hash, DEFAULT_ABBREV), sb.buf);
	}
D
Daniel Barkalow 已提交
414 415 416
	strbuf_release(&sb);
}

417 418
static int reset_tree(struct tree *tree, const struct checkout_opts *o,
		      int worktree, int *writeout_error)
D
Daniel Barkalow 已提交
419 420 421
{
	struct unpack_trees_options opts;
	struct tree_desc tree_desc;
422

D
Daniel Barkalow 已提交
423 424
	memset(&opts, 0, sizeof(opts));
	opts.head_idx = -1;
425 426
	opts.update = worktree;
	opts.skip_unmerged = !worktree;
D
Daniel Barkalow 已提交
427 428 429
	opts.reset = 1;
	opts.merge = 1;
	opts.fn = oneway_merge;
430
	opts.verbose_update = o->show_progress;
431 432
	opts.src_index = &the_index;
	opts.dst_index = &the_index;
D
Daniel Barkalow 已提交
433 434
	parse_tree(tree);
	init_tree_desc(&tree_desc, tree->buffer, tree->size);
435 436
	switch (unpack_trees(1, &tree_desc, &opts)) {
	case -2:
437
		*writeout_error = 1;
438 439 440 441 442 443
		/*
		 * We return 0 nevertheless, as the index is all right
		 * and more importantly we have made best efforts to
		 * update paths in the work tree, and we cannot revert
		 * them.
		 */
444
		/* fallthrough */
445 446 447
	case 0:
		return 0;
	default:
448
		return 128;
449
	}
D
Daniel Barkalow 已提交
450 451 452 453 454 455
}

struct branch_info {
	const char *name; /* The short name used */
	const char *path; /* The full name of a real branch */
	struct commit *commit; /* The named commit */
456 457 458 459 460
	/*
	 * if not null the branch is detached because it's already
	 * checked out in this checkout
	 */
	char *checkout;
D
Daniel Barkalow 已提交
461 462 463 464
};

static void setup_branch_path(struct branch_info *branch)
{
465
	struct strbuf buf = STRBUF_INIT;
466

467
	strbuf_branchname(&buf, branch->name, INTERPRET_BRANCH_LOCAL);
468
	if (strcmp(buf.buf, branch->name))
469
		branch->name = xstrdup(buf.buf);
470
	strbuf_splice(&buf, 0, 0, "refs/heads/", 11);
D
Daniel Barkalow 已提交
471 472 473
	branch->path = strbuf_detach(&buf, NULL);
}

474
static int merge_working_tree(const struct checkout_opts *opts,
475 476
			      struct branch_info *old_branch_info,
			      struct branch_info *new_branch_info,
477
			      int *writeout_error)
D
Daniel Barkalow 已提交
478 479
{
	int ret;
480
	struct lock_file lock_file = LOCK_INIT;
481

482
	hold_locked_index(&lock_file, LOCK_DIE_ON_ERROR);
483
	if (read_cache_preload(NULL) < 0)
V
Vasco Almeida 已提交
484
		return error(_("index file corrupt"));
D
Daniel Barkalow 已提交
485

486
	resolve_undo_clear();
D
Daniel Barkalow 已提交
487
	if (opts->force) {
488
		ret = reset_tree(new_branch_info->commit->tree, opts, 1, writeout_error);
D
Daniel Barkalow 已提交
489 490 491 492 493 494
		if (ret)
			return ret;
	} else {
		struct tree_desc trees[2];
		struct tree *tree;
		struct unpack_trees_options topts;
495

D
Daniel Barkalow 已提交
496 497
		memset(&topts, 0, sizeof(topts));
		topts.head_idx = -1;
498 499
		topts.src_index = &the_index;
		topts.dst_index = &the_index;
D
Daniel Barkalow 已提交
500

501
		setup_unpack_trees_porcelain(&topts, "checkout");
502

D
Daniel Barkalow 已提交
503 504 505
		refresh_cache(REFRESH_QUIET);

		if (unmerged_cache()) {
506
			error(_("you need to resolve your current index first"));
507
			return 1;
D
Daniel Barkalow 已提交
508
		}
509 510

		/* 2-way merge to the new branch */
511
		topts.initial_checkout = is_cache_unborn();
512 513
		topts.update = 1;
		topts.merge = 1;
514
		topts.gently = opts->merge && old_branch_info->commit;
515
		topts.verbose_update = opts->show_progress;
516
		topts.fn = twoway_merge;
517 518 519 520 521
		if (opts->overwrite_ignore) {
			topts.dir = xcalloc(1, sizeof(*topts.dir));
			topts.dir->flags |= DIR_SHOW_IGNORED;
			setup_standard_excludes(topts.dir);
		}
522 523
		tree = parse_tree_indirect(old_branch_info->commit ?
					   &old_branch_info->commit->object.oid :
524
					   the_hash_algo->empty_tree);
525
		init_tree_desc(&trees[0], tree->buffer, tree->size);
526
		tree = parse_tree_indirect(&new_branch_info->commit->object.oid);
527 528
		init_tree_desc(&trees[1], tree->buffer, tree->size);

529
		ret = unpack_trees(2, trees, &topts);
530
		if (ret == -1) {
D
Daniel Barkalow 已提交
531 532 533 534 535 536 537
			/*
			 * Unpack couldn't do a trivial merge; either
			 * give up or do a real merge, depending on
			 * whether the merge flag was used.
			 */
			struct tree *result;
			struct tree *work;
538
			struct merge_options o;
D
Daniel Barkalow 已提交
539 540
			if (!opts->merge)
				return 1;
541 542

			/*
543
			 * Without old_branch_info->commit, the below is the same as
544 545
			 * the two-tree unpack we already tried and failed.
			 */
546
			if (!old_branch_info->commit)
547
				return 1;
D
Daniel Barkalow 已提交
548 549 550 551 552 553 554 555 556 557 558 559 560 561

			/* Do more real merge */

			/*
			 * We update the index fully, then write the
			 * tree from the index, then merge the new
			 * branch with the current tree, with the old
			 * branch as the base. Then we reset the index
			 * (but not the working tree) to the new
			 * branch, leaving the working tree as the
			 * merged version, but skipping unmerged
			 * entries in the index.
			 */

562
			add_files_to_cache(NULL, NULL, 0);
J
Jonathan Nieder 已提交
563 564 565 566 567 568 569
			/*
			 * NEEDSWORK: carrying over local changes
			 * when branches have different end-of-line
			 * normalization (or clean+smudge rules) is
			 * a pain; plumb in an option to set
			 * o.renormalize?
			 */
570 571 572
			init_merge_options(&o);
			o.verbosity = 0;
			work = write_tree_from_memory(&o);
D
Daniel Barkalow 已提交
573

574
			ret = reset_tree(new_branch_info->commit->tree, opts, 1,
575
					 writeout_error);
D
Daniel Barkalow 已提交
576 577
			if (ret)
				return ret;
578 579
			o.ancestor = old_branch_info->name;
			o.branch1 = new_branch_info->name;
580
			o.branch2 = "local";
581 582
			ret = merge_trees(&o, new_branch_info->commit->tree, work,
				old_branch_info->commit->tree, &result);
583 584
			if (ret < 0)
				exit(128);
585
			ret = reset_tree(new_branch_info->commit->tree, opts, 0,
586
					 writeout_error);
587
			strbuf_release(&o.obuf);
588 589
			if (ret)
				return ret;
D
Daniel Barkalow 已提交
590 591 592
		}
	}

593 594 595 596
	if (!active_cache_tree)
		active_cache_tree = cache_tree();

	if (!cache_tree_fully_valid(active_cache_tree))
597
		cache_tree_update(&the_index, WRITE_TREE_SILENT | WRITE_TREE_REPAIR);
598

599
	if (write_locked_index(&the_index, &lock_file, COMMIT_LOCK))
600
		die(_("unable to write new index file"));
D
Daniel Barkalow 已提交
601

602
	if (!opts->force && !opts->quiet)
603
		show_local_changes(&new_branch_info->commit->object, &opts->diff_options);
D
Daniel Barkalow 已提交
604 605 606 607

	return 0;
}

608
static void report_tracking(struct branch_info *new_branch_info)
609
{
610
	struct strbuf sb = STRBUF_INIT;
611
	struct branch *branch = branch_get(new_branch_info->name);
612

613
	if (!format_tracking_info(branch, &sb))
614
		return;
615 616
	fputs(sb.buf, stdout);
	strbuf_release(&sb);
617
}
618

619
static void update_refs_for_switch(const struct checkout_opts *opts,
620 621
				   struct branch_info *old_branch_info,
				   struct branch_info *new_branch_info)
D
Daniel Barkalow 已提交
622
{
623
	struct strbuf msg = STRBUF_INIT;
624
	const char *old_desc, *reflog_msg;
D
Daniel Barkalow 已提交
625
	if (opts->new_branch) {
626
		if (opts->new_orphan_branch) {
627 628 629 630 631
			char *refname;

			refname = mkpathdup("refs/heads/%s", opts->new_orphan_branch);
			if (opts->new_branch_log &&
			    !should_autocreate_reflog(refname)) {
632
				int ret;
633
				struct strbuf err = STRBUF_INIT;
634

635
				ret = safe_create_reflog(refname, 1, &err);
636
				if (ret) {
637 638 639
					fprintf(stderr, _("Can not do reflog for '%s': %s\n"),
						opts->new_orphan_branch, err.buf);
					strbuf_release(&err);
640
					free(refname);
641 642
					return;
				}
643
				strbuf_release(&err);
644
			}
645
			free(refname);
646 647
		}
		else
648
			create_branch(opts->new_branch, new_branch_info->name,
T
Tay Ray Chuan 已提交
649
				      opts->new_branch_force ? 1 : 0,
650
				      opts->new_branch_force ? 1 : 0,
651
				      opts->new_branch_log,
652
				      opts->quiet,
653
				      opts->track);
654 655
		new_branch_info->name = opts->new_branch;
		setup_branch_path(new_branch_info);
D
Daniel Barkalow 已提交
656 657
	}

658 659 660
	old_desc = old_branch_info->name;
	if (!old_desc && old_branch_info->commit)
		old_desc = oid_to_hex(&old_branch_info->commit->object.oid);
661 662 663 664

	reflog_msg = getenv("GIT_REFLOG_ACTION");
	if (!reflog_msg)
		strbuf_addf(&msg, "checkout: moving from %s to %s",
665
			old_desc ? old_desc : "(invalid)", new_branch_info->name);
666 667
	else
		strbuf_insert(&msg, 0, reflog_msg, strlen(reflog_msg));
D
Daniel Barkalow 已提交
668

669
	if (!strcmp(new_branch_info->name, "HEAD") && !new_branch_info->path && !opts->force_detach) {
670
		/* Nothing to do. */
671 672
	} else if (opts->force_detach || !new_branch_info->path) {	/* No longer on any branch. */
		update_ref(msg.buf, "HEAD", &new_branch_info->commit->object.oid, NULL,
673
			   REF_NO_DEREF, UPDATE_REFS_DIE_ON_ERR);
674
		if (!opts->quiet) {
675
			if (old_branch_info->path &&
676
			    advice_detached_head && !opts->force_detach)
677 678
				detach_advice(new_branch_info->name);
			describe_detached_head(_("HEAD is now at"), new_branch_info->commit);
679
		}
680 681
	} else if (new_branch_info->path) {	/* Switch branches. */
		if (create_symref("HEAD", new_branch_info->path, msg.buf) < 0)
682
			die(_("unable to update HEAD"));
D
Daniel Barkalow 已提交
683
		if (!opts->quiet) {
684
			if (old_branch_info->path && !strcmp(new_branch_info->path, old_branch_info->path)) {
685 686
				if (opts->new_branch_force)
					fprintf(stderr, _("Reset branch '%s'\n"),
687
						new_branch_info->name);
688 689
				else
					fprintf(stderr, _("Already on '%s'\n"),
690
						new_branch_info->name);
691 692
			} else if (opts->new_branch) {
				if (opts->branch_exists)
693
					fprintf(stderr, _("Switched to and reset branch '%s'\n"), new_branch_info->name);
694
				else
695
					fprintf(stderr, _("Switched to a new branch '%s'\n"), new_branch_info->name);
696
			} else {
697
				fprintf(stderr, _("Switched to branch '%s'\n"),
698
					new_branch_info->name);
699
			}
D
Daniel Barkalow 已提交
700
		}
701 702 703
		if (old_branch_info->path && old_branch_info->name) {
			if (!ref_exists(old_branch_info->path) && reflog_exists(old_branch_info->path))
				delete_reflog(old_branch_info->path);
704
		}
D
Daniel Barkalow 已提交
705 706 707
	}
	remove_branch_state();
	strbuf_release(&msg);
708
	if (!opts->quiet &&
709 710
	    (new_branch_info->path || (!opts->force_detach && !strcmp(new_branch_info->name, "HEAD"))))
		report_tracking(new_branch_info);
D
Daniel Barkalow 已提交
711 712
}

713
static int add_pending_uninteresting_ref(const char *refname,
714
					 const struct object_id *oid,
715
					 int flags, void *cb_data)
716
{
717
	add_pending_oid(cb_data, refname, oid, UNINTERESTING);
718 719
	return 0;
}
720 721 722

static void describe_one_orphan(struct strbuf *sb, struct commit *commit)
{
723
	strbuf_addstr(sb, "  ");
724
	strbuf_add_unique_abbrev(sb, commit->object.oid.hash, DEFAULT_ABBREV);
725
	strbuf_addch(sb, ' ');
726 727
	if (!parse_commit(commit))
		pp_commit_easy(CMIT_FMT_ONELINE, commit, sb);
728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747
	strbuf_addch(sb, '\n');
}

#define ORPHAN_CUTOFF 4
static void suggest_reattach(struct commit *commit, struct rev_info *revs)
{
	struct commit *c, *last = NULL;
	struct strbuf sb = STRBUF_INIT;
	int lost = 0;
	while ((c = get_revision(revs)) != NULL) {
		if (lost < ORPHAN_CUTOFF)
			describe_one_orphan(&sb, c);
		last = c;
		lost++;
	}
	if (ORPHAN_CUTOFF < lost) {
		int more = lost - ORPHAN_CUTOFF;
		if (more == 1)
			describe_one_orphan(&sb, last);
		else
748
			strbuf_addf(&sb, _(" ... and %d more.\n"), more);
749 750 751
	}

	fprintf(stderr,
752 753 754 755 756
		Q_(
		/* The singular version */
		"Warning: you are leaving %d commit behind, "
		"not connected to\n"
		"any of your branches:\n\n"
757
		"%s\n",
758 759
		/* The plural version */
		"Warning: you are leaving %d commits behind, "
760 761
		"not connected to\n"
		"any of your branches:\n\n"
762
		"%s\n",
763 764 765
		/* Give ngettext() the count */
		lost),
		lost,
766
		sb.buf);
767
	strbuf_release(&sb);
768 769 770

	if (advice_detached_head)
		fprintf(stderr,
771 772 773 774 775 776
			Q_(
			/* The singular version */
			"If you want to keep it by creating a new branch, "
			"this may be a good time\nto do so with:\n\n"
			" git branch <new-branch-name> %s\n\n",
			/* The plural version */
777 778
			"If you want to keep them by creating a new branch, "
			"this may be a good time\nto do so with:\n\n"
779 780 781
			" git branch <new-branch-name> %s\n\n",
			/* Give ngettext() the count */
			lost),
B
brian m. carlson 已提交
782
			find_unique_abbrev(commit->object.oid.hash, DEFAULT_ABBREV));
783 784 785 786 787 788 789
}

/*
 * We are about to leave commit that was at the tip of a detached
 * HEAD.  If it is not reachable from any ref, this is the last chance
 * for the user to do so without resorting to reflog.
 */
790
static void orphaned_commit_warning(struct commit *old_commit, struct commit *new_commit)
791 792
{
	struct rev_info revs;
793
	struct object *object = &old_commit->object;
794 795

	init_revisions(&revs, NULL);
796 797 798
	setup_revisions(0, NULL, &revs, NULL);

	object->flags &= ~UNINTERESTING;
799
	add_pending_object(&revs, object, oid_to_hex(&object->oid));
800

801
	for_each_ref(add_pending_uninteresting_ref, &revs);
802
	add_pending_oid(&revs, "HEAD", &new_commit->object.oid, UNINTERESTING);
803

804
	if (prepare_revision_walk(&revs))
J
Junio C Hamano 已提交
805
		die(_("internal error in revision walk"));
806 807
	if (!(old_commit->object.flags & UNINTERESTING))
		suggest_reattach(old_commit, &revs);
808
	else
809
		describe_detached_head(_("Previous HEAD position was"), old_commit);
810

811
	/* Clean up objects used, as they will be reused. */
812
	clear_commit_marks_all(ALL_REV_FLAGS);
813 814
}

815
static int switch_branches(const struct checkout_opts *opts,
816
			   struct branch_info *new_branch_info)
D
Daniel Barkalow 已提交
817 818
{
	int ret = 0;
819
	struct branch_info old_branch_info;
820
	void *path_to_free;
821
	struct object_id rev;
822
	int flag, writeout_error = 0;
823 824 825 826
	memset(&old_branch_info, 0, sizeof(old_branch_info));
	old_branch_info.path = path_to_free = resolve_refdup("HEAD", 0, &rev, &flag);
	if (old_branch_info.path)
		old_branch_info.commit = lookup_commit_reference_gently(&rev, 1);
827
	if (!(flag & REF_ISSYMREF))
828
		old_branch_info.path = NULL;
D
Daniel Barkalow 已提交
829

830 831
	if (old_branch_info.path)
		skip_prefix(old_branch_info.path, "refs/heads/", &old_branch_info.name);
D
Daniel Barkalow 已提交
832

833 834 835 836
	if (!new_branch_info->name) {
		new_branch_info->name = "HEAD";
		new_branch_info->commit = old_branch_info.commit;
		if (!new_branch_info->commit)
837
			die(_("You are on a branch yet to be born"));
838
		parse_commit_or_die(new_branch_info->commit);
D
Daniel Barkalow 已提交
839 840
	}

841
	ret = merge_working_tree(opts, &old_branch_info, new_branch_info, &writeout_error);
842 843
	if (ret) {
		free(path_to_free);
D
Daniel Barkalow 已提交
844
		return ret;
845
	}
D
Daniel Barkalow 已提交
846

847 848
	if (!opts->quiet && !old_branch_info.path && old_branch_info.commit && new_branch_info->commit != old_branch_info.commit)
		orphaned_commit_warning(old_branch_info.commit, new_branch_info->commit);
849

850
	update_refs_for_switch(opts, &old_branch_info, new_branch_info);
D
Daniel Barkalow 已提交
851

852
	ret = post_checkout_hook(old_branch_info.commit, new_branch_info->commit, 1);
853
	free(path_to_free);
854
	return ret || writeout_error;
D
Daniel Barkalow 已提交
855 856
}

857 858
static int git_checkout_config(const char *var, const char *value, void *cb)
{
859 860 861 862 863
	if (!strcmp(var, "diff.ignoresubmodules")) {
		struct checkout_opts *opts = cb;
		handle_ignore_submodules_arg(&opts->diff_options, value);
		return 0;
	}
864

865
	if (starts_with(var, "submodule."))
866
		return git_default_submodule_config(var, value, NULL);
867

868
	return git_xmerge_config(var, value, NULL);
869 870
}

871 872
static int parse_branchname_arg(int argc, const char **argv,
				int dwim_new_local_branch_ok,
873
				struct branch_info *new_branch_info,
874
				struct checkout_opts *opts,
875
				struct object_id *rev)
876
{
877 878
	struct tree **source_tree = &opts->source_tree;
	const char **new_branch = &opts->new_branch;
879
	int argcount = 0;
880
	struct object_id branch_rev;
881
	const char *arg;
882 883 884
	int dash_dash_pos;
	int has_dash_dash = 0;
	int i;
885 886 887 888 889 890 891 892 893 894 895

	/*
	 * case 1: git checkout <ref> -- [<paths>]
	 *
	 *   <ref> must be a valid tree, everything after the '--' must be
	 *   a path.
	 *
	 * case 2: git checkout -- [<paths>]
	 *
	 *   everything after the '--' must be paths.
	 *
896
	 * case 3: git checkout <something> [--]
897
	 *
898 899 900 901 902
	 *   (a) If <something> is a commit, that is to
	 *       switch to the branch or detach HEAD at it.  As a special case,
	 *       if <something> is A...B (missing A or B means HEAD but you can
	 *       omit at most one side), and if there is a unique merge base
	 *       between A and B, A...B names that merge base.
903
	 *
904
	 *   (b) If <something> is _not_ a commit, either "--" is present
J
Justin Lebar 已提交
905
	 *       or <something> is not a path, no -t or -b was given, and
906 907 908
	 *       and there is a tracking branch whose name is <something>
	 *       in one and only one remote, then this is a short-hand to
	 *       fork local <something> from that remote-tracking branch.
909
	 *
910 911 912 913 914 915 916 917 918 919
	 *   (c) Otherwise, if "--" is present, treat it like case (1).
	 *
	 *   (d) Otherwise :
	 *       - if it's a reference, treat it like case (1)
	 *       - else if it's a path, treat it like case (2)
	 *       - else: fail.
	 *
	 * case 4: git checkout <something> <paths>
	 *
	 *   The first argument must not be ambiguous.
920 921 922 923 924 925 926 927 928
	 *   - If it's *only* a reference, treat it like case (1).
	 *   - If it's only a path, treat it like case (2).
	 *   - else: fail.
	 *
	 */
	if (!argc)
		return 0;

	arg = argv[0];
929 930 931 932 933 934 935 936 937 938 939 940 941
	dash_dash_pos = -1;
	for (i = 0; i < argc; i++) {
		if (!strcmp(argv[i], "--")) {
			dash_dash_pos = i;
			break;
		}
	}
	if (dash_dash_pos == 0)
		return 1; /* case (2) */
	else if (dash_dash_pos == 1)
		has_dash_dash = 1; /* case (3) or (1) */
	else if (dash_dash_pos >= 2)
		die(_("only one reference expected, %d given."), dash_dash_pos);
942 943 944 945

	if (!strcmp(arg, "-"))
		arg = "@{-1}";

946
	if (get_oid_mb(arg, rev)) {
947 948 949 950 951 952 953 954 955 956
		/*
		 * Either case (3) or (4), with <something> not being
		 * a commit, or an attempt to use case (1) with an
		 * invalid ref.
		 *
		 * It's likely an error, but we need to find out if
		 * we should auto-create the branch, case (3).(b).
		 */
		int recover_with_dwim = dwim_new_local_branch_ok;

957
		if (!has_dash_dash &&
958
		    (check_filename(opts->prefix, arg) || !no_wildcard(arg)))
959 960 961 962 963 964 965 966 967 968
			recover_with_dwim = 0;
		/*
		 * Accept "git checkout foo" and "git checkout foo --"
		 * as candidates for dwim.
		 */
		if (!(argc == 1 && !has_dash_dash) &&
		    !(argc == 2 && has_dash_dash))
			recover_with_dwim = 0;

		if (recover_with_dwim) {
969
			const char *remote = unique_tracking_name(arg, rev);
970 971 972 973 974 975 976 977 978 979 980 981
			if (remote) {
				*new_branch = arg;
				arg = remote;
				/* DWIMmed to create local branch, case (3).(b) */
			} else {
				recover_with_dwim = 0;
			}
		}

		if (!recover_with_dwim) {
			if (has_dash_dash)
				die(_("invalid reference: %s"), arg);
982 983 984 985 986 987 988 989 990
			return argcount;
		}
	}

	/* we can't end up being in (2) anymore, eat the argument */
	argcount++;
	argv++;
	argc--;

991 992
	new_branch_info->name = arg;
	setup_branch_path(new_branch_info);
993

994 995
	if (!check_refname_format(new_branch_info->path, 0) &&
	    !read_ref(new_branch_info->path, &branch_rev))
996
		oidcpy(rev, &branch_rev);
997
	else
998
		new_branch_info->path = NULL; /* not an existing branch */
999

1000 1001
	new_branch_info->commit = lookup_commit_reference_gently(rev, 1);
	if (!new_branch_info->commit) {
1002
		/* not a commit */
1003
		*source_tree = parse_tree_indirect(rev);
1004
	} else {
1005 1006
		parse_commit_or_die(new_branch_info->commit);
		*source_tree = new_branch_info->commit->tree;
1007 1008 1009
	}

	if (!*source_tree)                   /* case (1): want a tree */
J
Junio C Hamano 已提交
1010
		die(_("reference is not a tree: %s"), arg);
1011
	if (!has_dash_dash) {	/* case (3).(d) -> (1) */
1012 1013 1014 1015 1016 1017 1018
		/*
		 * Do not complain the most common case
		 *	git checkout branch
		 * even if there happen to be a file called 'branch';
		 * it would be extremely annoying.
		 */
		if (argc)
1019
			verify_non_filename(opts->prefix, arg);
1020 1021 1022 1023 1024 1025 1026 1027 1028
	} else {
		argcount++;
		argv++;
		argc--;
	}

	return argcount;
}

1029
static int switch_unborn_to_new_branch(const struct checkout_opts *opts)
1030 1031 1032 1033
{
	int status;
	struct strbuf branch_ref = STRBUF_INIT;

1034 1035
	if (!opts->new_branch)
		die(_("You are on a branch yet to be born"));
1036 1037 1038
	strbuf_addf(&branch_ref, "refs/heads/%s", opts->new_branch);
	status = create_symref("HEAD", branch_ref.buf, "checkout -b");
	strbuf_release(&branch_ref);
1039 1040 1041
	if (!opts->quiet)
		fprintf(stderr, _("Switched to a new branch '%s'\n"),
			opts->new_branch);
1042 1043 1044
	return status;
}

1045
static int checkout_branch(struct checkout_opts *opts,
1046
			   struct branch_info *new_branch_info)
1047
{
1048
	if (opts->pathspec.nr)
1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074
		die(_("paths cannot be used with switching branches"));

	if (opts->patch_mode)
		die(_("'%s' cannot be used with switching branches"),
		    "--patch");

	if (opts->writeout_stage)
		die(_("'%s' cannot be used with switching branches"),
		    "--ours/--theirs");

	if (opts->force && opts->merge)
		die(_("'%s' cannot be used with '%s'"), "-f", "-m");

	if (opts->force_detach && opts->new_branch)
		die(_("'%s' cannot be used with '%s'"),
		    "--detach", "-b/-B/--orphan");

	if (opts->new_orphan_branch) {
		if (opts->track != BRANCH_TRACK_UNSPECIFIED)
			die(_("'%s' cannot be used with '%s'"), "--orphan", "-t");
	} else if (opts->force_detach) {
		if (opts->track != BRANCH_TRACK_UNSPECIFIED)
			die(_("'%s' cannot be used with '%s'"), "--detach", "-t");
	} else if (opts->track == BRANCH_TRACK_UNSPECIFIED)
		opts->track = git_branch_track;

1075
	if (new_branch_info->name && !new_branch_info->commit)
1076
		die(_("Cannot switch branch to a non-commit '%s'"),
1077
		    new_branch_info->name);
1078

1079
	if (new_branch_info->path && !opts->force_detach && !opts->new_branch &&
1080
	    !opts->ignore_other_worktrees) {
1081
		int flag;
1082
		char *head_ref = resolve_refdup("HEAD", 0, NULL, &flag);
1083
		if (head_ref &&
1084 1085
		    (!(flag & REF_ISSYMREF) || strcmp(head_ref, new_branch_info->path)))
			die_if_checked_out(new_branch_info->path, 1);
1086 1087 1088
		free(head_ref);
	}

1089
	if (!new_branch_info->commit && opts->new_branch) {
1090
		struct object_id rev;
1091 1092
		int flag;

1093
		if (!read_ref_full("HEAD", 0, &rev, &flag) &&
1094
		    (flag & REF_ISSYMREF) && is_null_oid(&rev))
1095 1096
			return switch_unborn_to_new_branch(opts);
	}
1097
	return switch_branches(opts, new_branch_info);
1098 1099
}

D
Daniel Barkalow 已提交
1100 1101 1102
int cmd_checkout(int argc, const char **argv, const char *prefix)
{
	struct checkout_opts opts;
1103
	struct branch_info new_branch_info;
1104
	char *conflict_style = NULL;
J
Junio C Hamano 已提交
1105
	int dwim_new_local_branch = 1;
D
Daniel Barkalow 已提交
1106
	struct option options[] = {
1107 1108 1109 1110 1111
		OPT__QUIET(&opts.quiet, N_("suppress progress reporting")),
		OPT_STRING('b', NULL, &opts.new_branch, N_("branch"),
			   N_("create and checkout a new branch")),
		OPT_STRING('B', NULL, &opts.new_branch_force, N_("branch"),
			   N_("create/reset and checkout a branch")),
1112
		OPT_BOOL('l', NULL, &opts.new_branch_log, N_("create reflog for new branch")),
V
Vasco Almeida 已提交
1113
		OPT_BOOL(0, "detach", &opts.force_detach, N_("detach HEAD at named commit")),
1114
		OPT_SET_INT('t', "track",  &opts.track, N_("set upstream info for new branch"),
1115
			BRANCH_TRACK_EXPLICIT),
1116
		OPT_STRING(0, "orphan", &opts.new_orphan_branch, N_("new-branch"), N_("new unparented branch")),
1117
		OPT_SET_INT('2', "ours", &opts.writeout_stage, N_("checkout our version for unmerged files"),
1118
			    2),
1119
		OPT_SET_INT('3', "theirs", &opts.writeout_stage, N_("checkout their version for unmerged files"),
1120
			    3),
1121
		OPT__FORCE(&opts.force, N_("force checkout (throw away local modifications)")),
1122 1123
		OPT_BOOL('m', "merge", &opts.merge, N_("perform a 3-way merge with the new branch")),
		OPT_BOOL(0, "overwrite-ignore", &opts.overwrite_ignore, N_("update ignored files (default)")),
1124 1125
		OPT_STRING(0, "conflict", &conflict_style, N_("style"),
			   N_("conflict style (merge or diff3)")),
1126
		OPT_BOOL('p', "patch", &opts.patch_mode, N_("select hunks interactively")),
1127 1128
		OPT_BOOL(0, "ignore-skip-worktree-bits", &opts.ignore_skipworktree,
			 N_("do not limit pathspecs to sparse entries only")),
1129
		OPT_HIDDEN_BOOL(0, "guess", &dwim_new_local_branch,
1130
				N_("second guess 'git checkout <no-such-branch>'")),
1131 1132
		OPT_BOOL(0, "ignore-other-worktrees", &opts.ignore_other_worktrees,
			 N_("do not check if another worktree is holding the given ref")),
1133
		{ OPTION_CALLBACK, 0, "recurse-submodules", NULL,
1134
			    "checkout", "control recursive updating of submodules",
1135
			    PARSE_OPT_OPTARG, option_parse_recurse_submodules_worktree_updater },
1136
		OPT_BOOL(0, "progress", &opts.show_progress, N_("force progress reporting")),
1137
		OPT_END(),
D
Daniel Barkalow 已提交
1138 1139 1140
	};

	memset(&opts, 0, sizeof(opts));
1141
	memset(&new_branch_info, 0, sizeof(new_branch_info));
1142
	opts.overwrite_ignore = 1;
1143
	opts.prefix = prefix;
1144
	opts.show_progress = -1;
D
Daniel Barkalow 已提交
1145

1146
	git_config(git_checkout_config, &opts);
D
Daniel Barkalow 已提交
1147

1148
	opts.track = BRANCH_TRACK_UNSPECIFIED;
D
Daniel Barkalow 已提交
1149

1150
	argc = parse_options(argc, argv, prefix, options, checkout_usage,
1151
			     PARSE_OPT_KEEP_DASHDASH);
1152

1153 1154 1155 1156 1157 1158 1159
	if (opts.show_progress < 0) {
		if (opts.quiet)
			opts.show_progress = 0;
		else
			opts.show_progress = isatty(2);
	}

1160 1161 1162 1163
	if (conflict_style) {
		opts.merge = 1; /* implied */
		git_xmerge_config("merge.conflictstyle", conflict_style, NULL);
	}
T
Tay Ray Chuan 已提交
1164

1165 1166
	if ((!!opts.new_branch + !!opts.new_branch_force + !!opts.new_orphan_branch) > 1)
		die(_("-b, -B and --orphan are mutually exclusive"));
T
Tay Ray Chuan 已提交
1167

1168 1169 1170 1171 1172
	/*
	 * From here on, new_branch will contain the branch to be checked out,
	 * and new_branch_force and new_orphan_branch will tell us which one of
	 * -b/-B/--orphan is being used.
	 */
T
Tay Ray Chuan 已提交
1173 1174 1175
	if (opts.new_branch_force)
		opts.new_branch = opts.new_branch_force;

1176 1177
	if (opts.new_orphan_branch)
		opts.new_branch = opts.new_orphan_branch;
1178

1179 1180
	/* --track without -b/-B/--orphan should DWIM */
	if (opts.track != BRANCH_TRACK_UNSPECIFIED && !opts.new_branch) {
1181 1182
		const char *argv0 = argv[0];
		if (!argc || !strcmp(argv0, "--"))
1183
			die (_("--track needs a branch name"));
1184 1185
		skip_prefix(argv0, "refs/", &argv0);
		skip_prefix(argv0, "remotes/", &argv0);
1186 1187
		argv0 = strchr(argv0, '/');
		if (!argv0 || !argv0[1])
1188
			die (_("Missing branch name; try -b"));
1189
		opts.new_branch = argv0 + 1;
1190 1191
	}

1192
	/*
1193 1194
	 * Extract branch name from command line arguments, so
	 * all that is left is pathspecs.
1195
	 *
1196
	 * Handle
1197
	 *
1198 1199 1200
	 *  1) git checkout <tree> -- [<paths>]
	 *  2) git checkout -- [<paths>]
	 *  3) git checkout <something> [<paths>]
1201
	 *
1202 1203
	 * including "last branch" syntax and DWIM-ery for names of
	 * remote branches, erroring out for invalid or ambiguous cases.
1204
	 */
D
Daniel Barkalow 已提交
1205
	if (argc) {
1206
		struct object_id rev;
1207
		int dwim_ok =
1208
			!opts.patch_mode &&
1209 1210 1211
			dwim_new_local_branch &&
			opts.track == BRANCH_TRACK_UNSPECIFIED &&
			!opts.new_branch;
1212
		int n = parse_branchname_arg(argc, argv, dwim_ok,
1213
					     &new_branch_info, &opts, &rev);
1214 1215
		argv += n;
		argc -= n;
D
Daniel Barkalow 已提交
1216 1217 1218
	}

	if (argc) {
1219 1220 1221
		parse_pathspec(&opts.pathspec, 0,
			       opts.patch_mode ? PATHSPEC_PREFIX_ORIGIN : 0,
			       prefix, argv);
1222

1223
		if (!opts.pathspec.nr)
1224
			die(_("invalid path specification"));
1225

1226 1227 1228 1229 1230
		/*
		 * Try to give more helpful suggestion.
		 * new_branch && argc > 1 will be caught later.
		 */
		if (opts.new_branch && argc == 1)
1231 1232
			die(_("'%s' is not a commit and a branch '%s' cannot be created from it"),
				argv[0], opts.new_branch);
D
Daniel Barkalow 已提交
1233

1234
		if (opts.force_detach)
1235 1236
			die(_("git checkout: --detach does not take a path argument '%s'"),
			    argv[0]);
1237

1238
		if (1 < !!opts.writeout_stage + !!opts.force + !!opts.merge)
1239 1240
			die(_("git checkout: --ours/--theirs, --force and --merge are incompatible when\n"
			      "checking out of the index."));
D
Daniel Barkalow 已提交
1241 1242
	}

1243
	if (opts.new_branch) {
1244
		struct strbuf buf = STRBUF_INIT;
1245

1246 1247 1248 1249 1250
		if (opts.new_branch_force)
			opts.branch_exists = validate_branchname(opts.new_branch, &buf);
		else
			opts.branch_exists =
				validate_new_branchname(opts.new_branch, &buf, 0);
1251 1252 1253
		strbuf_release(&buf);
	}

M
Martin Ågren 已提交
1254
	UNLEAK(opts);
1255
	if (opts.patch_mode || opts.pathspec.nr)
1256
		return checkout_paths(&opts, new_branch_info.name);
1257
	else
1258
		return checkout_branch(&opts, &new_branch_info);
D
Daniel Barkalow 已提交
1259
}