pull.c 25.3 KB
Newer Older
P
Paul Tan 已提交
1 2 3 4 5 6 7 8 9 10 11
/*
 * Builtin "git pull"
 *
 * Based on git-pull.sh by Junio C Hamano
 *
 * Fetch one or more remote refs and merge it/them into the current HEAD.
 */
#include "cache.h"
#include "builtin.h"
#include "parse-options.h"
#include "exec_cmd.h"
P
Paul Tan 已提交
12
#include "run-command.h"
P
Paul Tan 已提交
13 14
#include "sha1-array.h"
#include "remote.h"
15
#include "dir.h"
16
#include "refs.h"
17
#include "revision.h"
J
Junio C Hamano 已提交
18
#include "tempfile.h"
19
#include "lockfile.h"
20
#include "wt-status.h"
P
Paul Tan 已提交
21

P
Paul Tan 已提交
22 23 24 25
enum rebase_type {
	REBASE_INVALID = -1,
	REBASE_FALSE = 0,
	REBASE_TRUE,
26 27
	REBASE_PRESERVE,
	REBASE_INTERACTIVE
P
Paul Tan 已提交
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
};

/**
 * Parses the value of --rebase. If value is a false value, returns
 * REBASE_FALSE. If value is a true value, returns REBASE_TRUE. If value is
 * "preserve", returns REBASE_PRESERVE. If value is a invalid value, dies with
 * a fatal error if fatal is true, otherwise returns REBASE_INVALID.
 */
static enum rebase_type parse_config_rebase(const char *key, const char *value,
		int fatal)
{
	int v = git_config_maybe_bool("pull.rebase", value);

	if (!v)
		return REBASE_FALSE;
	else if (v > 0)
		return REBASE_TRUE;
	else if (!strcmp(value, "preserve"))
		return REBASE_PRESERVE;
47 48
	else if (!strcmp(value, "interactive"))
		return REBASE_INTERACTIVE;
P
Paul Tan 已提交
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71

	if (fatal)
		die(_("Invalid value for %s: %s"), key, value);
	else
		error(_("Invalid value for %s: %s"), key, value);

	return REBASE_INVALID;
}

/**
 * Callback for --rebase, which parses arg with parse_config_rebase().
 */
static int parse_opt_rebase(const struct option *opt, const char *arg, int unset)
{
	enum rebase_type *value = opt->value;

	if (arg)
		*value = parse_config_rebase("--rebase", arg, 0);
	else
		*value = unset ? REBASE_FALSE : REBASE_TRUE;
	return *value == REBASE_INVALID ? -1 : 0;
}

P
Paul Tan 已提交
72
static const char * const pull_usage[] = {
73
	N_("git pull [<options>] [<repository> [<refspec>...]]"),
P
Paul Tan 已提交
74 75 76
	NULL
};

77 78 79 80
/* Shared options */
static int opt_verbosity;
static char *opt_progress;

P
Paul Tan 已提交
81
/* Options passed to git-merge or git-rebase */
82
static enum rebase_type opt_rebase = -1;
83 84 85 86 87 88 89
static char *opt_diffstat;
static char *opt_log;
static char *opt_squash;
static char *opt_commit;
static char *opt_edit;
static char *opt_ff;
static char *opt_verify_signatures;
90
static int opt_autostash = -1;
91
static int config_autostash;
92 93 94
static struct argv_array opt_strategies = ARGV_ARRAY_INIT;
static struct argv_array opt_strategy_opts = ARGV_ARRAY_INIT;
static char *opt_gpg_sign;
95
static int opt_allow_unrelated_histories;
96

97 98 99 100 101 102 103 104
/* Options passed to git-fetch */
static char *opt_all;
static char *opt_append;
static char *opt_upload_pack;
static int opt_force;
static char *opt_tags;
static char *opt_prune;
static char *opt_recurse_submodules;
105
static char *max_children;
106 107 108 109 110 111 112
static int opt_dry_run;
static char *opt_keep;
static char *opt_depth;
static char *opt_unshallow;
static char *opt_update_shallow;
static char *opt_refmap;

P
Paul Tan 已提交
113
static struct option pull_options[] = {
114 115 116 117 118 119
	/* Shared options */
	OPT__VERBOSITY(&opt_verbosity),
	OPT_PASSTHRU(0, "progress", &opt_progress, NULL,
		N_("force progress reporting"),
		PARSE_OPT_NOARG),

P
Paul Tan 已提交
120
	/* Options passed to git-merge or git-rebase */
121
	OPT_GROUP(N_("Options related to merging")),
P
Paul Tan 已提交
122
	{ OPTION_CALLBACK, 'r', "rebase", &opt_rebase,
123
	  "false|true|preserve|interactive",
P
Paul Tan 已提交
124 125
	  N_("incorporate changes by rebasing rather than merging"),
	  PARSE_OPT_OPTARG, parse_opt_rebase },
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155
	OPT_PASSTHRU('n', NULL, &opt_diffstat, NULL,
		N_("do not show a diffstat at the end of the merge"),
		PARSE_OPT_NOARG | PARSE_OPT_NONEG),
	OPT_PASSTHRU(0, "stat", &opt_diffstat, NULL,
		N_("show a diffstat at the end of the merge"),
		PARSE_OPT_NOARG),
	OPT_PASSTHRU(0, "summary", &opt_diffstat, NULL,
		N_("(synonym to --stat)"),
		PARSE_OPT_NOARG | PARSE_OPT_HIDDEN),
	OPT_PASSTHRU(0, "log", &opt_log, N_("n"),
		N_("add (at most <n>) entries from shortlog to merge commit message"),
		PARSE_OPT_OPTARG),
	OPT_PASSTHRU(0, "squash", &opt_squash, NULL,
		N_("create a single commit instead of doing a merge"),
		PARSE_OPT_NOARG),
	OPT_PASSTHRU(0, "commit", &opt_commit, NULL,
		N_("perform a commit if the merge succeeds (default)"),
		PARSE_OPT_NOARG),
	OPT_PASSTHRU(0, "edit", &opt_edit, NULL,
		N_("edit message before committing"),
		PARSE_OPT_NOARG),
	OPT_PASSTHRU(0, "ff", &opt_ff, NULL,
		N_("allow fast-forward"),
		PARSE_OPT_NOARG),
	OPT_PASSTHRU(0, "ff-only", &opt_ff, NULL,
		N_("abort if fast-forward is not possible"),
		PARSE_OPT_NOARG | PARSE_OPT_NONEG),
	OPT_PASSTHRU(0, "verify-signatures", &opt_verify_signatures, NULL,
		N_("verify that the named commit has a valid GPG signature"),
		PARSE_OPT_NOARG),
156 157
	OPT_BOOL(0, "autostash", &opt_autostash,
		N_("automatically stash/stash pop before and after rebase")),
158 159 160 161 162 163 164 165 166 167
	OPT_PASSTHRU_ARGV('s', "strategy", &opt_strategies, N_("strategy"),
		N_("merge strategy to use"),
		0),
	OPT_PASSTHRU_ARGV('X', "strategy-option", &opt_strategy_opts,
		N_("option=value"),
		N_("option for selected merge strategy"),
		0),
	OPT_PASSTHRU('S', "gpg-sign", &opt_gpg_sign, N_("key-id"),
		N_("GPG sign commit"),
		PARSE_OPT_OPTARG),
168 169 170
	OPT_SET_INT(0, "allow-unrelated-histories",
		    &opt_allow_unrelated_histories,
		    N_("allow merging unrelated histories"), 1),
171

172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193
	/* Options passed to git-fetch */
	OPT_GROUP(N_("Options related to fetching")),
	OPT_PASSTHRU(0, "all", &opt_all, NULL,
		N_("fetch from all remotes"),
		PARSE_OPT_NOARG),
	OPT_PASSTHRU('a', "append", &opt_append, NULL,
		N_("append to .git/FETCH_HEAD instead of overwriting"),
		PARSE_OPT_NOARG),
	OPT_PASSTHRU(0, "upload-pack", &opt_upload_pack, N_("path"),
		N_("path to upload pack on remote end"),
		0),
	OPT__FORCE(&opt_force, N_("force overwrite of local branch")),
	OPT_PASSTHRU('t', "tags", &opt_tags, NULL,
		N_("fetch all tags and associated objects"),
		PARSE_OPT_NOARG),
	OPT_PASSTHRU('p', "prune", &opt_prune, NULL,
		N_("prune remote-tracking branches no longer on remote"),
		PARSE_OPT_NOARG),
	OPT_PASSTHRU(0, "recurse-submodules", &opt_recurse_submodules,
		N_("on-demand"),
		N_("control recursive fetching of submodules"),
		PARSE_OPT_OPTARG),
194 195 196
	OPT_PASSTHRU('j', "jobs", &max_children, N_("n"),
		N_("number of submodules pulled in parallel"),
		PARSE_OPT_OPTARG),
197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214
	OPT_BOOL(0, "dry-run", &opt_dry_run,
		N_("dry run")),
	OPT_PASSTHRU('k', "keep", &opt_keep, NULL,
		N_("keep downloaded pack"),
		PARSE_OPT_NOARG),
	OPT_PASSTHRU(0, "depth", &opt_depth, N_("depth"),
		N_("deepen history of shallow clone"),
		0),
	OPT_PASSTHRU(0, "unshallow", &opt_unshallow, NULL,
		N_("convert to a complete repository"),
		PARSE_OPT_NONEG | PARSE_OPT_NOARG),
	OPT_PASSTHRU(0, "update-shallow", &opt_update_shallow, NULL,
		N_("accept refs that update .git/shallow"),
		PARSE_OPT_NOARG),
	OPT_PASSTHRU(0, "refmap", &opt_refmap, N_("refmap"),
		N_("specify fetch refmap"),
		PARSE_OPT_NONEG),

P
Paul Tan 已提交
215 216 217
	OPT_END()
};

218 219 220 221 222 223 224 225 226 227 228 229 230 231
/**
 * Pushes "-q" or "-v" switches into arr to match the opt_verbosity level.
 */
static void argv_push_verbosity(struct argv_array *arr)
{
	int verbosity;

	for (verbosity = opt_verbosity; verbosity > 0; verbosity--)
		argv_array_push(arr, "-v");

	for (verbosity = opt_verbosity; verbosity < 0; verbosity++)
		argv_array_push(arr, "-q");
}

232 233 234 235 236 237 238 239 240 241
/**
 * Pushes "-f" switches into arr to match the opt_force level.
 */
static void argv_push_force(struct argv_array *arr)
{
	int force = opt_force;
	while (force-- > 0)
		argv_array_push(arr, "-f");
}

P
Paul Tan 已提交
242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260
/**
 * Sets the GIT_REFLOG_ACTION environment variable to the concatenation of argv
 */
static void set_reflog_message(int argc, const char **argv)
{
	int i;
	struct strbuf msg = STRBUF_INIT;

	for (i = 0; i < argc; i++) {
		if (i)
			strbuf_addch(&msg, ' ');
		strbuf_addstr(&msg, argv[i]);
	}

	setenv("GIT_REFLOG_ACTION", msg.buf, 0);

	strbuf_release(&msg);
}

P
Paul Tan 已提交
261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286
/**
 * If pull.ff is unset, returns NULL. If pull.ff is "true", returns "--ff". If
 * pull.ff is "false", returns "--no-ff". If pull.ff is "only", returns
 * "--ff-only". Otherwise, if pull.ff is set to an invalid value, die with an
 * error.
 */
static const char *config_get_ff(void)
{
	const char *value;

	if (git_config_get_value("pull.ff", &value))
		return NULL;

	switch (git_config_maybe_bool("pull.ff", value)) {
	case 0:
		return "--no-ff";
	case 1:
		return "--ff";
	}

	if (!strcmp(value, "only"))
		return "--ff-only";

	die(_("Invalid value for pull.ff: %s"), value);
}

287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316
/**
 * Returns the default configured value for --rebase. It first looks for the
 * value of "branch.$curr_branch.rebase", where $curr_branch is the current
 * branch, and if HEAD is detached or the configuration key does not exist,
 * looks for the value of "pull.rebase". If both configuration keys do not
 * exist, returns REBASE_FALSE.
 */
static enum rebase_type config_get_rebase(void)
{
	struct branch *curr_branch = branch_get("HEAD");
	const char *value;

	if (curr_branch) {
		char *key = xstrfmt("branch.%s.rebase", curr_branch->name);

		if (!git_config_get_value(key, &value)) {
			enum rebase_type ret = parse_config_rebase(key, value, 1);
			free(key);
			return ret;
		}

		free(key);
	}

	if (!git_config_get_value("pull.rebase", &value))
		return parse_config_rebase("pull.rebase", value, 1);

	return REBASE_FALSE;
}

317 318 319 320 321 322 323 324 325 326 327 328
/**
 * Read config variables.
 */
static int git_pull_config(const char *var, const char *value, void *cb)
{
	if (!strcmp(var, "rebase.autostash")) {
		config_autostash = git_config_bool(var, value);
		return 0;
	}
	return git_default_config(var, value, cb);
}

P
Paul Tan 已提交
329 330 331 332
/**
 * Appends merge candidates from FETCH_HEAD that are not marked not-for-merge
 * into merge_heads.
 */
333
static void get_merge_heads(struct oid_array *merge_heads)
P
Paul Tan 已提交
334
{
J
Jeff King 已提交
335
	const char *filename = git_path_fetch_head();
P
Paul Tan 已提交
336 337
	FILE *fp;
	struct strbuf sb = STRBUF_INIT;
338
	struct object_id oid;
P
Paul Tan 已提交
339 340 341

	if (!(fp = fopen(filename, "r")))
		die_errno(_("could not open '%s' for reading"), filename);
342
	while (strbuf_getline_lf(&sb, fp) != EOF) {
343
		if (get_oid_hex(sb.buf, &oid))
P
Paul Tan 已提交
344 345 346
			continue;  /* invalid line: does not start with SHA1 */
		if (starts_with(sb.buf + GIT_SHA1_HEXSZ, "\tnot-for-merge\t"))
			continue;  /* ref is not-for-merge */
347
		oid_array_append(merge_heads, &oid);
P
Paul Tan 已提交
348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395
	}
	fclose(fp);
	strbuf_release(&sb);
}

/**
 * Used by die_no_merge_candidates() as a for_each_remote() callback to
 * retrieve the name of the remote if the repository only has one remote.
 */
static int get_only_remote(struct remote *remote, void *cb_data)
{
	const char **remote_name = cb_data;

	if (*remote_name)
		return -1;

	*remote_name = remote->name;
	return 0;
}

/**
 * Dies with the appropriate reason for why there are no merge candidates:
 *
 * 1. We fetched from a specific remote, and a refspec was given, but it ended
 *    up not fetching anything. This is usually because the user provided a
 *    wildcard refspec which had no matches on the remote end.
 *
 * 2. We fetched from a non-default remote, but didn't specify a branch to
 *    merge. We can't use the configured one because it applies to the default
 *    remote, thus the user must specify the branches to merge.
 *
 * 3. We fetched from the branch's or repo's default remote, but:
 *
 *    a. We are not on a branch, so there will never be a configured branch to
 *       merge with.
 *
 *    b. We are on a branch, but there is no configured branch to merge with.
 *
 * 4. We fetched from the branch's or repo's default remote, but the configured
 *    branch to merge didn't get fetched. (Either it doesn't exist, or wasn't
 *    part of the configured fetch refspec.)
 */
static void NORETURN die_no_merge_candidates(const char *repo, const char **refspecs)
{
	struct branch *curr_branch = branch_get("HEAD");
	const char *remote = curr_branch ? curr_branch->remote_name : NULL;

	if (*refspecs) {
396 397 398 399
		if (opt_rebase)
			fprintf_ln(stderr, _("There is no candidate for rebasing against among the refs that you just fetched."));
		else
			fprintf_ln(stderr, _("There are no candidates for merging among the refs that you just fetched."));
P
Paul Tan 已提交
400 401 402 403 404 405 406 407 408
		fprintf_ln(stderr, _("Generally this means that you provided a wildcard refspec which had no\n"
					"matches on the remote end."));
	} else if (repo && curr_branch && (!remote || strcmp(repo, remote))) {
		fprintf_ln(stderr, _("You asked to pull from the remote '%s', but did not specify\n"
			"a branch. Because this is not the default configured remote\n"
			"for your current branch, you must specify a branch on the command line."),
			repo);
	} else if (!curr_branch) {
		fprintf_ln(stderr, _("You are not currently on a branch."));
409 410 411 412
		if (opt_rebase)
			fprintf_ln(stderr, _("Please specify which branch you want to rebase against."));
		else
			fprintf_ln(stderr, _("Please specify which branch you want to merge with."));
P
Paul Tan 已提交
413 414
		fprintf_ln(stderr, _("See git-pull(1) for details."));
		fprintf(stderr, "\n");
415
		fprintf_ln(stderr, "    git pull %s %s", _("<remote>"), _("<branch>"));
P
Paul Tan 已提交
416 417 418 419 420
		fprintf(stderr, "\n");
	} else if (!curr_branch->merge_nr) {
		const char *remote_name = NULL;

		if (for_each_remote(get_only_remote, &remote_name) || !remote_name)
421
			remote_name = _("<remote>");
P
Paul Tan 已提交
422 423

		fprintf_ln(stderr, _("There is no tracking information for the current branch."));
424 425 426 427
		if (opt_rebase)
			fprintf_ln(stderr, _("Please specify which branch you want to rebase against."));
		else
			fprintf_ln(stderr, _("Please specify which branch you want to merge with."));
P
Paul Tan 已提交
428 429
		fprintf_ln(stderr, _("See git-pull(1) for details."));
		fprintf(stderr, "\n");
430
		fprintf_ln(stderr, "    git pull %s %s", _("<remote>"), _("<branch>"));
P
Paul Tan 已提交
431
		fprintf(stderr, "\n");
432 433 434 435
		fprintf_ln(stderr, _("If you wish to set tracking information for this branch you can do so with:"));
		fprintf(stderr, "\n");
		fprintf_ln(stderr, "    git branch --set-upstream-to=%s/%s %s\n",
				remote_name, _("<branch>"), curr_branch->name);
P
Paul Tan 已提交
436 437 438 439 440 441 442
	} else
		fprintf_ln(stderr, _("Your configuration specifies to merge with the ref '%s'\n"
			"from the remote, but no such ref was fetched."),
			*curr_branch->merge_name);
	exit(1);
}

P
Paul Tan 已提交
443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468
/**
 * Parses argv into [<repo> [<refspecs>...]], returning their values in `repo`
 * as a string and `refspecs` as a null-terminated array of strings. If `repo`
 * is not provided in argv, it is set to NULL.
 */
static void parse_repo_refspecs(int argc, const char **argv, const char **repo,
		const char ***refspecs)
{
	if (argc > 0) {
		*repo = *argv++;
		argc--;
	} else
		*repo = NULL;
	*refspecs = argv;
}

/**
 * Runs git-fetch, returning its exit status. `repo` and `refspecs` are the
 * repository and refspecs to fetch, or NULL if they are not provided.
 */
static int run_fetch(const char *repo, const char **refspecs)
{
	struct argv_array args = ARGV_ARRAY_INIT;
	int ret;

	argv_array_pushl(&args, "fetch", "--update-head-ok", NULL);
469 470 471 472 473 474

	/* Shared options */
	argv_push_verbosity(&args);
	if (opt_progress)
		argv_array_push(&args, opt_progress);

475 476 477 478 479 480 481 482 483 484 485 486 487 488
	/* Options passed to git-fetch */
	if (opt_all)
		argv_array_push(&args, opt_all);
	if (opt_append)
		argv_array_push(&args, opt_append);
	if (opt_upload_pack)
		argv_array_push(&args, opt_upload_pack);
	argv_push_force(&args);
	if (opt_tags)
		argv_array_push(&args, opt_tags);
	if (opt_prune)
		argv_array_push(&args, opt_prune);
	if (opt_recurse_submodules)
		argv_array_push(&args, opt_recurse_submodules);
489 490
	if (max_children)
		argv_array_push(&args, max_children);
491 492 493 494 495 496 497 498 499 500 501 502 503
	if (opt_dry_run)
		argv_array_push(&args, "--dry-run");
	if (opt_keep)
		argv_array_push(&args, opt_keep);
	if (opt_depth)
		argv_array_push(&args, opt_depth);
	if (opt_unshallow)
		argv_array_push(&args, opt_unshallow);
	if (opt_update_shallow)
		argv_array_push(&args, opt_update_shallow);
	if (opt_refmap)
		argv_array_push(&args, opt_refmap);

P
Paul Tan 已提交
504 505 506 507 508 509 510 511 512 513
	if (repo) {
		argv_array_push(&args, repo);
		argv_array_pushv(&args, refspecs);
	} else if (*refspecs)
		die("BUG: refspecs without repo?");
	ret = run_command_v_opt(args.argv, RUN_GIT_CMD);
	argv_array_clear(&args);
	return ret;
}

514 515 516
/**
 * "Pulls into void" by branching off merge_head.
 */
517
static int pull_into_void(const struct object_id *merge_head,
518
		const struct object_id *curr_head)
519 520 521 522 523 524 525
{
	/*
	 * Two-way merge: we treat the index as based on an empty tree,
	 * and try to fast-forward to HEAD. This ensures we will not lose
	 * index/worktree changes that the user already made on the unborn
	 * branch.
	 */
526
	if (checkout_fast_forward(EMPTY_TREE_SHA1_BIN, merge_head->hash, 0))
527 528
		return 1;

529
	if (update_ref("initial pull", "HEAD", merge_head->hash, curr_head->hash, 0, UPDATE_REFS_DIE_ON_ERR))
530 531 532 533 534
		return 1;

	return 0;
}

P
Paul Tan 已提交
535 536 537 538 539 540 541 542 543
/**
 * Runs git-merge, returning its exit status.
 */
static int run_merge(void)
{
	int ret;
	struct argv_array args = ARGV_ARRAY_INIT;

	argv_array_pushl(&args, "merge", NULL);
544 545 546 547 548 549

	/* Shared options */
	argv_push_verbosity(&args);
	if (opt_progress)
		argv_array_push(&args, opt_progress);

550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568
	/* Options passed to git-merge */
	if (opt_diffstat)
		argv_array_push(&args, opt_diffstat);
	if (opt_log)
		argv_array_push(&args, opt_log);
	if (opt_squash)
		argv_array_push(&args, opt_squash);
	if (opt_commit)
		argv_array_push(&args, opt_commit);
	if (opt_edit)
		argv_array_push(&args, opt_edit);
	if (opt_ff)
		argv_array_push(&args, opt_ff);
	if (opt_verify_signatures)
		argv_array_push(&args, opt_verify_signatures);
	argv_array_pushv(&args, opt_strategies.argv);
	argv_array_pushv(&args, opt_strategy_opts.argv);
	if (opt_gpg_sign)
		argv_array_push(&args, opt_gpg_sign);
569 570
	if (opt_allow_unrelated_histories > 0)
		argv_array_push(&args, "--allow-unrelated-histories");
571

P
Paul Tan 已提交
572 573 574 575 576 577
	argv_array_push(&args, "FETCH_HEAD");
	ret = run_command_v_opt(args.argv, RUN_GIT_CMD);
	argv_array_clear(&args);
	return ret;
}

P
Paul Tan 已提交
578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649
/**
 * Returns remote's upstream branch for the current branch. If remote is NULL,
 * the current branch's configured default remote is used. Returns NULL if
 * `remote` does not name a valid remote, HEAD does not point to a branch,
 * remote is not the branch's configured remote or the branch does not have any
 * configured upstream branch.
 */
static const char *get_upstream_branch(const char *remote)
{
	struct remote *rm;
	struct branch *curr_branch;
	const char *curr_branch_remote;

	rm = remote_get(remote);
	if (!rm)
		return NULL;

	curr_branch = branch_get("HEAD");
	if (!curr_branch)
		return NULL;

	curr_branch_remote = remote_for_branch(curr_branch, NULL);
	assert(curr_branch_remote);

	if (strcmp(curr_branch_remote, rm->name))
		return NULL;

	return branch_get_upstream(curr_branch, NULL);
}

/**
 * Derives the remote tracking branch from the remote and refspec.
 *
 * FIXME: The current implementation assumes the default mapping of
 * refs/heads/<branch_name> to refs/remotes/<remote_name>/<branch_name>.
 */
static const char *get_tracking_branch(const char *remote, const char *refspec)
{
	struct refspec *spec;
	const char *spec_src;
	const char *merge_branch;

	spec = parse_fetch_refspec(1, &refspec);
	spec_src = spec->src;
	if (!*spec_src || !strcmp(spec_src, "HEAD"))
		spec_src = "HEAD";
	else if (skip_prefix(spec_src, "heads/", &spec_src))
		;
	else if (skip_prefix(spec_src, "refs/heads/", &spec_src))
		;
	else if (starts_with(spec_src, "refs/") ||
		starts_with(spec_src, "tags/") ||
		starts_with(spec_src, "remotes/"))
		spec_src = "";

	if (*spec_src) {
		if (!strcmp(remote, "."))
			merge_branch = mkpath("refs/heads/%s", spec_src);
		else
			merge_branch = mkpath("refs/remotes/%s/%s", remote, spec_src);
	} else
		merge_branch = NULL;

	free_refspec(1, spec);
	return merge_branch;
}

/**
 * Given the repo and refspecs, sets fork_point to the point at which the
 * current branch forked from its remote tracking branch. Returns 0 on success,
 * -1 on failure.
 */
650
static int get_rebase_fork_point(struct object_id *fork_point, const char *repo,
P
Paul Tan 已提交
651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680
		const char *refspec)
{
	int ret;
	struct branch *curr_branch;
	const char *remote_branch;
	struct child_process cp = CHILD_PROCESS_INIT;
	struct strbuf sb = STRBUF_INIT;

	curr_branch = branch_get("HEAD");
	if (!curr_branch)
		return -1;

	if (refspec)
		remote_branch = get_tracking_branch(repo, refspec);
	else
		remote_branch = get_upstream_branch(repo);

	if (!remote_branch)
		return -1;

	argv_array_pushl(&cp.args, "merge-base", "--fork-point",
			remote_branch, curr_branch->name, NULL);
	cp.no_stdin = 1;
	cp.no_stderr = 1;
	cp.git_cmd = 1;

	ret = capture_command(&cp, &sb, GIT_SHA1_HEXSZ);
	if (ret)
		goto cleanup;

681
	ret = get_oid_hex(sb.buf, fork_point);
P
Paul Tan 已提交
682 683 684 685 686 687 688 689 690 691 692 693
	if (ret)
		goto cleanup;

cleanup:
	strbuf_release(&sb);
	return ret ? -1 : 0;
}

/**
 * Sets merge_base to the octopus merge base of curr_head, merge_head and
 * fork_point. Returns 0 if a merge base is found, 1 otherwise.
 */
694 695
static int get_octopus_merge_base(struct object_id *merge_base,
		const struct object_id *curr_head,
696
		const struct object_id *merge_head,
697
		const struct object_id *fork_point)
P
Paul Tan 已提交
698 699 700
{
	struct commit_list *revs = NULL, *result;

701
	commit_list_insert(lookup_commit_reference(curr_head->hash), &revs);
702
	commit_list_insert(lookup_commit_reference(merge_head->hash), &revs);
703 704
	if (!is_null_oid(fork_point))
		commit_list_insert(lookup_commit_reference(fork_point->hash), &revs);
P
Paul Tan 已提交
705 706 707 708 709 710

	result = reduce_heads(get_octopus_merge_bases(revs));
	free_commit_list(revs);
	if (!result)
		return 1;

711
	oidcpy(merge_base, &result->item->object.oid);
P
Paul Tan 已提交
712 713 714 715 716 717 718 719
	return 0;
}

/**
 * Given the current HEAD SHA1, the merge head returned from git-fetch and the
 * fork point calculated by get_rebase_fork_point(), runs git-rebase with the
 * appropriate arguments and returns its exit status.
 */
720
static int run_rebase(const struct object_id *curr_head,
721
		const struct object_id *merge_head,
722
		const struct object_id *fork_point)
P
Paul Tan 已提交
723 724
{
	int ret;
725
	struct object_id oct_merge_base;
P
Paul Tan 已提交
726 727
	struct argv_array args = ARGV_ARRAY_INIT;

728 729
	if (!get_octopus_merge_base(&oct_merge_base, curr_head, merge_head, fork_point))
		if (!is_null_oid(fork_point) && !oidcmp(&oct_merge_base, fork_point))
P
Paul Tan 已提交
730 731 732 733 734 735 736 737 738 739
			fork_point = NULL;

	argv_array_push(&args, "rebase");

	/* Shared options */
	argv_push_verbosity(&args);

	/* Options passed to git-rebase */
	if (opt_rebase == REBASE_PRESERVE)
		argv_array_push(&args, "--preserve-merges");
740 741
	else if (opt_rebase == REBASE_INTERACTIVE)
		argv_array_push(&args, "--interactive");
P
Paul Tan 已提交
742 743 744 745 746 747
	if (opt_diffstat)
		argv_array_push(&args, opt_diffstat);
	argv_array_pushv(&args, opt_strategies.argv);
	argv_array_pushv(&args, opt_strategy_opts.argv);
	if (opt_gpg_sign)
		argv_array_push(&args, opt_gpg_sign);
748 749 750 751
	if (opt_autostash == 0)
		argv_array_push(&args, "--no-autostash");
	else if (opt_autostash == 1)
		argv_array_push(&args, "--autostash");
752 753 754
	if (opt_verify_signatures &&
	    !strcmp(opt_verify_signatures, "--verify-signatures"))
		warning(_("ignoring --verify-signatures for rebase"));
P
Paul Tan 已提交
755 756

	argv_array_push(&args, "--onto");
757
	argv_array_push(&args, oid_to_hex(merge_head));
P
Paul Tan 已提交
758

759 760
	if (fork_point && !is_null_oid(fork_point))
		argv_array_push(&args, oid_to_hex(fork_point));
P
Paul Tan 已提交
761
	else
762
		argv_array_push(&args, oid_to_hex(merge_head));
P
Paul Tan 已提交
763 764 765 766 767 768

	ret = run_command_v_opt(args.argv, RUN_GIT_CMD);
	argv_array_clear(&args);
	return ret;
}

P
Paul Tan 已提交
769 770
int cmd_pull(int argc, const char **argv, const char *prefix)
{
P
Paul Tan 已提交
771
	const char *repo, **refspecs;
772
	struct oid_array merge_heads = OID_ARRAY_INIT;
773 774
	struct object_id orig_head, curr_head;
	struct object_id rebase_fork_point;
P
Paul Tan 已提交
775

P
Paul Tan 已提交
776 777 778
	if (!getenv("GIT_REFLOG_ACTION"))
		set_reflog_message(argc, argv);

P
Paul Tan 已提交
779 780
	argc = parse_options(argc, argv, prefix, pull_options, pull_usage, 0);

P
Paul Tan 已提交
781 782
	parse_repo_refspecs(argc, argv, &repo, &refspecs);

P
Paul Tan 已提交
783 784 785
	if (!opt_ff)
		opt_ff = xstrdup_or_null(config_get_ff());

786 787 788
	if (opt_rebase < 0)
		opt_rebase = config_get_rebase();

789
	git_config(git_pull_config, NULL);
790 791

	if (read_cache_unmerged())
792
		die_resolve_conflict("pull");
793

J
Jeff King 已提交
794
	if (file_exists(git_path_merge_head()))
795 796
		die_conclude_merge();

797 798
	if (get_oid("HEAD", &orig_head))
		oidclr(&orig_head);
799

800 801 802
	if (!opt_rebase && opt_autostash != -1)
		die(_("--[no-]autostash option is only valid with --rebase."));

803
	if (opt_rebase) {
804
		int autostash = config_autostash;
805 806
		if (opt_autostash != -1)
			autostash = opt_autostash;
807

808
		if (is_null_oid(&orig_head) && !is_cache_unborn())
809 810
			die(_("Updating an unborn branch with changes added to the index."));

811
		if (!autostash)
812
			require_clean_work_tree(N_("pull with rebase"),
813
				_("please commit or stash them."), 1, 0);
814

815 816
		if (get_rebase_fork_point(&rebase_fork_point, repo, *refspecs))
			oidclr(&rebase_fork_point);
817
	}
P
Paul Tan 已提交
818

P
Paul Tan 已提交
819 820 821
	if (run_fetch(repo, refspecs))
		return 1;

822 823 824
	if (opt_dry_run)
		return 0;

825 826
	if (get_oid("HEAD", &curr_head))
		oidclr(&curr_head);
827

828 829
	if (!is_null_oid(&orig_head) && !is_null_oid(&curr_head) &&
			oidcmp(&orig_head, &curr_head)) {
830 831 832 833 834 835 836 837 838 839
		/*
		 * The fetch involved updating the current branch.
		 *
		 * The working tree and the index file are still based on
		 * orig_head commit, but we are merging into curr_head.
		 * Update the working tree to match curr_head.
		 */

		warning(_("fetch updated the current branch head.\n"
			"fast-forwarding your working tree from\n"
840
			"commit %s."), oid_to_hex(&orig_head));
841

842
		if (checkout_fast_forward(orig_head.hash, curr_head.hash, 0))
843 844 845 846 847
			die(_("Cannot fast-forward your working tree.\n"
				"After making sure that you saved anything precious from\n"
				"$ git diff %s\n"
				"output, run\n"
				"$ git reset --hard\n"
848
				"to recover."), oid_to_hex(&orig_head));
849 850
	}

P
Paul Tan 已提交
851 852 853 854 855
	get_merge_heads(&merge_heads);

	if (!merge_heads.nr)
		die_no_merge_candidates(repo, refspecs);

856
	if (is_null_oid(&orig_head)) {
857 858
		if (merge_heads.nr > 1)
			die(_("Cannot merge multiple branches into empty head."));
859
		return pull_into_void(merge_heads.oid, &curr_head);
860 861 862 863 864 865 866 867
	}
	if (opt_rebase && merge_heads.nr > 1)
		die(_("Cannot rebase onto multiple branches."));

	if (opt_rebase) {
		struct commit_list *list = NULL;
		struct commit *merge_head, *head;

868
		head = lookup_commit_reference(orig_head.hash);
869
		commit_list_insert(head, &list);
870
		merge_head = lookup_commit_reference(merge_heads.oid[0].hash);
871 872 873 874 875
		if (is_descendant_of(merge_head, list)) {
			/* we can fast-forward this without invoking rebase */
			opt_ff = "--ff-only";
			return run_merge();
		}
876
		return run_rebase(&curr_head, merge_heads.oid, &rebase_fork_point);
877
	} else {
878
		return run_merge();
879
	}
P
Paul Tan 已提交
880
}