checkout.c 37.9 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
#include "parse-options.h"
#include "refs.h"
7
#include "object-store.h"
D
Daniel Barkalow 已提交
8 9 10
#include "commit.h"
#include "tree.h"
#include "tree-walk.h"
11
#include "cache-tree.h"
D
Daniel Barkalow 已提交
12 13 14 15 16 17 18
#include "unpack-trees.h"
#include "dir.h"
#include "run-command.h"
#include "merge-recursive.h"
#include "branch.h"
#include "diff.h"
#include "revision.h"
19
#include "remote.h"
20 21 22
#include "blob.h"
#include "xdiff-interface.h"
#include "ll-merge.h"
23
#include "resolve-undo.h"
24
#include "submodule-config.h"
25
#include "submodule.h"
26
#include "advice.h"
D
Daniel Barkalow 已提交
27 28

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

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

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

	int branch_exists;
	const char *prefix;
55
	struct pathspec pathspec;
56
	struct tree *source_tree;
57 58
};

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

D
Daniel Barkalow 已提交
69 70
}

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

	if (S_ISDIR(mode))
		return READ_TREE_RECURSIVE;

81
	len = base->len + strlen(pathname);
82
	ce = make_empty_cache_entry(&the_index, len);
83
	oidcpy(&ce->oid, oid);
84 85
	memcpy(ce->name, base->buf, base->len);
	memcpy(ce->name + base->len, pathname, len - base->len);
86 87
	ce->ce_flags = create_ce_flags(0) | CE_UPDATE;
	ce->ce_namelen = len;
D
Daniel Barkalow 已提交
88
	ce->ce_mode = create_ce_mode(mode);
89 90 91 92 93 94 95 96 97 98

	/*
	 * 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 &&
99
		    !oidcmp(&ce->oid, &old->oid)) {
100
			old->ce_flags |= CE_UPDATE;
101
			discard_cache_entry(ce);
102 103 104 105
			return 0;
		}
	}

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

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

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

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

129
static int check_stage(int stage, const struct cache_entry *ce, int pos)
130 131 132 133 134 135 136
{
	while (pos < active_nr &&
	       !strcmp(active_cache[pos]->name, ce->name)) {
		if (ce_stage(active_cache[pos]) == stage)
			return 0;
		pos++;
	}
137 138 139 140
	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);
141 142
}

143
static int check_stages(unsigned stages, const struct cache_entry *ce, int pos)
144
{
145 146 147 148 149 150 151 152 153 154 155 156 157
	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);
158 159 160
	return 0;
}

161 162
static int checkout_stage(int stage, const struct cache_entry *ce, int pos,
			  const struct checkout *state)
163 164 165 166 167 168 169
{
	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++;
	}
170 171 172 173
	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);
174
}
175

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

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

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

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

	/*
	 * NEEDSWORK:
	 * There is absolutely no reason to write this as a blob object
J
Johannes Schindelin 已提交
224 225 226 227 228 229 230 231
	 * 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).
232
	 */
233
	if (write_object_file(result_buf.ptr, result_buf.size, blob_type, &oid))
234
		die(_("Unable to add merge result for '%s'"), path);
J
Junio C Hamano 已提交
235
	free(result_buf.ptr);
236
	ce = make_transient_cache_entry(mode, &oid, path, 2);
237
	if (!ce)
238
		die(_("make_cache_entry failed for path '%s'"), path);
239
	status = checkout_entry(ce, state, NULL);
240
	discard_cache_entry(ce);
241 242
	return status;
}
243

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

	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",
279
					   &opts->pathspec);
280

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

285
	if (opts->source_tree)
286
		read_tree_some(opts->source_tree, &opts->pathspec);
287

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

290 291 292 293
	/*
	 * Make sure all pathspecs participated in locating the paths
	 * to be checked out.
	 */
D
Daniel Barkalow 已提交
294 295
	for (pos = 0; pos < active_nr; pos++) {
		struct cache_entry *ce = active_cache[pos];
296
		ce->ce_flags &= ~CE_MATCHED;
297 298
		if (!opts->ignore_skipworktree && ce_skip_worktree(ce))
			continue;
299
		if (opts->source_tree && !(ce->ce_flags & CE_UPDATE))
300 301 302 303 304 305 306
			/*
			 * "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.
			 */
307
			continue;
308 309 310 311 312 313 314 315 316 317 318 319 320 321
		/*
		 * 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.
		 */
322
		if (ce_path_match(&the_index, ce, &opts->pathspec, ps_matched))
323
			ce->ce_flags |= CE_MATCHED;
D
Daniel Barkalow 已提交
324 325
	}

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

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

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

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

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

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

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

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

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

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

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

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

D
Daniel Barkalow 已提交
425 426
	memset(&opts, 0, sizeof(opts));
	opts.head_idx = -1;
427 428
	opts.update = worktree;
	opts.skip_unmerged = !worktree;
D
Daniel Barkalow 已提交
429 430 431
	opts.reset = 1;
	opts.merge = 1;
	opts.fn = oneway_merge;
432
	opts.verbose_update = o->show_progress;
433 434
	opts.src_index = &the_index;
	opts.dst_index = &the_index;
D
Daniel Barkalow 已提交
435 436
	parse_tree(tree);
	init_tree_desc(&tree_desc, tree->buffer, tree->size);
437 438
	switch (unpack_trees(1, &tree_desc, &opts)) {
	case -2:
439
		*writeout_error = 1;
440 441 442 443 444 445
		/*
		 * 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.
		 */
446
		/* fallthrough */
447 448 449
	case 0:
		return 0;
	default:
450
		return 128;
451
	}
D
Daniel Barkalow 已提交
452 453 454 455 456 457
}

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 */
458 459 460 461 462
	/*
	 * if not null the branch is detached because it's already
	 * checked out in this checkout
	 */
	char *checkout;
D
Daniel Barkalow 已提交
463 464 465 466
};

static void setup_branch_path(struct branch_info *branch)
{
467
	struct strbuf buf = STRBUF_INIT;
468

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

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

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

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

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

504
		setup_unpack_trees_porcelain(&topts, "checkout");
505

D
Daniel Barkalow 已提交
506 507 508
		refresh_cache(REFRESH_QUIET);

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

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

532
		ret = unpack_trees(2, trees, &topts);
533
		clear_unpack_trees_porcelain(&topts);
534
		if (ret == -1) {
D
Daniel Barkalow 已提交
535 536 537 538 539 540 541
			/*
			 * 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;
542
			struct merge_options o;
D
Daniel Barkalow 已提交
543 544
			if (!opts->merge)
				return 1;
545 546

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

			/* 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.
			 */

566
			add_files_to_cache(NULL, NULL, 0);
J
Jonathan Nieder 已提交
567 568 569 570 571 572 573
			/*
			 * 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?
			 */
574 575 576
			init_merge_options(&o);
			o.verbosity = 0;
			work = write_tree_from_memory(&o);
D
Daniel Barkalow 已提交
577

578 579
			ret = reset_tree(get_commit_tree(new_branch_info->commit),
					 opts, 1,
580
					 writeout_error);
D
Daniel Barkalow 已提交
581 582
			if (ret)
				return ret;
583 584
			o.ancestor = old_branch_info->name;
			o.branch1 = new_branch_info->name;
585
			o.branch2 = "local";
586 587 588 589 590
			ret = merge_trees(&o,
					  get_commit_tree(new_branch_info->commit),
					  work,
					  get_commit_tree(old_branch_info->commit),
					  &result);
591 592
			if (ret < 0)
				exit(128);
593 594
			ret = reset_tree(get_commit_tree(new_branch_info->commit),
					 opts, 0,
595
					 writeout_error);
596
			strbuf_release(&o.obuf);
597 598
			if (ret)
				return ret;
D
Daniel Barkalow 已提交
599 600 601
		}
	}

602 603 604 605
	if (!active_cache_tree)
		active_cache_tree = cache_tree();

	if (!cache_tree_fully_valid(active_cache_tree))
606
		cache_tree_update(&the_index, WRITE_TREE_SILENT | WRITE_TREE_REPAIR);
607

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

611
	if (!opts->force && !opts->quiet)
612
		show_local_changes(&new_branch_info->commit->object, &opts->diff_options);
D
Daniel Barkalow 已提交
613 614 615 616

	return 0;
}

617
static void report_tracking(struct branch_info *new_branch_info)
618
{
619
	struct strbuf sb = STRBUF_INIT;
620
	struct branch *branch = branch_get(new_branch_info->name);
621

622
	if (!format_tracking_info(branch, &sb, AHEAD_BEHIND_FULL))
623
		return;
624 625
	fputs(sb.buf, stdout);
	strbuf_release(&sb);
626
}
627

628
static void update_refs_for_switch(const struct checkout_opts *opts,
629 630
				   struct branch_info *old_branch_info,
				   struct branch_info *new_branch_info)
D
Daniel Barkalow 已提交
631
{
632
	struct strbuf msg = STRBUF_INIT;
633
	const char *old_desc, *reflog_msg;
D
Daniel Barkalow 已提交
634
	if (opts->new_branch) {
635
		if (opts->new_orphan_branch) {
636 637 638 639 640
			char *refname;

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

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

667 668 669
	old_desc = old_branch_info->name;
	if (!old_desc && old_branch_info->commit)
		old_desc = oid_to_hex(&old_branch_info->commit->object.oid);
670 671 672 673

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

678
	if (!strcmp(new_branch_info->name, "HEAD") && !new_branch_info->path && !opts->force_detach) {
679
		/* Nothing to do. */
680 681
	} 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,
682
			   REF_NO_DEREF, UPDATE_REFS_DIE_ON_ERR);
683
		if (!opts->quiet) {
684
			if (old_branch_info->path &&
685
			    advice_detached_head && !opts->force_detach)
686 687
				detach_advice(new_branch_info->name);
			describe_detached_head(_("HEAD is now at"), new_branch_info->commit);
688
		}
689 690
	} else if (new_branch_info->path) {	/* Switch branches. */
		if (create_symref("HEAD", new_branch_info->path, msg.buf) < 0)
691
			die(_("unable to update HEAD"));
D
Daniel Barkalow 已提交
692
		if (!opts->quiet) {
693
			if (old_branch_info->path && !strcmp(new_branch_info->path, old_branch_info->path)) {
694 695
				if (opts->new_branch_force)
					fprintf(stderr, _("Reset branch '%s'\n"),
696
						new_branch_info->name);
697 698
				else
					fprintf(stderr, _("Already on '%s'\n"),
699
						new_branch_info->name);
700 701
			} else if (opts->new_branch) {
				if (opts->branch_exists)
702
					fprintf(stderr, _("Switched to and reset branch '%s'\n"), new_branch_info->name);
703
				else
704
					fprintf(stderr, _("Switched to a new branch '%s'\n"), new_branch_info->name);
705
			} else {
706
				fprintf(stderr, _("Switched to branch '%s'\n"),
707
					new_branch_info->name);
708
			}
D
Daniel Barkalow 已提交
709
		}
710 711 712
		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);
713
		}
D
Daniel Barkalow 已提交
714 715 716
	}
	remove_branch_state();
	strbuf_release(&msg);
717
	if (!opts->quiet &&
718 719
	    (new_branch_info->path || (!opts->force_detach && !strcmp(new_branch_info->name, "HEAD"))))
		report_tracking(new_branch_info);
D
Daniel Barkalow 已提交
720 721
}

722
static int add_pending_uninteresting_ref(const char *refname,
723
					 const struct object_id *oid,
724
					 int flags, void *cb_data)
725
{
726
	add_pending_oid(cb_data, refname, oid, UNINTERESTING);
727 728
	return 0;
}
729 730 731

static void describe_one_orphan(struct strbuf *sb, struct commit *commit)
{
732
	strbuf_addstr(sb, "  ");
733
	strbuf_add_unique_abbrev(sb, &commit->object.oid, DEFAULT_ABBREV);
734
	strbuf_addch(sb, ' ');
735 736
	if (!parse_commit(commit))
		pp_commit_easy(CMIT_FMT_ONELINE, commit, sb);
737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756
	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
757
			strbuf_addf(&sb, _(" ... and %d more.\n"), more);
758 759 760
	}

	fprintf(stderr,
761 762 763 764 765
		Q_(
		/* The singular version */
		"Warning: you are leaving %d commit behind, "
		"not connected to\n"
		"any of your branches:\n\n"
766
		"%s\n",
767 768
		/* The plural version */
		"Warning: you are leaving %d commits behind, "
769 770
		"not connected to\n"
		"any of your branches:\n\n"
771
		"%s\n",
772 773 774
		/* Give ngettext() the count */
		lost),
		lost,
775
		sb.buf);
776
	strbuf_release(&sb);
777 778 779

	if (advice_detached_head)
		fprintf(stderr,
780 781 782 783 784 785
			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 */
786 787
			"If you want to keep them by creating a new branch, "
			"this may be a good time\nto do so with:\n\n"
788 789 790
			" git branch <new-branch-name> %s\n\n",
			/* Give ngettext() the count */
			lost),
791
			find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV));
792 793 794 795 796 797 798
}

/*
 * 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.
 */
799
static void orphaned_commit_warning(struct commit *old_commit, struct commit *new_commit)
800 801
{
	struct rev_info revs;
802
	struct object *object = &old_commit->object;
803

804
	repo_init_revisions(the_repository, &revs, NULL);
805 806 807
	setup_revisions(0, NULL, &revs, NULL);

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

810
	for_each_ref(add_pending_uninteresting_ref, &revs);
811
	add_pending_oid(&revs, "HEAD", &new_commit->object.oid, UNINTERESTING);
812

813
	if (prepare_revision_walk(&revs))
J
Junio C Hamano 已提交
814
		die(_("internal error in revision walk"));
815 816
	if (!(old_commit->object.flags & UNINTERESTING))
		suggest_reattach(old_commit, &revs);
817
	else
818
		describe_detached_head(_("Previous HEAD position was"), old_commit);
819

820
	/* Clean up objects used, as they will be reused. */
821
	clear_commit_marks_all(ALL_REV_FLAGS);
822 823
}

824
static int switch_branches(const struct checkout_opts *opts,
825
			   struct branch_info *new_branch_info)
D
Daniel Barkalow 已提交
826 827
{
	int ret = 0;
828
	struct branch_info old_branch_info;
829
	void *path_to_free;
830
	struct object_id rev;
831
	int flag, writeout_error = 0;
832 833 834
	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)
835
		old_branch_info.commit = lookup_commit_reference_gently(the_repository, &rev, 1);
836
	if (!(flag & REF_ISSYMREF))
837
		old_branch_info.path = NULL;
D
Daniel Barkalow 已提交
838

839 840
	if (old_branch_info.path)
		skip_prefix(old_branch_info.path, "refs/heads/", &old_branch_info.name);
D
Daniel Barkalow 已提交
841

842 843 844 845
	if (!new_branch_info->name) {
		new_branch_info->name = "HEAD";
		new_branch_info->commit = old_branch_info.commit;
		if (!new_branch_info->commit)
846
			die(_("You are on a branch yet to be born"));
847
		parse_commit_or_die(new_branch_info->commit);
D
Daniel Barkalow 已提交
848 849
	}

850
	ret = merge_working_tree(opts, &old_branch_info, new_branch_info, &writeout_error);
851 852
	if (ret) {
		free(path_to_free);
D
Daniel Barkalow 已提交
853
		return ret;
854
	}
D
Daniel Barkalow 已提交
855

856 857
	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);
858

859
	update_refs_for_switch(opts, &old_branch_info, new_branch_info);
D
Daniel Barkalow 已提交
860

861
	ret = post_checkout_hook(old_branch_info.commit, new_branch_info->commit, 1);
862
	free(path_to_free);
863
	return ret || writeout_error;
D
Daniel Barkalow 已提交
864 865
}

866 867
static int git_checkout_config(const char *var, const char *value, void *cb)
{
868 869 870 871 872
	if (!strcmp(var, "diff.ignoresubmodules")) {
		struct checkout_opts *opts = cb;
		handle_ignore_submodules_arg(&opts->diff_options, value);
		return 0;
	}
873

874
	if (starts_with(var, "submodule."))
875
		return git_default_submodule_config(var, value, NULL);
876

877
	return git_xmerge_config(var, value, NULL);
878 879
}

880 881
static int parse_branchname_arg(int argc, const char **argv,
				int dwim_new_local_branch_ok,
882
				struct branch_info *new_branch_info,
883
				struct checkout_opts *opts,
884 885
				struct object_id *rev,
				int *dwim_remotes_matched)
886
{
887 888
	struct tree **source_tree = &opts->source_tree;
	const char **new_branch = &opts->new_branch;
889
	int argcount = 0;
890
	struct object_id branch_rev;
891
	const char *arg;
892 893 894
	int dash_dash_pos;
	int has_dash_dash = 0;
	int i;
895 896 897 898 899 900 901 902 903 904 905

	/*
	 * 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.
	 *
906
	 * case 3: git checkout <something> [--]
907
	 *
908 909 910 911 912
	 *   (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.
913
	 *
914
	 *   (b) If <something> is _not_ a commit, either "--" is present
J
Justin Lebar 已提交
915
	 *       or <something> is not a path, no -t or -b was given, and
916
	 *       and there is a tracking branch whose name is <something>
917 918 919 920
	 *       in one and only one remote (or if the branch exists on the
	 *       remote named in checkout.defaultRemote), then this is a
	 *       short-hand to fork local <something> from that
	 *       remote-tracking branch.
921
	 *
922 923 924 925 926 927 928 929 930 931
	 *   (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.
932 933 934 935 936 937 938 939 940
	 *   - 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];
941 942 943 944 945 946 947 948 949 950 951 952 953
	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);
954 955 956 957

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

958
	if (get_oid_mb(arg, rev)) {
959 960 961 962 963 964 965 966 967 968
		/*
		 * 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;

969
		if (!has_dash_dash &&
970
		    (check_filename(opts->prefix, arg) || !no_wildcard(arg)))
971 972 973 974 975 976 977 978 979 980
			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) {
981 982
			const char *remote = unique_tracking_name(arg, rev,
								  dwim_remotes_matched);
983 984 985 986 987 988 989 990 991 992 993 994
			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);
995 996 997 998 999 1000 1001 1002 1003
			return argcount;
		}
	}

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

1004 1005
	new_branch_info->name = arg;
	setup_branch_path(new_branch_info);
1006

1007 1008
	if (!check_refname_format(new_branch_info->path, 0) &&
	    !read_ref(new_branch_info->path, &branch_rev))
1009
		oidcpy(rev, &branch_rev);
1010
	else
1011
		new_branch_info->path = NULL; /* not an existing branch */
1012

1013
	new_branch_info->commit = lookup_commit_reference_gently(the_repository, rev, 1);
1014
	if (!new_branch_info->commit) {
1015
		/* not a commit */
1016
		*source_tree = parse_tree_indirect(rev);
1017
	} else {
1018
		parse_commit_or_die(new_branch_info->commit);
1019
		*source_tree = get_commit_tree(new_branch_info->commit);
1020 1021 1022
	}

	if (!*source_tree)                   /* case (1): want a tree */
J
Junio C Hamano 已提交
1023
		die(_("reference is not a tree: %s"), arg);
1024
	if (!has_dash_dash) {	/* case (3).(d) -> (1) */
1025 1026 1027 1028 1029 1030 1031
		/*
		 * 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)
1032
			verify_non_filename(opts->prefix, arg);
1033 1034 1035 1036 1037 1038 1039 1040 1041
	} else {
		argcount++;
		argv++;
		argc--;
	}

	return argcount;
}

1042
static int switch_unborn_to_new_branch(const struct checkout_opts *opts)
1043 1044 1045 1046
{
	int status;
	struct strbuf branch_ref = STRBUF_INIT;

1047 1048
	if (!opts->new_branch)
		die(_("You are on a branch yet to be born"));
1049 1050 1051
	strbuf_addf(&branch_ref, "refs/heads/%s", opts->new_branch);
	status = create_symref("HEAD", branch_ref.buf, "checkout -b");
	strbuf_release(&branch_ref);
1052 1053 1054
	if (!opts->quiet)
		fprintf(stderr, _("Switched to a new branch '%s'\n"),
			opts->new_branch);
1055 1056 1057
	return status;
}

1058
static int checkout_branch(struct checkout_opts *opts,
1059
			   struct branch_info *new_branch_info)
1060
{
1061
	if (opts->pathspec.nr)
1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087
		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;

1088
	if (new_branch_info->name && !new_branch_info->commit)
1089
		die(_("Cannot switch branch to a non-commit '%s'"),
1090
		    new_branch_info->name);
1091

1092
	if (new_branch_info->path && !opts->force_detach && !opts->new_branch &&
1093
	    !opts->ignore_other_worktrees) {
1094
		int flag;
1095
		char *head_ref = resolve_refdup("HEAD", 0, NULL, &flag);
1096
		if (head_ref &&
1097 1098
		    (!(flag & REF_ISSYMREF) || strcmp(head_ref, new_branch_info->path)))
			die_if_checked_out(new_branch_info->path, 1);
1099 1100 1101
		free(head_ref);
	}

1102
	if (!new_branch_info->commit && opts->new_branch) {
1103
		struct object_id rev;
1104 1105
		int flag;

1106
		if (!read_ref_full("HEAD", 0, &rev, &flag) &&
1107
		    (flag & REF_ISSYMREF) && is_null_oid(&rev))
1108 1109
			return switch_unborn_to_new_branch(opts);
	}
1110
	return switch_branches(opts, new_branch_info);
1111 1112
}

D
Daniel Barkalow 已提交
1113 1114 1115
int cmd_checkout(int argc, const char **argv, const char *prefix)
{
	struct checkout_opts opts;
1116
	struct branch_info new_branch_info;
1117
	char *conflict_style = NULL;
J
Junio C Hamano 已提交
1118
	int dwim_new_local_branch = 1;
1119
	int dwim_remotes_matched = 0;
D
Daniel Barkalow 已提交
1120
	struct option options[] = {
1121 1122 1123 1124 1125
		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")),
1126
		OPT_BOOL('l', NULL, &opts.new_branch_log, N_("create reflog for new branch")),
V
Vasco Almeida 已提交
1127
		OPT_BOOL(0, "detach", &opts.force_detach, N_("detach HEAD at named commit")),
1128
		OPT_SET_INT('t', "track",  &opts.track, N_("set upstream info for new branch"),
1129
			BRANCH_TRACK_EXPLICIT),
1130
		OPT_STRING(0, "orphan", &opts.new_orphan_branch, N_("new-branch"), N_("new unparented branch")),
1131 1132 1133 1134 1135 1136
		OPT_SET_INT_F('2', "ours", &opts.writeout_stage,
			      N_("checkout our version for unmerged files"),
			      2, PARSE_OPT_NONEG),
		OPT_SET_INT_F('3', "theirs", &opts.writeout_stage,
			      N_("checkout their version for unmerged files"),
			      3, PARSE_OPT_NONEG),
1137 1138
		OPT__FORCE(&opts.force, N_("force checkout (throw away local modifications)"),
			   PARSE_OPT_NOCOMPLETE),
1139
		OPT_BOOL('m', "merge", &opts.merge, N_("perform a 3-way merge with the new branch")),
1140 1141 1142
		OPT_BOOL_F(0, "overwrite-ignore", &opts.overwrite_ignore,
			   N_("update ignored files (default)"),
			   PARSE_OPT_NOCOMPLETE),
1143 1144
		OPT_STRING(0, "conflict", &conflict_style, N_("style"),
			   N_("conflict style (merge or diff3)")),
1145
		OPT_BOOL('p', "patch", &opts.patch_mode, N_("select hunks interactively")),
1146 1147
		OPT_BOOL(0, "ignore-skip-worktree-bits", &opts.ignore_skipworktree,
			 N_("do not limit pathspecs to sparse entries only")),
1148
		OPT_HIDDEN_BOOL(0, "guess", &dwim_new_local_branch,
1149
				N_("second guess 'git checkout <no-such-branch>'")),
1150 1151
		OPT_BOOL(0, "ignore-other-worktrees", &opts.ignore_other_worktrees,
			 N_("do not check if another worktree is holding the given ref")),
1152
		{ OPTION_CALLBACK, 0, "recurse-submodules", NULL,
1153
			    "checkout", "control recursive updating of submodules",
1154
			    PARSE_OPT_OPTARG, option_parse_recurse_submodules_worktree_updater },
1155
		OPT_BOOL(0, "progress", &opts.show_progress, N_("force progress reporting")),
1156
		OPT_END(),
D
Daniel Barkalow 已提交
1157 1158 1159
	};

	memset(&opts, 0, sizeof(opts));
1160
	memset(&new_branch_info, 0, sizeof(new_branch_info));
1161
	opts.overwrite_ignore = 1;
1162
	opts.prefix = prefix;
1163
	opts.show_progress = -1;
D
Daniel Barkalow 已提交
1164

1165
	git_config(git_checkout_config, &opts);
D
Daniel Barkalow 已提交
1166

1167
	opts.track = BRANCH_TRACK_UNSPECIFIED;
D
Daniel Barkalow 已提交
1168

1169
	argc = parse_options(argc, argv, prefix, options, checkout_usage,
1170
			     PARSE_OPT_KEEP_DASHDASH);
1171

1172 1173 1174 1175 1176 1177 1178
	if (opts.show_progress < 0) {
		if (opts.quiet)
			opts.show_progress = 0;
		else
			opts.show_progress = isatty(2);
	}

1179 1180 1181 1182
	if (conflict_style) {
		opts.merge = 1; /* implied */
		git_xmerge_config("merge.conflictstyle", conflict_style, NULL);
	}
T
Tay Ray Chuan 已提交
1183

1184 1185
	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 已提交
1186

1187 1188 1189 1190 1191
	/*
	 * 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 已提交
1192 1193 1194
	if (opts.new_branch_force)
		opts.new_branch = opts.new_branch_force;

1195 1196
	if (opts.new_orphan_branch)
		opts.new_branch = opts.new_orphan_branch;
1197

1198 1199
	/* --track without -b/-B/--orphan should DWIM */
	if (opts.track != BRANCH_TRACK_UNSPECIFIED && !opts.new_branch) {
1200 1201
		const char *argv0 = argv[0];
		if (!argc || !strcmp(argv0, "--"))
1202
			die(_("--track needs a branch name"));
1203 1204
		skip_prefix(argv0, "refs/", &argv0);
		skip_prefix(argv0, "remotes/", &argv0);
1205 1206
		argv0 = strchr(argv0, '/');
		if (!argv0 || !argv0[1])
1207
			die(_("missing branch name; try -b"));
1208
		opts.new_branch = argv0 + 1;
1209 1210
	}

1211
	/*
1212 1213
	 * Extract branch name from command line arguments, so
	 * all that is left is pathspecs.
1214
	 *
1215
	 * Handle
1216
	 *
1217 1218 1219
	 *  1) git checkout <tree> -- [<paths>]
	 *  2) git checkout -- [<paths>]
	 *  3) git checkout <something> [<paths>]
1220
	 *
1221 1222
	 * including "last branch" syntax and DWIM-ery for names of
	 * remote branches, erroring out for invalid or ambiguous cases.
1223
	 */
D
Daniel Barkalow 已提交
1224
	if (argc) {
1225
		struct object_id rev;
1226
		int dwim_ok =
1227
			!opts.patch_mode &&
1228 1229 1230
			dwim_new_local_branch &&
			opts.track == BRANCH_TRACK_UNSPECIFIED &&
			!opts.new_branch;
1231
		int n = parse_branchname_arg(argc, argv, dwim_ok,
1232 1233
					     &new_branch_info, &opts, &rev,
					     &dwim_remotes_matched);
1234 1235
		argv += n;
		argc -= n;
D
Daniel Barkalow 已提交
1236 1237 1238
	}

	if (argc) {
1239 1240 1241
		parse_pathspec(&opts.pathspec, 0,
			       opts.patch_mode ? PATHSPEC_PREFIX_ORIGIN : 0,
			       prefix, argv);
1242

1243
		if (!opts.pathspec.nr)
1244
			die(_("invalid path specification"));
1245

1246 1247 1248 1249 1250
		/*
		 * Try to give more helpful suggestion.
		 * new_branch && argc > 1 will be caught later.
		 */
		if (opts.new_branch && argc == 1)
1251 1252
			die(_("'%s' is not a commit and a branch '%s' cannot be created from it"),
				argv[0], opts.new_branch);
D
Daniel Barkalow 已提交
1253

1254
		if (opts.force_detach)
1255 1256
			die(_("git checkout: --detach does not take a path argument '%s'"),
			    argv[0]);
1257

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

1263
	if (opts.new_branch) {
1264
		struct strbuf buf = STRBUF_INIT;
1265

1266 1267 1268 1269 1270
		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);
1271 1272 1273
		strbuf_release(&buf);
	}

M
Martin Ågren 已提交
1274
	UNLEAK(opts);
1275 1276
	if (opts.patch_mode || opts.pathspec.nr) {
		int ret = checkout_paths(&opts, new_branch_info.name);
1277 1278 1279 1280 1281 1282 1283 1284 1285
		if (ret && dwim_remotes_matched > 1 &&
		    advice_checkout_ambiguous_remote_branch_name)
			advise(_("'%s' matched more than one remote tracking branch.\n"
				 "We found %d remotes with a reference that matched. So we fell back\n"
				 "on trying to resolve the argument as a path, but failed there too!\n"
				 "\n"
				 "If you meant to check out a remote tracking branch on, e.g. 'origin',\n"
				 "you can do so by fully qualifying the name with the --track option:\n"
				 "\n"
1286 1287 1288 1289 1290
				 "    git checkout --track origin/<name>\n"
				 "\n"
				 "If you'd like to always have checkouts of an ambiguous <name> prefer\n"
				 "one remote, e.g. the 'origin' remote, consider setting\n"
				 "checkout.defaultRemote=origin in your config."),
1291 1292
			       argv[0],
			       dwim_remotes_matched);
1293 1294
		return ret;
	} else {
1295
		return checkout_branch(&opts, &new_branch_info);
1296
	}
D
Daniel Barkalow 已提交
1297
}