fetch.c 31.5 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
	return ref_remove_duplicates(ref_map);
D
Daniel Barkalow 已提交
364 365
}

366 367 368
#define STORE_REF_ERROR_OTHER 1
#define STORE_REF_ERROR_DF_CONFLICT 2

D
Daniel Barkalow 已提交
369 370 371 372 373 374 375 376
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 已提交
377 378
	if (dry_run)
		return 0;
D
Daniel Barkalow 已提交
379
	if (!rla)
380
		rla = default_rla.buf;
D
Daniel Barkalow 已提交
381 382
	snprintf(msg, sizeof(msg), "%s: %s", rla, action);
	lock = lock_any_ref_for_update(ref->name,
383 384
				       check_old ? ref->old_sha1 : NULL,
				       0, NULL);
D
Daniel Barkalow 已提交
385
	if (!lock)
386 387
		return errno == ENOTDIR ? STORE_REF_ERROR_DF_CONFLICT :
					  STORE_REF_ERROR_OTHER;
D
Daniel Barkalow 已提交
388
	if (write_ref_sha1(lock, ref->new_sha1, msg) < 0)
389 390
		return errno == ENOTDIR ? STORE_REF_ERROR_DF_CONFLICT :
					  STORE_REF_ERROR_OTHER;
D
Daniel Barkalow 已提交
391 392 393
	return 0;
}

P
Pierre Habouzit 已提交
394
#define REFCOL_WIDTH  10
N
Nicolas Pitre 已提交
395

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

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

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

418 419
	if (current_branch &&
	    !strcmp(ref->name, current_branch->name) &&
D
Daniel Barkalow 已提交
420 421 422 423 424 425
	    !(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...
		 */
426 427
		strbuf_addf(display,
			    _("! %-*s %-*s -> %s  (can't fetch in current branch)"),
428
			    TRANSPORT_SUMMARY(_("[rejected]")),
429
			    REFCOL_WIDTH, remote, pretty_ref);
D
Daniel Barkalow 已提交
430 431 432 433 434
		return 1;
	}

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

445 446
	current = lookup_commit_reference_gently(ref->old_sha1, 1);
	updated = lookup_commit_reference_gently(ref->new_sha1, 1);
D
Daniel Barkalow 已提交
447
	if (!current || !updated) {
N
Nicolas Pitre 已提交
448 449
		const char *msg;
		const char *what;
450
		int r;
451 452 453 454 455 456 457
		/*
		 * 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 已提交
458
			msg = "storing tag";
459
			what = _("[new tag]");
460
		} else if (!prefixcmp(name, "refs/heads/")) {
D
Daniel Barkalow 已提交
461
			msg = "storing head";
462
			what = _("[new branch]");
463 464 465
		} else {
			msg = "storing ref";
			what = _("[new ref]");
N
Nicolas Pitre 已提交
466 467
		}

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

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

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

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

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

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

549 550 551 552
	if (raw_url)
		url = transport_anonymize_url(raw_url);
	else
		url = xstrdup("foreign");
553

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

560
	/*
J
Jeff King 已提交
561 562 563
	 * 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.
564
	 */
J
Jeff King 已提交
565 566 567
	for (want_status = FETCH_HEAD_MERGE;
	     want_status <= FETCH_HEAD_IGNORE;
	     want_status++) {
568 569
		for (rm = ref_map; rm; rm = rm->next) {
			struct ref *ref = NULL;
J
Jeff King 已提交
570
			const char *merge_status_marker = "";
571 572 573

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

J
Jeff King 已提交
576
			if (rm->fetch_head_status != want_status)
577 578 579 580 581 582 583 584 585
				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 已提交
586 587


588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607
			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 已提交
608

609 610 611 612 613 614 615 616 617 618 619 620 621
			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 已提交
622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641
			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;
			}
642 643 644

			strbuf_reset(&note);
			if (ref) {
645
				rc |= update_local_ref(ref, what, rm, &note);
646 647 648 649 650 651 652 653 654 655 656 657 658 659 660
				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 已提交
661 662
			}
		}
D
Daniel Barkalow 已提交
663
	}
664

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

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

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

686 687 688 689 690 691 692 693 694
	/*
	 * 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;
695
	return check_everything_connected(iterate_ref_map, 1, &rm);
696 697
}

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

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

	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",
724
				TRANSPORT_SUMMARY(_("[deleted]")),
725
				REFCOL_WIDTH, _("(none)"), prettify_refname(ref->name));
J
Jay Soffian 已提交
726 727 728 729 730 731 732
			warn_dangling_symref(stderr, dangling_msg, ref->name);
		}
	}
	free_refs(stale_refs);
	return result;
}

733 734 735 736 737 738 739 740 741 742
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))
743 744
			die(_("Refusing to fetch into current branch %s "
			    "of non-bare repository"), current_branch->refname);
745 746
}

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

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

758 759 760 761 762 763 764 765 766 767 768
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);
}

769
static struct transport *prepare_transport(struct remote *remote)
770 771 772 773 774 775 776 777 778 779 780 781 782
{
	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;
}

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

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

	if (gsecondary) {
		transport_disconnect(gsecondary);
		gsecondary = NULL;
	}
798 799
}

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

	for_each_ref(add_existing, &existing_refs);

811 812 813 814 815 816
	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 已提交
817

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

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

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

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

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

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

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

882 883 884
static int get_one_remote_for_fetch(struct remote *remote, void *priv)
{
	struct string_list *list = priv;
885
	if (!remote->skip_default_update)
886
		string_list_append(list, remote->name);
887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904
	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) {
905 906
				string_list_append(g->list,
						   xstrndup(value, space));
907 908 909 910 911 912 913 914 915 916 917 918
			}
			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;
919 920
	struct remote_group_data g;
	g.name = name; g.list = list;
921 922 923 924 925 926 927

	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);
928
		string_list_append(list, remote->name);
929 930 931 932
	}
	return 1;
}

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

}

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

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

973 974 975
	argv_array_pushl(&argv, "fetch", "--append", NULL);
	add_options_to_argv(&argv);

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

988
	argv_array_clear(&argv);
989 990 991 992
	return result;
}

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

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

1004
	gtransport = prepare_transport(remote);
1005 1006 1007

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

1016
	if (argc > 0) {
D
Daniel Barkalow 已提交
1017
		int j = 0;
1018
		refs = xcalloc(argc + 1, sizeof(const char *));
1019
		for (i = 0; i < argc; i++) {
D
Daniel Barkalow 已提交
1020 1021 1022
			if (!strcmp(argv[i], "tag")) {
				char *ref;
				i++;
1023
				if (i >= argc)
1024
					die(_("You need to specify a tag name."));
D
Daniel Barkalow 已提交
1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037
				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;
	}

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

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

J
Jeff King 已提交
1058 1059
	packet_trace_identity("fetch");

1060 1061 1062 1063 1064
	/* 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]);

1065 1066
	git_config(git_fetch_config, NULL);

1067 1068 1069
	argc = parse_options(argc, argv, prefix,
			     builtin_fetch_options, builtin_fetch_usage, 0);

1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081
	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;
		}
	}

1082 1083 1084 1085 1086 1087 1088 1089 1090
	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);
	}

1091 1092
	if (all) {
		if (argc == 1)
1093
			die(_("fetch --all does not take a repository argument"));
1094
		else if (argc > 1)
1095
			die(_("fetch --all does not make sense with refspecs"));
1096 1097 1098 1099 1100 1101
		(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);
1102 1103 1104 1105
	} 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))
1106
				die(_("No such remote or remote group: %s"), argv[i]);
1107
		result = fetch_multiple(&list);
1108 1109 1110 1111 1112 1113
	} else {
		/* Single remote or group */
		(void) add_remote_or_group(argv[0], &list);
		if (list.nr > 1) {
			/* More than one remote */
			if (argc > 1)
1114
				die(_("Fetching a group and specifying refspecs does not make sense"));
1115 1116 1117 1118 1119 1120 1121 1122
			result = fetch_multiple(&list);
		} else {
			/* Zero or one remotes */
			remote = remote_get(argv[0]);
			result = fetch_one(remote, argc-1, argv+1);
		}
	}

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

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

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

J
Jeff King 已提交
1138 1139
	run_command_v_opt(argv_gc_auto, RUN_GIT_CMD);

1140 1141
	return result;
}