fetch.c 31.4 KB
Newer Older
D
Daniel Barkalow 已提交
1 2 3 4 5 6 7
/*
 * "git fetch"
 */
#include "cache.h"
#include "refs.h"
#include "commit.h"
#include "builtin.h"
8
#include "string-list.h"
D
Daniel Barkalow 已提交
9 10
#include "remote.h"
#include "transport.h"
11
#include "run-command.h"
12
#include "parse-options.h"
13
#include "sigchain.h"
14
#include "transport.h"
15
#include "submodule.h"
16
#include "connected.h"
17
#include "argv-array.h"
D
Daniel Barkalow 已提交
18

19
static const char * const builtin_fetch_usage[] = {
20 21 22 23
	N_("git fetch [<options>] [<repository> [<refspec>...]]"),
	N_("git fetch [<options>] <group>"),
	N_("git fetch --multiple [<options>] [(<repository> | <group>)...]"),
	N_("git fetch --all [<options>]"),
24 25
	NULL
};
D
Daniel Barkalow 已提交
26

27 28 29 30 31 32
enum {
	TAGS_UNSET = 0,
	TAGS_DEFAULT = 1,
	TAGS_SET = 2
};

33 34 35 36 37
static int fetch_prune_config = -1; /* unspecified */
static int prune = -1; /* unspecified */
#define PRUNE_BY_DEFAULT 0 /* do we prune by default? */

static int all, append, dry_run, force, keep, multiple, update_head_ok, verbosity;
38
static int progress = -1, recurse_submodules = RECURSE_SUBMODULES_DEFAULT;
39
static int tags = TAGS_DEFAULT, unshallow;
40
static const char *depth;
41
static const char *upload_pack;
42
static struct strbuf default_rla = STRBUF_INIT;
43
static struct transport *gtransport;
44
static struct transport *gsecondary;
45
static const char *submodule_prefix = "";
46
static const char *recurse_submodules_default;
47

48 49 50 51 52 53 54 55 56 57 58 59 60
static int option_parse_recurse_submodules(const struct option *opt,
				   const char *arg, int unset)
{
	if (unset) {
		recurse_submodules = RECURSE_SUBMODULES_OFF;
	} else {
		if (arg)
			recurse_submodules = parse_fetch_recurse_submodules_arg(opt->long_name, arg);
		else
			recurse_submodules = RECURSE_SUBMODULES_ON;
	}
	return 0;
}
61

62 63 64 65 66 67 68 69 70
static int git_fetch_config(const char *k, const char *v, void *cb)
{
	if (!strcmp(k, "fetch.prune")) {
		fetch_prune_config = git_config_bool(k, v);
		return 0;
	}
	return 0;
}

71
static struct option builtin_fetch_options[] = {
T
Tuncer Ayaz 已提交
72
	OPT__VERBOSITY(&verbosity),
73 74 75 76
	OPT_BOOL(0, "all", &all,
		 N_("fetch from all remotes")),
	OPT_BOOL('a', "append", &append,
		 N_("append to .git/FETCH_HEAD instead of overwriting")),
77 78 79
	OPT_STRING(0, "upload-pack", &upload_pack, N_("path"),
		   N_("path to upload pack on remote end")),
	OPT__FORCE(&force, N_("force overwrite of local branch")),
80 81
	OPT_BOOL('m', "multiple", &multiple,
		 N_("fetch from multiple remotes")),
82
	OPT_SET_INT('t', "tags", &tags,
83
		    N_("fetch all tags and associated objects"), TAGS_SET),
84
	OPT_SET_INT('n', NULL, &tags,
85
		    N_("do not fetch all tags (--no-tags)"), TAGS_UNSET),
86 87
	OPT_BOOL('p', "prune", &prune,
		 N_("prune remote-tracking branches no longer on remote")),
88 89
	{ OPTION_CALLBACK, 0, "recurse-submodules", NULL, N_("on-demand"),
		    N_("control recursive fetching of submodules"),
90
		    PARSE_OPT_OPTARG, option_parse_recurse_submodules },
91 92 93 94
	OPT_BOOL(0, "dry-run", &dry_run,
		 N_("dry run")),
	OPT_BOOL('k', "keep", &keep, N_("keep downloaded pack")),
	OPT_BOOL('u', "update-head-ok", &update_head_ok,
95 96 97 98
		    N_("allow updating of HEAD ref")),
	OPT_BOOL(0, "progress", &progress, N_("force progress reporting")),
	OPT_STRING(0, "depth", &depth, N_("depth"),
		   N_("deepen history of shallow clone")),
99 100 101
	{ OPTION_SET_INT, 0, "unshallow", &unshallow, NULL,
		   N_("convert to a complete repository"),
		   PARSE_OPT_NONEG | PARSE_OPT_NOARG, NULL, 1 },
102 103
	{ OPTION_STRING, 0, "submodule-prefix", &submodule_prefix, N_("dir"),
		   N_("prepend this to submodule path output"), PARSE_OPT_HIDDEN },
104 105
	{ OPTION_STRING, 0, "recurse-submodules-default",
		   &recurse_submodules_default, NULL,
106
		   N_("default mode for recursion"), PARSE_OPT_HIDDEN },
107 108 109
	OPT_END()
};

110 111
static void unlock_pack(void)
{
112 113
	if (gtransport)
		transport_unlock_pack(gtransport);
114 115
	if (gsecondary)
		transport_unlock_pack(gsecondary);
116 117 118 119 120
}

static void unlock_pack_on_signal(int signo)
{
	unlock_pack();
121
	sigchain_pop(signo);
122 123
	raise(signo);
}
D
Daniel Barkalow 已提交
124

125
static void add_merge_config(struct ref **head,
126
			   const struct ref *remote_refs,
127 128
		           struct branch *branch,
		           struct ref ***tail)
D
Daniel Barkalow 已提交
129
{
130
	int i;
D
Daniel Barkalow 已提交
131

132 133 134 135 136 137
	for (i = 0; i < branch->merge_nr; i++) {
		struct ref *rm, **old_tail = *tail;
		struct refspec refspec;

		for (rm = *head; rm; rm = rm->next) {
			if (branch_merge_matches(branch, i, rm->name)) {
J
Jeff King 已提交
138
				rm->fetch_head_status = FETCH_HEAD_MERGE;
139 140
				break;
			}
D
Daniel Barkalow 已提交
141
		}
142 143 144
		if (rm)
			continue;

145
		/*
146
		 * Not fetched to a remote-tracking branch?  We need to fetch
147
		 * it anyway to allow this branch's "branch.$name.merge"
148
		 * to be honored by 'git pull', but we do not have to
149 150
		 * fail if branch.$name.merge is misconfigured to point
		 * at a nonexisting branch.  If we were indeed called by
151
		 * 'git pull', it will notice the misconfiguration because
152 153
		 * there is no entry in the resulting FETCH_HEAD marked
		 * for merging.
154
		 */
155
		memset(&refspec, 0, sizeof(refspec));
156
		refspec.src = branch->merge[i]->src;
157
		get_fetch_map(remote_refs, &refspec, tail, 1);
158
		for (rm = *old_tail; rm; rm = rm->next)
J
Jeff King 已提交
159
			rm->fetch_head_status = FETCH_HEAD_MERGE;
D
Daniel Barkalow 已提交
160 161 162
	}
}

163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183
static int add_existing(const char *refname, const unsigned char *sha1,
			int flag, void *cbdata)
{
	struct string_list *list = (struct string_list *)cbdata;
	struct string_list_item *item = string_list_insert(list, refname);
	item->util = xmalloc(20);
	hashcpy(item->util, sha1);
	return 0;
}

static int will_fetch(struct ref **head, const unsigned char *sha1)
{
	struct ref *rm = *head;
	while (rm) {
		if (!hashcmp(rm->old_sha1, sha1))
			return 1;
		rm = rm->next;
	}
	return 0;
}

184 185
static void find_non_local_tags(struct transport *transport,
			struct ref **head,
186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261
			struct ref ***tail)
{
	struct string_list existing_refs = STRING_LIST_INIT_DUP;
	struct string_list remote_refs = STRING_LIST_INIT_NODUP;
	const struct ref *ref;
	struct string_list_item *item = NULL;

	for_each_ref(add_existing, &existing_refs);
	for (ref = transport_get_remote_refs(transport); ref; ref = ref->next) {
		if (prefixcmp(ref->name, "refs/tags/"))
			continue;

		/*
		 * The peeled ref always follows the matching base
		 * ref, so if we see a peeled ref that we don't want
		 * to fetch then we can mark the ref entry in the list
		 * as one to ignore by setting util to NULL.
		 */
		if (!suffixcmp(ref->name, "^{}")) {
			if (item && !has_sha1_file(ref->old_sha1) &&
			    !will_fetch(head, ref->old_sha1) &&
			    !has_sha1_file(item->util) &&
			    !will_fetch(head, item->util))
				item->util = NULL;
			item = NULL;
			continue;
		}

		/*
		 * If item is non-NULL here, then we previously saw a
		 * ref not followed by a peeled reference, so we need
		 * to check if it is a lightweight tag that we want to
		 * fetch.
		 */
		if (item && !has_sha1_file(item->util) &&
		    !will_fetch(head, item->util))
			item->util = NULL;

		item = NULL;

		/* skip duplicates and refs that we already have */
		if (string_list_has_string(&remote_refs, ref->name) ||
		    string_list_has_string(&existing_refs, ref->name))
			continue;

		item = string_list_insert(&remote_refs, ref->name);
		item->util = (void *)ref->old_sha1;
	}
	string_list_clear(&existing_refs, 1);

	/*
	 * We may have a final lightweight tag that needs to be
	 * checked to see if it needs fetching.
	 */
	if (item && !has_sha1_file(item->util) &&
	    !will_fetch(head, item->util))
		item->util = NULL;

	/*
	 * For all the tags in the remote_refs string list,
	 * add them to the list of refs to be fetched
	 */
	for_each_string_list_item(item, &remote_refs) {
		/* Unless we have already decided to ignore this item... */
		if (item->util)
		{
			struct ref *rm = alloc_ref(item->string);
			rm->peer_ref = alloc_ref(item->string);
			hashcpy(rm->old_sha1, item->util);
			**tail = rm;
			*tail = &rm->next;
		}
	}

	string_list_clear(&remote_refs, 0);
}
262

D
Daniel Barkalow 已提交
263
static struct ref *get_ref_map(struct transport *transport,
264 265
			       struct refspec *refspecs, int refspec_count,
			       int tags, int *autotags)
D
Daniel Barkalow 已提交
266 267 268 269 270 271
{
	int i;
	struct ref *rm;
	struct ref *ref_map = NULL;
	struct ref **tail = &ref_map;

272 273
	/* opportunistically-updated references: */
	struct ref *orefs = NULL, **oref_tail = &orefs;
D
Daniel Barkalow 已提交
274

275
	const struct ref *remote_refs = transport_get_remote_refs(transport);
276

277
	if (refspec_count) {
278 279 280
		for (i = 0; i < refspec_count; i++) {
			get_fetch_map(remote_refs, &refspecs[i], &tail, 0);
			if (refspecs[i].dst && refspecs[i].dst[0])
D
Daniel Barkalow 已提交
281 282
				*autotags = 1;
		}
283
		/* Merge everything on the command line (but not --tags) */
D
Daniel Barkalow 已提交
284
		for (rm = ref_map; rm; rm = rm->next)
J
Jeff King 已提交
285
			rm->fetch_head_status = FETCH_HEAD_MERGE;
286 287

		/*
288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305
		 * For any refs that we happen to be fetching via
		 * command-line arguments, the destination ref might
		 * have been missing or have been different than the
		 * remote-tracking ref that would be derived from the
		 * configured refspec.  In these cases, we want to
		 * take the opportunity to update their configured
		 * remote-tracking reference.  However, we do not want
		 * to mention these entries in FETCH_HEAD at all, as
		 * they would simply be duplicates of existing
		 * entries, so we set them FETCH_HEAD_IGNORE below.
		 *
		 * We compute these entries now, based only on the
		 * refspecs specified on the command line.  But we add
		 * them to the list following the refspecs resulting
		 * from the tags option so that one of the latter,
		 * which has FETCH_HEAD_NOT_FOR_MERGE, is not removed
		 * by ref_remove_duplicates() in favor of one of these
		 * opportunistic entries with FETCH_HEAD_IGNORE.
306 307 308
		 */
		for (i = 0; i < transport->remote->fetch_refspec_nr; i++)
			get_fetch_map(ref_map, &transport->remote->fetch[i],
309 310 311 312
				      &oref_tail, 1);

		if (tags == TAGS_SET)
			get_fetch_map(remote_refs, tag_refspec, &tail, 0);
D
Daniel Barkalow 已提交
313 314 315
	} else {
		/* Use the defaults */
		struct remote *remote = transport->remote;
316 317
		struct branch *branch = branch_get(NULL);
		int has_merge = branch_has_merge_config(branch);
318 319
		if (remote &&
		    (remote->fetch_refspec_nr ||
320
		     /* Note: has_merge implies non-NULL branch->remote_name */
321
		     (has_merge && !strcmp(branch->remote_name, remote->name)))) {
D
Daniel Barkalow 已提交
322
			for (i = 0; i < remote->fetch_refspec_nr; i++) {
323
				get_fetch_map(remote_refs, &remote->fetch[i], &tail, 0);
D
Daniel Barkalow 已提交
324 325 326
				if (remote->fetch[i].dst &&
				    remote->fetch[i].dst[0])
					*autotags = 1;
327
				if (!i && !has_merge && ref_map &&
328
				    !remote->fetch[0].pattern)
J
Jeff King 已提交
329
					ref_map->fetch_head_status = FETCH_HEAD_MERGE;
D
Daniel Barkalow 已提交
330
			}
331 332 333 334
			/*
			 * if the remote we're fetching from is the same
			 * as given in branch.<name>.remote, we add the
			 * ref given in branch.<name>.merge, too.
335 336
			 *
			 * Note: has_merge implies non-NULL branch->remote_name
337
			 */
338 339
			if (has_merge &&
			    !strcmp(branch->remote_name, remote->name))
340
				add_merge_config(&ref_map, remote_refs, branch, &tail);
D
Daniel Barkalow 已提交
341 342
		} else {
			ref_map = get_remote_ref(remote_refs, "HEAD");
343
			if (!ref_map)
344
				die(_("Couldn't find remote ref HEAD"));
J
Jeff King 已提交
345
			ref_map->fetch_head_status = FETCH_HEAD_MERGE;
346
			tail = &ref_map->next;
D
Daniel Barkalow 已提交
347 348
		}
	}
349

350 351 352 353
	if (tags == TAGS_SET)
		/* also fetch all tags */
		get_fetch_map(remote_refs, tag_refspec, &tail, 0);
	else if (tags == TAGS_DEFAULT && *autotags)
354
		find_non_local_tags(transport, &ref_map, &tail);
355

356 357 358 359 360 361 362
	/* Now append any refs to be updated opportunistically: */
	*tail = orefs;
	for (rm = orefs; rm; rm = rm->next) {
		rm->fetch_head_status = FETCH_HEAD_IGNORE;
		tail = &rm->next;
	}

363
	ref_remove_duplicates(ref_map);
D
Daniel Barkalow 已提交
364 365 366 367

	return ref_map;
}

368 369 370
#define STORE_REF_ERROR_OTHER 1
#define STORE_REF_ERROR_DF_CONFLICT 2

D
Daniel Barkalow 已提交
371 372 373 374 375 376 377 378
static int s_update_ref(const char *action,
			struct ref *ref,
			int check_old)
{
	char msg[1024];
	char *rla = getenv("GIT_REFLOG_ACTION");
	static struct ref_lock *lock;

J
Jay Soffian 已提交
379 380
	if (dry_run)
		return 0;
D
Daniel Barkalow 已提交
381
	if (!rla)
382
		rla = default_rla.buf;
D
Daniel Barkalow 已提交
383 384
	snprintf(msg, sizeof(msg), "%s: %s", rla, action);
	lock = lock_any_ref_for_update(ref->name,
385 386
				       check_old ? ref->old_sha1 : NULL,
				       0, NULL);
D
Daniel Barkalow 已提交
387
	if (!lock)
388 389
		return errno == ENOTDIR ? STORE_REF_ERROR_DF_CONFLICT :
					  STORE_REF_ERROR_OTHER;
D
Daniel Barkalow 已提交
390
	if (write_ref_sha1(lock, ref->new_sha1, msg) < 0)
391 392
		return errno == ENOTDIR ? STORE_REF_ERROR_DF_CONFLICT :
					  STORE_REF_ERROR_OTHER;
D
Daniel Barkalow 已提交
393 394 395
	return 0;
}

P
Pierre Habouzit 已提交
396
#define REFCOL_WIDTH  10
N
Nicolas Pitre 已提交
397

D
Daniel Barkalow 已提交
398
static int update_local_ref(struct ref *ref,
N
Nicolas Pitre 已提交
399
			    const char *remote,
400
			    const struct ref *remote_ref,
401
			    struct strbuf *display)
D
Daniel Barkalow 已提交
402 403 404 405
{
	struct commit *current = NULL, *updated;
	enum object_type type;
	struct branch *current_branch = branch_get(NULL);
406
	const char *pretty_ref = prettify_refname(ref->name);
D
Daniel Barkalow 已提交
407 408 409

	type = sha1_object_info(ref->new_sha1, NULL);
	if (type < 0)
410
		die(_("object %s not found"), sha1_to_hex(ref->new_sha1));
D
Daniel Barkalow 已提交
411 412

	if (!hashcmp(ref->old_sha1, ref->new_sha1)) {
T
Tuncer Ayaz 已提交
413
		if (verbosity > 0)
414
			strbuf_addf(display, "= %-*s %-*s -> %s",
415 416
				    TRANSPORT_SUMMARY(_("[up to date]")),
				    REFCOL_WIDTH, remote, pretty_ref);
D
Daniel Barkalow 已提交
417 418 419
		return 0;
	}

420 421
	if (current_branch &&
	    !strcmp(ref->name, current_branch->name) &&
D
Daniel Barkalow 已提交
422 423 424 425 426 427
	    !(update_head_ok || is_bare_repository()) &&
	    !is_null_sha1(ref->old_sha1)) {
		/*
		 * If this is the head, and it's not okay to update
		 * the head, and the old value of the head isn't empty...
		 */
428 429
		strbuf_addf(display,
			    _("! %-*s %-*s -> %s  (can't fetch in current branch)"),
430
			    TRANSPORT_SUMMARY(_("[rejected]")),
431
			    REFCOL_WIDTH, remote, pretty_ref);
D
Daniel Barkalow 已提交
432 433 434 435 436
		return 1;
	}

	if (!is_null_sha1(ref->old_sha1) &&
	    !prefixcmp(ref->name, "refs/tags/")) {
437 438
		int r;
		r = s_update_ref("updating tag", ref, 0);
439 440
		strbuf_addf(display, "%c %-*s %-*s -> %s%s",
			    r ? '!' : '-',
441
			    TRANSPORT_SUMMARY(_("[tag update]")),
442 443
			    REFCOL_WIDTH, remote, pretty_ref,
			    r ? _("  (unable to update local ref)") : "");
444
		return r;
D
Daniel Barkalow 已提交
445 446
	}

447 448
	current = lookup_commit_reference_gently(ref->old_sha1, 1);
	updated = lookup_commit_reference_gently(ref->new_sha1, 1);
D
Daniel Barkalow 已提交
449
	if (!current || !updated) {
N
Nicolas Pitre 已提交
450 451
		const char *msg;
		const char *what;
452
		int r;
453 454 455 456 457 458 459
		/*
		 * Nicely describe the new ref we're fetching.
		 * Base this on the remote's ref name, as it's
		 * more likely to follow a standard layout.
		 */
		const char *name = remote_ref ? remote_ref->name : "";
		if (!prefixcmp(name, "refs/tags/")) {
D
Daniel Barkalow 已提交
460
			msg = "storing tag";
461
			what = _("[new tag]");
462
		} else if (!prefixcmp(name, "refs/heads/")) {
D
Daniel Barkalow 已提交
463
			msg = "storing head";
464
			what = _("[new branch]");
465 466 467
		} else {
			msg = "storing ref";
			what = _("[new ref]");
N
Nicolas Pitre 已提交
468 469
		}

470 471 472
		if ((recurse_submodules != RECURSE_SUBMODULES_OFF) &&
		    (recurse_submodules != RECURSE_SUBMODULES_ON))
			check_for_new_submodule_commits(ref->new_sha1);
473
		r = s_update_ref(msg, ref, 0);
474 475
		strbuf_addf(display, "%c %-*s %-*s -> %s%s",
			    r ? '!' : '*',
476
			    TRANSPORT_SUMMARY(what),
477 478
			    REFCOL_WIDTH, remote, pretty_ref,
			    r ? _("  (unable to update local ref)") : "");
479
		return r;
D
Daniel Barkalow 已提交
480 481
	}

482
	if (in_merge_bases(current, updated)) {
N
Nicolas Pitre 已提交
483
		char quickref[83];
484
		int r;
N
Nicolas Pitre 已提交
485 486 487
		strcpy(quickref, find_unique_abbrev(current->object.sha1, DEFAULT_ABBREV));
		strcat(quickref, "..");
		strcat(quickref, find_unique_abbrev(ref->new_sha1, DEFAULT_ABBREV));
488 489 490
		if ((recurse_submodules != RECURSE_SUBMODULES_OFF) &&
		    (recurse_submodules != RECURSE_SUBMODULES_ON))
			check_for_new_submodule_commits(ref->new_sha1);
491
		r = s_update_ref("fast-forward", ref, 1);
492 493 494 495 496
		strbuf_addf(display, "%c %-*s %-*s -> %s%s",
			    r ? '!' : ' ',
			    TRANSPORT_SUMMARY_WIDTH, quickref,
			    REFCOL_WIDTH, remote, pretty_ref,
			    r ? _("  (unable to update local ref)") : "");
497
		return r;
N
Nicolas Pitre 已提交
498 499
	} else if (force || ref->force) {
		char quickref[84];
500
		int r;
N
Nicolas Pitre 已提交
501 502 503
		strcpy(quickref, find_unique_abbrev(current->object.sha1, DEFAULT_ABBREV));
		strcat(quickref, "...");
		strcat(quickref, find_unique_abbrev(ref->new_sha1, DEFAULT_ABBREV));
504 505 506
		if ((recurse_submodules != RECURSE_SUBMODULES_OFF) &&
		    (recurse_submodules != RECURSE_SUBMODULES_ON))
			check_for_new_submodule_commits(ref->new_sha1);
507
		r = s_update_ref("forced-update", ref, 1);
508 509 510 511 512
		strbuf_addf(display, "%c %-*s %-*s -> %s  (%s)",
			    r ? '!' : '+',
			    TRANSPORT_SUMMARY_WIDTH, quickref,
			    REFCOL_WIDTH, remote, pretty_ref,
			    r ? _("unable to update local ref") : _("forced update"));
513
		return r;
N
Nicolas Pitre 已提交
514
	} else {
515
		strbuf_addf(display, "! %-*s %-*s -> %s  %s",
516
			    TRANSPORT_SUMMARY(_("[rejected]")),
517 518
			    REFCOL_WIDTH, remote, pretty_ref,
			    _("(non-fast-forward)"));
D
Daniel Barkalow 已提交
519 520 521 522
		return 1;
	}
}

523
static int iterate_ref_map(void *cb_data, unsigned char sha1[20])
524
{
525 526
	struct ref **rm = cb_data;
	struct ref *ref = *rm;
527

528 529 530 531 532
	if (!ref)
		return -1; /* end of the list */
	*rm = ref->next;
	hashcpy(sha1, ref->old_sha1);
	return 0;
533 534
}

535
static int store_updated_refs(const char *raw_url, const char *remote_name,
536
		struct ref *ref_map)
D
Daniel Barkalow 已提交
537 538 539
{
	FILE *fp;
	struct commit *commit;
540 541
	int url_len, i, shown_url = 0, rc = 0;
	struct strbuf note = STRBUF_INIT;
D
Daniel Barkalow 已提交
542 543
	const char *what, *kind;
	struct ref *rm;
J
Jay Soffian 已提交
544
	char *url, *filename = dry_run ? "/dev/null" : git_path("FETCH_HEAD");
J
Jeff King 已提交
545
	int want_status;
D
Daniel Barkalow 已提交
546

547 548
	fp = fopen(filename, "a");
	if (!fp)
549
		return error(_("cannot open %s: %s\n"), filename, strerror(errno));
550

551 552 553 554
	if (raw_url)
		url = transport_anonymize_url(raw_url);
	else
		url = xstrdup("foreign");
555

556
	rm = ref_map;
J
Junio C Hamano 已提交
557
	if (check_everything_connected(iterate_ref_map, 0, &rm)) {
558 559 560
		rc = error(_("%s did not send all necessary objects\n"), url);
		goto abort;
	}
561

562
	/*
J
Jeff King 已提交
563 564 565
	 * We do a pass for each fetch_head_status type in their enum order, so
	 * merged entries are written before not-for-merge. That lets readers
	 * use FETCH_HEAD as a refname to refer to the ref to be merged.
566
	 */
J
Jeff King 已提交
567 568 569
	for (want_status = FETCH_HEAD_MERGE;
	     want_status <= FETCH_HEAD_IGNORE;
	     want_status++) {
570 571
		for (rm = ref_map; rm; rm = rm->next) {
			struct ref *ref = NULL;
J
Jeff King 已提交
572
			const char *merge_status_marker = "";
573 574 575

			commit = lookup_commit_reference_gently(rm->old_sha1, 1);
			if (!commit)
J
Jeff King 已提交
576
				rm->fetch_head_status = FETCH_HEAD_NOT_FOR_MERGE;
577

J
Jeff King 已提交
578
			if (rm->fetch_head_status != want_status)
579 580 581 582 583 584 585 586 587
				continue;

			if (rm->peer_ref) {
				ref = xcalloc(1, sizeof(*ref) + strlen(rm->peer_ref->name) + 1);
				strcpy(ref->name, rm->peer_ref->name);
				hashcpy(ref->old_sha1, rm->peer_ref->old_sha1);
				hashcpy(ref->new_sha1, rm->old_sha1);
				ref->force = rm->peer_ref->force;
			}
D
Daniel Barkalow 已提交
588 589


590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609
			if (!strcmp(rm->name, "HEAD")) {
				kind = "";
				what = "";
			}
			else if (!prefixcmp(rm->name, "refs/heads/")) {
				kind = "branch";
				what = rm->name + 11;
			}
			else if (!prefixcmp(rm->name, "refs/tags/")) {
				kind = "tag";
				what = rm->name + 10;
			}
			else if (!prefixcmp(rm->name, "refs/remotes/")) {
				kind = "remote-tracking branch";
				what = rm->name + 13;
			}
			else {
				kind = "";
				what = rm->name;
			}
D
Daniel Barkalow 已提交
610

611 612 613 614 615 616 617 618 619 620 621 622 623
			url_len = strlen(url);
			for (i = url_len - 1; url[i] == '/' && 0 <= i; i--)
				;
			url_len = i + 1;
			if (4 < i && !strncmp(".git", url + i - 3, 4))
				url_len = i - 3;

			strbuf_reset(&note);
			if (*what) {
				if (*kind)
					strbuf_addf(&note, "%s ", kind);
				strbuf_addf(&note, "'%s' of ", what);
			}
J
Jeff King 已提交
624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643
			switch (rm->fetch_head_status) {
			case FETCH_HEAD_NOT_FOR_MERGE:
				merge_status_marker = "not-for-merge";
				/* fall-through */
			case FETCH_HEAD_MERGE:
				fprintf(fp, "%s\t%s\t%s",
					sha1_to_hex(rm->old_sha1),
					merge_status_marker,
					note.buf);
				for (i = 0; i < url_len; ++i)
					if ('\n' == url[i])
						fputs("\\n", fp);
					else
						fputc(url[i], fp);
				fputc('\n', fp);
				break;
			default:
				/* do not write anything to FETCH_HEAD */
				break;
			}
644 645 646

			strbuf_reset(&note);
			if (ref) {
647
				rc |= update_local_ref(ref, what, rm, &note);
648 649 650 651 652 653 654 655 656 657 658 659 660 661 662
				free(ref);
			} else
				strbuf_addf(&note, "* %-*s %-*s -> FETCH_HEAD",
					    TRANSPORT_SUMMARY_WIDTH,
					    *kind ? kind : "branch",
					    REFCOL_WIDTH,
					    *what ? what : "HEAD");
			if (note.len) {
				if (verbosity >= 0 && !shown_url) {
					fprintf(stderr, _("From %.*s\n"),
							url_len, url);
					shown_url = 1;
				}
				if (verbosity >= 0)
					fprintf(stderr, " %s\n", note.buf);
N
Nicolas Pitre 已提交
663 664
			}
		}
D
Daniel Barkalow 已提交
665
	}
666

667
	if (rc & STORE_REF_ERROR_DF_CONFLICT)
668
		error(_("some local refs could not be updated; try running\n"
669
		      " 'git remote prune %s' to remove any old, conflicting "
670
		      "branches"), remote_name);
671 672

 abort:
673
	strbuf_release(&note);
674 675
	free(url);
	fclose(fp);
676
	return rc;
D
Daniel Barkalow 已提交
677 678
}

679 680
/*
 * We would want to bypass the object transfer altogether if
681
 * everything we are going to fetch already exists and is connected
682 683 684 685
 * locally.
 */
static int quickfetch(struct ref *ref_map)
{
686 687
	struct ref *rm = ref_map;

688 689 690 691 692 693 694 695 696
	/*
	 * If we are deepening a shallow clone we already have these
	 * objects reachable.  Running rev-list here will return with
	 * a good (0) exit status and we'll bypass the fetch that we
	 * really need to perform.  Claiming failure now will ensure
	 * we perform the network exchange to deepen our history.
	 */
	if (depth)
		return -1;
697
	return check_everything_connected(iterate_ref_map, 1, &rm);
698 699
}

D
Daniel Barkalow 已提交
700 701
static int fetch_refs(struct transport *transport, struct ref *ref_map)
{
702 703 704
	int ret = quickfetch(ref_map);
	if (ret)
		ret = transport_fetch_refs(transport, ref_map);
D
Daniel Barkalow 已提交
705
	if (!ret)
706 707 708
		ret |= store_updated_refs(transport->url,
				transport->remote->name,
				ref_map);
709
	transport_unlock_pack(transport);
D
Daniel Barkalow 已提交
710 711 712
	return ret;
}

713
static int prune_refs(struct refspec *refs, int ref_count, struct ref *ref_map)
J
Jay Soffian 已提交
714 715
{
	int result = 0;
716
	struct ref *ref, *stale_refs = get_stale_heads(refs, ref_count, ref_map);
J
Jay Soffian 已提交
717
	const char *dangling_msg = dry_run
718 719
		? _("   (%s will become dangling)")
		: _("   (%s has become dangling)");
J
Jay Soffian 已提交
720 721 722 723 724 725

	for (ref = stale_refs; ref; ref = ref->next) {
		if (!dry_run)
			result |= delete_ref(ref->name, NULL, 0);
		if (verbosity >= 0) {
			fprintf(stderr, " x %-*s %-*s -> %s\n",
726
				TRANSPORT_SUMMARY(_("[deleted]")),
727
				REFCOL_WIDTH, _("(none)"), prettify_refname(ref->name));
J
Jay Soffian 已提交
728 729 730 731 732 733 734
			warn_dangling_symref(stderr, dangling_msg, ref->name);
		}
	}
	free_refs(stale_refs);
	return result;
}

735 736 737 738 739 740 741 742 743 744
static void check_not_current_branch(struct ref *ref_map)
{
	struct branch *current_branch = branch_get(NULL);

	if (is_bare_repository() || !current_branch)
		return;

	for (; ref_map; ref_map = ref_map->next)
		if (ref_map->peer_ref && !strcmp(current_branch->refname,
					ref_map->peer_ref->name))
745 746
			die(_("Refusing to fetch into current branch %s "
			    "of non-bare repository"), current_branch->refname);
747 748
}

749 750 751 752 753 754
static int truncate_fetch_head(void)
{
	char *filename = git_path("FETCH_HEAD");
	FILE *fp = fopen(filename, "w");

	if (!fp)
755
		return error(_("cannot open %s: %s\n"), filename, strerror(errno));
756 757 758 759
	fclose(fp);
	return 0;
}

760 761 762 763 764 765 766 767 768 769 770
static void set_option(struct transport *transport, const char *name, const char *value)
{
	int r = transport_set_option(transport, name, value);
	if (r < 0)
		die(_("Option \"%s\" value \"%s\" is not valid for %s"),
		    name, value, transport->url);
	if (r > 0)
		warning(_("Option \"%s\" is ignored for %s\n"),
			name, transport->url);
}

771
static struct transport *prepare_transport(struct remote *remote)
772 773 774 775 776 777 778 779 780 781 782 783 784
{
	struct transport *transport;
	transport = transport_get(remote, NULL);
	transport_set_verbosity(transport, verbosity, progress);
	if (upload_pack)
		set_option(transport, TRANS_OPT_UPLOADPACK, upload_pack);
	if (keep)
		set_option(transport, TRANS_OPT_KEEP, "yes");
	if (depth)
		set_option(transport, TRANS_OPT_DEPTH, depth);
	return transport;
}

785 786
static void backfill_tags(struct transport *transport, struct ref *ref_map)
{
787 788 789 790 791
	if (transport->cannot_reuse) {
		gsecondary = prepare_transport(transport->remote);
		transport = gsecondary;
	}

792 793 794
	transport_set_option(transport, TRANS_OPT_FOLLOWTAGS, NULL);
	transport_set_option(transport, TRANS_OPT_DEPTH, "0");
	fetch_refs(transport, ref_map);
795 796 797 798 799

	if (gsecondary) {
		transport_disconnect(gsecondary);
		gsecondary = NULL;
	}
800 801
}

D
Daniel Barkalow 已提交
802 803 804
static int do_fetch(struct transport *transport,
		    struct refspec *refs, int ref_count)
{
805
	struct string_list existing_refs = STRING_LIST_INIT_DUP;
806
	struct ref *ref_map;
D
Daniel Barkalow 已提交
807 808
	struct ref *rm;
	int autotags = (transport->remote->fetch_tags == 1);
809
	int retcode = 0;
810 811 812

	for_each_ref(add_existing, &existing_refs);

813 814 815 816 817 818
	if (tags == TAGS_DEFAULT) {
		if (transport->remote->fetch_tags == 2)
			tags = TAGS_SET;
		if (transport->remote->fetch_tags == -1)
			tags = TAGS_UNSET;
	}
D
Daniel Barkalow 已提交
819

820
	if (!transport->get_refs_list || !transport->fetch)
821
		die(_("Don't know how to fetch from %s"), transport->url);
D
Daniel Barkalow 已提交
822 823

	/* if not appending, truncate FETCH_HEAD */
J
Jay Soffian 已提交
824
	if (!append && !dry_run) {
825 826 827
		retcode = truncate_fetch_head();
		if (retcode)
			goto cleanup;
828
	}
D
Daniel Barkalow 已提交
829 830

	ref_map = get_ref_map(transport, refs, ref_count, tags, &autotags);
831 832
	if (!update_head_ok)
		check_not_current_branch(ref_map);
D
Daniel Barkalow 已提交
833 834

	for (rm = ref_map; rm; rm = rm->next) {
835
		if (rm->peer_ref) {
836 837 838
			struct string_list_item *peer_item =
				string_list_lookup(&existing_refs,
						   rm->peer_ref->name);
839 840 841 842
			if (peer_item)
				hashcpy(rm->peer_ref->old_sha1,
					peer_item->util);
		}
D
Daniel Barkalow 已提交
843 844
	}

845 846
	if (tags == TAGS_DEFAULT && autotags)
		transport_set_option(transport, TRANS_OPT_FOLLOWTAGS, "1");
D
Daniel Barkalow 已提交
847 848
	if (fetch_refs(transport, ref_map)) {
		free_refs(ref_map);
849 850
		retcode = 1;
		goto cleanup;
D
Daniel Barkalow 已提交
851
	}
852
	if (prune) {
853 854 855 856 857
		/*
		 * We only prune based on refspecs specified
		 * explicitly (via command line or configuration); we
		 * don't care whether --tags was specified.
		 */
858
		if (ref_count) {
859
			prune_refs(refs, ref_count, ref_map);
860
		} else {
861 862 863
			prune_refs(transport->remote->fetch,
				   transport->remote->fetch_refspec_nr,
				   ref_map);
864
		}
865
	}
866
	free_refs(ref_map);
D
Daniel Barkalow 已提交
867 868 869

	/* if neither --no-tags nor --tags was specified, do automated tag
	 * following ... */
870
	if (tags == TAGS_DEFAULT && autotags) {
871 872 873
		struct ref **tail = &ref_map;
		ref_map = NULL;
		find_non_local_tags(transport, &ref_map, &tail);
874 875
		if (ref_map)
			backfill_tags(transport, ref_map);
D
Daniel Barkalow 已提交
876 877 878
		free_refs(ref_map);
	}

879
 cleanup:
880
	string_list_clear(&existing_refs, 1);
881
	return retcode;
D
Daniel Barkalow 已提交
882 883
}

884 885 886
static int get_one_remote_for_fetch(struct remote *remote, void *priv)
{
	struct string_list *list = priv;
887
	if (!remote->skip_default_update)
888
		string_list_append(list, remote->name);
889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906
	return 0;
}

struct remote_group_data {
	const char *name;
	struct string_list *list;
};

static int get_remote_group(const char *key, const char *value, void *priv)
{
	struct remote_group_data *g = priv;

	if (!prefixcmp(key, "remotes.") &&
			!strcmp(key + 8, g->name)) {
		/* split list by white space */
		int space = strcspn(value, " \t\n");
		while (*value) {
			if (space > 1) {
907 908
				string_list_append(g->list,
						   xstrndup(value, space));
909 910 911 912 913 914 915 916 917 918 919 920
			}
			value += space + (value[space] != '\0');
			space = strcspn(value, " \t\n");
		}
	}

	return 0;
}

static int add_remote_or_group(const char *name, struct string_list *list)
{
	int prev_nr = list->nr;
921 922
	struct remote_group_data g;
	g.name = name; g.list = list;
923 924 925 926 927 928 929

	git_config(get_remote_group, &g);
	if (list->nr == prev_nr) {
		struct remote *remote;
		if (!remote_is_configured(name))
			return 0;
		remote = remote_get(name);
930
		string_list_append(list, remote->name);
931 932 933 934
	}
	return 1;
}

935
static void add_options_to_argv(struct argv_array *argv)
936
{
J
Jay Soffian 已提交
937
	if (dry_run)
938
		argv_array_push(argv, "--dry-run");
939
	if (prune > 0)
940
		argv_array_push(argv, "--prune");
941
	if (update_head_ok)
942
		argv_array_push(argv, "--update-head-ok");
943
	if (force)
944
		argv_array_push(argv, "--force");
945
	if (keep)
946
		argv_array_push(argv, "--keep");
947
	if (recurse_submodules == RECURSE_SUBMODULES_ON)
948
		argv_array_push(argv, "--recurse-submodules");
949
	else if (recurse_submodules == RECURSE_SUBMODULES_ON_DEMAND)
950
		argv_array_push(argv, "--recurse-submodules=on-demand");
951 952 953 954
	if (tags == TAGS_SET)
		argv_array_push(argv, "--tags");
	else if (tags == TAGS_UNSET)
		argv_array_push(argv, "--no-tags");
955
	if (verbosity >= 2)
956
		argv_array_push(argv, "-v");
957
	if (verbosity >= 1)
958
		argv_array_push(argv, "-v");
959
	else if (verbosity < 0)
960
		argv_array_push(argv, "-q");
961 962 963 964 965 966

}

static int fetch_multiple(struct string_list *list)
{
	int i, result = 0;
967
	struct argv_array argv = ARGV_ARRAY_INIT;
968

969 970 971 972 973 974
	if (!append && !dry_run) {
		int errcode = truncate_fetch_head();
		if (errcode)
			return errcode;
	}

975 976 977
	argv_array_pushl(&argv, "fetch", "--append", NULL);
	add_options_to_argv(&argv);

978 979
	for (i = 0; i < list->nr; i++) {
		const char *name = list->items[i].string;
980
		argv_array_push(&argv, name);
981
		if (verbosity >= 0)
982
			printf(_("Fetching %s\n"), name);
983
		if (run_command_v_opt(argv.argv, RUN_GIT_CMD)) {
984
			error(_("Could not fetch %s"), name);
985 986
			result = 1;
		}
987
		argv_array_pop(&argv);
988 989
	}

990
	argv_array_clear(&argv);
991 992 993 994
	return result;
}

static int fetch_one(struct remote *remote, int argc, const char **argv)
D
Daniel Barkalow 已提交
995
{
996
	int i;
D
Daniel Barkalow 已提交
997
	static const char **refs = NULL;
J
Jim Meyering 已提交
998
	struct refspec *refspec;
D
Daniel Barkalow 已提交
999
	int ref_nr = 0;
1000
	int exit_code;
D
Daniel Barkalow 已提交
1001

1002
	if (!remote)
1003 1004
		die(_("No remote repository specified.  Please, specify either a URL or a\n"
		    "remote name from which new revisions should be fetched."));
1005

1006
	gtransport = prepare_transport(remote);
1007 1008 1009

	if (prune < 0) {
		/* no command line request */
1010 1011
		if (0 <= gtransport->remote->prune)
			prune = gtransport->remote->prune;
1012 1013 1014 1015 1016 1017
		else if (0 <= fetch_prune_config)
			prune = fetch_prune_config;
		else
			prune = PRUNE_BY_DEFAULT;
	}

1018
	if (argc > 0) {
D
Daniel Barkalow 已提交
1019
		int j = 0;
1020
		refs = xcalloc(argc + 1, sizeof(const char *));
1021
		for (i = 0; i < argc; i++) {
D
Daniel Barkalow 已提交
1022 1023 1024
			if (!strcmp(argv[i], "tag")) {
				char *ref;
				i++;
1025
				if (i >= argc)
1026
					die(_("You need to specify a tag name."));
D
Daniel Barkalow 已提交
1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039
				ref = xmalloc(strlen(argv[i]) * 2 + 22);
				strcpy(ref, "refs/tags/");
				strcat(ref, argv[i]);
				strcat(ref, ":refs/tags/");
				strcat(ref, argv[i]);
				refs[j++] = ref;
			} else
				refs[j++] = argv[i];
		}
		refs[j] = NULL;
		ref_nr = j;
	}

1040
	sigchain_push_common(unlock_pack_on_signal);
1041
	atexit(unlock_pack);
J
Jim Meyering 已提交
1042
	refspec = parse_fetch_refspec(ref_nr, refs);
1043
	exit_code = do_fetch(gtransport, refspec, ref_nr);
1044
	free_refspec(ref_nr, refspec);
1045 1046
	transport_disconnect(gtransport);
	gtransport = NULL;
1047
	return exit_code;
D
Daniel Barkalow 已提交
1048
}
1049 1050 1051 1052

int cmd_fetch(int argc, const char **argv, const char *prefix)
{
	int i;
1053
	struct string_list list = STRING_LIST_INIT_NODUP;
1054 1055
	struct remote *remote;
	int result = 0;
J
Jeff King 已提交
1056 1057 1058
	static const char *argv_gc_auto[] = {
		"gc", "--auto", NULL,
	};
1059

J
Jeff King 已提交
1060 1061
	packet_trace_identity("fetch");

1062 1063 1064 1065 1066
	/* Record the command line for the reflog */
	strbuf_addstr(&default_rla, "fetch");
	for (i = 1; i < argc; i++)
		strbuf_addf(&default_rla, " %s", argv[i]);

1067 1068
	git_config(git_fetch_config, NULL);

1069 1070 1071
	argc = parse_options(argc, argv, prefix,
			     builtin_fetch_options, builtin_fetch_usage, 0);

1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083
	if (unshallow) {
		if (depth)
			die(_("--depth and --unshallow cannot be used together"));
		else if (!is_repository_shallow())
			die(_("--unshallow on a complete repository does not make sense"));
		else {
			static char inf_depth[12];
			sprintf(inf_depth, "%d", INFINITE_DEPTH);
			depth = inf_depth;
		}
	}

1084 1085 1086 1087 1088 1089 1090 1091 1092
	if (recurse_submodules != RECURSE_SUBMODULES_OFF) {
		if (recurse_submodules_default) {
			int arg = parse_fetch_recurse_submodules_arg("--recurse-submodules-default", recurse_submodules_default);
			set_config_fetch_recurse_submodules(arg);
		}
		gitmodules_config();
		git_config(submodule_config, NULL);
	}

1093 1094
	if (all) {
		if (argc == 1)
1095
			die(_("fetch --all does not take a repository argument"));
1096
		else if (argc > 1)
1097
			die(_("fetch --all does not make sense with refspecs"));
1098 1099 1100 1101 1102 1103
		(void) for_each_remote(get_one_remote_for_fetch, &list);
		result = fetch_multiple(&list);
	} else if (argc == 0) {
		/* No arguments -- use default remote */
		remote = remote_get(NULL);
		result = fetch_one(remote, argc, argv);
1104 1105 1106 1107
	} else if (multiple) {
		/* All arguments are assumed to be remotes or groups */
		for (i = 0; i < argc; i++)
			if (!add_remote_or_group(argv[i], &list))
1108
				die(_("No such remote or remote group: %s"), argv[i]);
1109
		result = fetch_multiple(&list);
1110 1111 1112 1113 1114 1115
	} else {
		/* Single remote or group */
		(void) add_remote_or_group(argv[0], &list);
		if (list.nr > 1) {
			/* More than one remote */
			if (argc > 1)
1116
				die(_("Fetching a group and specifying refspecs does not make sense"));
1117 1118 1119 1120 1121 1122 1123 1124
			result = fetch_multiple(&list);
		} else {
			/* Zero or one remotes */
			remote = remote_get(argv[0]);
			result = fetch_one(remote, argc-1, argv+1);
		}
	}

1125
	if (!result && (recurse_submodules != RECURSE_SUBMODULES_OFF)) {
1126 1127 1128
		struct argv_array options = ARGV_ARRAY_INIT;

		add_options_to_argv(&options);
1129
		result = fetch_populated_submodules(&options,
1130
						    submodule_prefix,
1131
						    recurse_submodules,
1132
						    verbosity < 0);
1133
		argv_array_clear(&options);
1134 1135
	}

1136 1137 1138 1139
	/* All names were strdup()ed or strndup()ed */
	list.strdup_strings = 1;
	string_list_clear(&list, 0);

J
Jeff King 已提交
1140 1141
	run_command_v_opt(argv_gc_auto, RUN_GIT_CMD);

1142 1143
	return result;
}