fetch.c 31.1 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
	const struct ref *remote_refs = transport_get_remote_refs(transport);
D
Daniel Barkalow 已提交
273

274
	if (refspec_count || tags == TAGS_SET) {
275 276
		struct ref **old_tail;

277 278 279
		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 已提交
280 281 282 283
				*autotags = 1;
		}
		/* Merge everything on the command line, but not --tags */
		for (rm = ref_map; rm; rm = rm->next)
J
Jeff King 已提交
284
			rm->fetch_head_status = FETCH_HEAD_MERGE;
285 286
		if (tags == TAGS_SET)
			get_fetch_map(remote_refs, tag_refspec, &tail, 0);
287 288 289 290 291 292 293 294 295 296 297

		/*
		 * For any refs that we happen to be fetching via command-line
		 * arguments, take the opportunity to update their configured
		 * counterparts. However, we do not want to mention these
		 * entries in FETCH_HEAD at all, as they would simply be
		 * duplicates of existing entries.
		 */
		old_tail = tail;
		for (i = 0; i < transport->remote->fetch_refspec_nr; i++)
			get_fetch_map(ref_map, &transport->remote->fetch[i],
298
				      &tail, 1);
299 300
		for (rm = *old_tail; rm; rm = rm->next)
			rm->fetch_head_status = FETCH_HEAD_IGNORE;
D
Daniel Barkalow 已提交
301 302 303
	} else {
		/* Use the defaults */
		struct remote *remote = transport->remote;
304 305
		struct branch *branch = branch_get(NULL);
		int has_merge = branch_has_merge_config(branch);
306 307
		if (remote &&
		    (remote->fetch_refspec_nr ||
308
		     /* Note: has_merge implies non-NULL branch->remote_name */
309
		     (has_merge && !strcmp(branch->remote_name, remote->name)))) {
D
Daniel Barkalow 已提交
310
			for (i = 0; i < remote->fetch_refspec_nr; i++) {
311
				get_fetch_map(remote_refs, &remote->fetch[i], &tail, 0);
D
Daniel Barkalow 已提交
312 313 314
				if (remote->fetch[i].dst &&
				    remote->fetch[i].dst[0])
					*autotags = 1;
315
				if (!i && !has_merge && ref_map &&
316
				    !remote->fetch[0].pattern)
J
Jeff King 已提交
317
					ref_map->fetch_head_status = FETCH_HEAD_MERGE;
D
Daniel Barkalow 已提交
318
			}
319 320 321 322
			/*
			 * 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.
323 324
			 *
			 * Note: has_merge implies non-NULL branch->remote_name
325
			 */
326 327
			if (has_merge &&
			    !strcmp(branch->remote_name, remote->name))
328
				add_merge_config(&ref_map, remote_refs, branch, &tail);
D
Daniel Barkalow 已提交
329 330
		} else {
			ref_map = get_remote_ref(remote_refs, "HEAD");
331
			if (!ref_map)
332
				die(_("Couldn't find remote ref HEAD"));
J
Jeff King 已提交
333
			ref_map->fetch_head_status = FETCH_HEAD_MERGE;
334
			tail = &ref_map->next;
D
Daniel Barkalow 已提交
335 336
		}
	}
337 338
	if (tags == TAGS_DEFAULT && *autotags)
		find_non_local_tags(transport, &ref_map, &tail);
339
	ref_remove_duplicates(ref_map);
D
Daniel Barkalow 已提交
340 341 342 343

	return ref_map;
}

344 345 346
#define STORE_REF_ERROR_OTHER 1
#define STORE_REF_ERROR_DF_CONFLICT 2

D
Daniel Barkalow 已提交
347 348 349 350 351 352 353 354
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 已提交
355 356
	if (dry_run)
		return 0;
D
Daniel Barkalow 已提交
357
	if (!rla)
358
		rla = default_rla.buf;
D
Daniel Barkalow 已提交
359 360
	snprintf(msg, sizeof(msg), "%s: %s", rla, action);
	lock = lock_any_ref_for_update(ref->name,
361 362
				       check_old ? ref->old_sha1 : NULL,
				       0, NULL);
D
Daniel Barkalow 已提交
363
	if (!lock)
364 365
		return errno == ENOTDIR ? STORE_REF_ERROR_DF_CONFLICT :
					  STORE_REF_ERROR_OTHER;
D
Daniel Barkalow 已提交
366
	if (write_ref_sha1(lock, ref->new_sha1, msg) < 0)
367 368
		return errno == ENOTDIR ? STORE_REF_ERROR_DF_CONFLICT :
					  STORE_REF_ERROR_OTHER;
D
Daniel Barkalow 已提交
369 370 371
	return 0;
}

P
Pierre Habouzit 已提交
372
#define REFCOL_WIDTH  10
N
Nicolas Pitre 已提交
373

D
Daniel Barkalow 已提交
374
static int update_local_ref(struct ref *ref,
N
Nicolas Pitre 已提交
375
			    const char *remote,
376
			    const struct ref *remote_ref,
377
			    struct strbuf *display)
D
Daniel Barkalow 已提交
378 379 380 381
{
	struct commit *current = NULL, *updated;
	enum object_type type;
	struct branch *current_branch = branch_get(NULL);
382
	const char *pretty_ref = prettify_refname(ref->name);
D
Daniel Barkalow 已提交
383 384 385

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

	if (!hashcmp(ref->old_sha1, ref->new_sha1)) {
T
Tuncer Ayaz 已提交
389
		if (verbosity > 0)
390
			strbuf_addf(display, "= %-*s %-*s -> %s",
391 392
				    TRANSPORT_SUMMARY(_("[up to date]")),
				    REFCOL_WIDTH, remote, pretty_ref);
D
Daniel Barkalow 已提交
393 394 395
		return 0;
	}

396 397
	if (current_branch &&
	    !strcmp(ref->name, current_branch->name) &&
D
Daniel Barkalow 已提交
398 399 400 401 402 403
	    !(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...
		 */
404 405
		strbuf_addf(display,
			    _("! %-*s %-*s -> %s  (can't fetch in current branch)"),
406
			    TRANSPORT_SUMMARY(_("[rejected]")),
407
			    REFCOL_WIDTH, remote, pretty_ref);
D
Daniel Barkalow 已提交
408 409 410 411 412
		return 1;
	}

	if (!is_null_sha1(ref->old_sha1) &&
	    !prefixcmp(ref->name, "refs/tags/")) {
413 414
		int r;
		r = s_update_ref("updating tag", ref, 0);
415 416
		strbuf_addf(display, "%c %-*s %-*s -> %s%s",
			    r ? '!' : '-',
417
			    TRANSPORT_SUMMARY(_("[tag update]")),
418 419
			    REFCOL_WIDTH, remote, pretty_ref,
			    r ? _("  (unable to update local ref)") : "");
420
		return r;
D
Daniel Barkalow 已提交
421 422
	}

423 424
	current = lookup_commit_reference_gently(ref->old_sha1, 1);
	updated = lookup_commit_reference_gently(ref->new_sha1, 1);
D
Daniel Barkalow 已提交
425
	if (!current || !updated) {
N
Nicolas Pitre 已提交
426 427
		const char *msg;
		const char *what;
428
		int r;
429 430 431 432 433 434 435
		/*
		 * 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 已提交
436
			msg = "storing tag";
437
			what = _("[new tag]");
438
		} else if (!prefixcmp(name, "refs/heads/")) {
D
Daniel Barkalow 已提交
439
			msg = "storing head";
440
			what = _("[new branch]");
441 442 443
		} else {
			msg = "storing ref";
			what = _("[new ref]");
N
Nicolas Pitre 已提交
444 445
		}

446 447 448
		if ((recurse_submodules != RECURSE_SUBMODULES_OFF) &&
		    (recurse_submodules != RECURSE_SUBMODULES_ON))
			check_for_new_submodule_commits(ref->new_sha1);
449
		r = s_update_ref(msg, ref, 0);
450 451
		strbuf_addf(display, "%c %-*s %-*s -> %s%s",
			    r ? '!' : '*',
452
			    TRANSPORT_SUMMARY(what),
453 454
			    REFCOL_WIDTH, remote, pretty_ref,
			    r ? _("  (unable to update local ref)") : "");
455
		return r;
D
Daniel Barkalow 已提交
456 457
	}

458
	if (in_merge_bases(current, updated)) {
N
Nicolas Pitre 已提交
459
		char quickref[83];
460
		int r;
N
Nicolas Pitre 已提交
461 462 463
		strcpy(quickref, find_unique_abbrev(current->object.sha1, DEFAULT_ABBREV));
		strcat(quickref, "..");
		strcat(quickref, find_unique_abbrev(ref->new_sha1, DEFAULT_ABBREV));
464 465 466
		if ((recurse_submodules != RECURSE_SUBMODULES_OFF) &&
		    (recurse_submodules != RECURSE_SUBMODULES_ON))
			check_for_new_submodule_commits(ref->new_sha1);
467
		r = s_update_ref("fast-forward", ref, 1);
468 469 470 471 472
		strbuf_addf(display, "%c %-*s %-*s -> %s%s",
			    r ? '!' : ' ',
			    TRANSPORT_SUMMARY_WIDTH, quickref,
			    REFCOL_WIDTH, remote, pretty_ref,
			    r ? _("  (unable to update local ref)") : "");
473
		return r;
N
Nicolas Pitre 已提交
474 475
	} else if (force || ref->force) {
		char quickref[84];
476
		int r;
N
Nicolas Pitre 已提交
477 478 479
		strcpy(quickref, find_unique_abbrev(current->object.sha1, DEFAULT_ABBREV));
		strcat(quickref, "...");
		strcat(quickref, find_unique_abbrev(ref->new_sha1, DEFAULT_ABBREV));
480 481 482
		if ((recurse_submodules != RECURSE_SUBMODULES_OFF) &&
		    (recurse_submodules != RECURSE_SUBMODULES_ON))
			check_for_new_submodule_commits(ref->new_sha1);
483
		r = s_update_ref("forced-update", ref, 1);
484 485 486 487 488
		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"));
489
		return r;
N
Nicolas Pitre 已提交
490
	} else {
491
		strbuf_addf(display, "! %-*s %-*s -> %s  %s",
492
			    TRANSPORT_SUMMARY(_("[rejected]")),
493 494
			    REFCOL_WIDTH, remote, pretty_ref,
			    _("(non-fast-forward)"));
D
Daniel Barkalow 已提交
495 496 497 498
		return 1;
	}
}

499
static int iterate_ref_map(void *cb_data, unsigned char sha1[20])
500
{
501 502
	struct ref **rm = cb_data;
	struct ref *ref = *rm;
503

504 505 506 507 508
	if (!ref)
		return -1; /* end of the list */
	*rm = ref->next;
	hashcpy(sha1, ref->old_sha1);
	return 0;
509 510
}

511
static int store_updated_refs(const char *raw_url, const char *remote_name,
512
		struct ref *ref_map)
D
Daniel Barkalow 已提交
513 514 515
{
	FILE *fp;
	struct commit *commit;
516 517
	int url_len, i, shown_url = 0, rc = 0;
	struct strbuf note = STRBUF_INIT;
D
Daniel Barkalow 已提交
518 519
	const char *what, *kind;
	struct ref *rm;
J
Jay Soffian 已提交
520
	char *url, *filename = dry_run ? "/dev/null" : git_path("FETCH_HEAD");
J
Jeff King 已提交
521
	int want_status;
D
Daniel Barkalow 已提交
522

523 524
	fp = fopen(filename, "a");
	if (!fp)
525
		return error(_("cannot open %s: %s\n"), filename, strerror(errno));
526

527 528 529 530
	if (raw_url)
		url = transport_anonymize_url(raw_url);
	else
		url = xstrdup("foreign");
531

532
	rm = ref_map;
J
Junio C Hamano 已提交
533
	if (check_everything_connected(iterate_ref_map, 0, &rm)) {
534 535 536
		rc = error(_("%s did not send all necessary objects\n"), url);
		goto abort;
	}
537

538
	/*
J
Jeff King 已提交
539 540 541
	 * 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.
542
	 */
J
Jeff King 已提交
543 544 545
	for (want_status = FETCH_HEAD_MERGE;
	     want_status <= FETCH_HEAD_IGNORE;
	     want_status++) {
546 547
		for (rm = ref_map; rm; rm = rm->next) {
			struct ref *ref = NULL;
J
Jeff King 已提交
548
			const char *merge_status_marker = "";
549 550 551

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

J
Jeff King 已提交
554
			if (rm->fetch_head_status != want_status)
555 556 557 558 559 560 561 562 563
				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 已提交
564 565


566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585
			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 已提交
586

587 588 589 590 591 592 593 594 595 596 597 598 599
			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 已提交
600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619
			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;
			}
620 621 622

			strbuf_reset(&note);
			if (ref) {
623
				rc |= update_local_ref(ref, what, rm, &note);
624 625 626 627 628 629 630 631 632 633 634 635 636 637 638
				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 已提交
639 640
			}
		}
D
Daniel Barkalow 已提交
641
	}
642

643
	if (rc & STORE_REF_ERROR_DF_CONFLICT)
644
		error(_("some local refs could not be updated; try running\n"
645
		      " 'git remote prune %s' to remove any old, conflicting "
646
		      "branches"), remote_name);
647 648

 abort:
649
	strbuf_release(&note);
650 651
	free(url);
	fclose(fp);
652
	return rc;
D
Daniel Barkalow 已提交
653 654
}

655 656
/*
 * We would want to bypass the object transfer altogether if
657
 * everything we are going to fetch already exists and is connected
658 659 660 661
 * locally.
 */
static int quickfetch(struct ref *ref_map)
{
662 663
	struct ref *rm = ref_map;

664 665 666 667 668 669 670 671 672
	/*
	 * 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;
673
	return check_everything_connected(iterate_ref_map, 1, &rm);
674 675
}

D
Daniel Barkalow 已提交
676 677
static int fetch_refs(struct transport *transport, struct ref *ref_map)
{
678 679 680
	int ret = quickfetch(ref_map);
	if (ret)
		ret = transport_fetch_refs(transport, ref_map);
D
Daniel Barkalow 已提交
681
	if (!ret)
682 683 684
		ret |= store_updated_refs(transport->url,
				transport->remote->name,
				ref_map);
685
	transport_unlock_pack(transport);
D
Daniel Barkalow 已提交
686 687 688
	return ret;
}

689
static int prune_refs(struct refspec *refs, int ref_count, struct ref *ref_map)
J
Jay Soffian 已提交
690 691
{
	int result = 0;
692
	struct ref *ref, *stale_refs = get_stale_heads(refs, ref_count, ref_map);
J
Jay Soffian 已提交
693
	const char *dangling_msg = dry_run
694 695
		? _("   (%s will become dangling)")
		: _("   (%s has become dangling)");
J
Jay Soffian 已提交
696 697 698 699 700 701

	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",
702
				TRANSPORT_SUMMARY(_("[deleted]")),
703
				REFCOL_WIDTH, _("(none)"), prettify_refname(ref->name));
J
Jay Soffian 已提交
704 705 706 707 708 709 710
			warn_dangling_symref(stderr, dangling_msg, ref->name);
		}
	}
	free_refs(stale_refs);
	return result;
}

711 712 713 714 715 716 717 718 719 720
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))
721 722
			die(_("Refusing to fetch into current branch %s "
			    "of non-bare repository"), current_branch->refname);
723 724
}

725 726 727 728 729 730
static int truncate_fetch_head(void)
{
	char *filename = git_path("FETCH_HEAD");
	FILE *fp = fopen(filename, "w");

	if (!fp)
731
		return error(_("cannot open %s: %s\n"), filename, strerror(errno));
732 733 734 735
	fclose(fp);
	return 0;
}

736 737 738 739 740 741 742 743 744 745 746
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);
}

747
static struct transport *prepare_transport(struct remote *remote)
748 749 750 751 752 753 754 755 756 757 758 759 760
{
	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;
}

761 762
static void backfill_tags(struct transport *transport, struct ref *ref_map)
{
763 764 765 766 767
	if (transport->cannot_reuse) {
		gsecondary = prepare_transport(transport->remote);
		transport = gsecondary;
	}

768 769 770
	transport_set_option(transport, TRANS_OPT_FOLLOWTAGS, NULL);
	transport_set_option(transport, TRANS_OPT_DEPTH, "0");
	fetch_refs(transport, ref_map);
771 772 773 774 775

	if (gsecondary) {
		transport_disconnect(gsecondary);
		gsecondary = NULL;
	}
776 777
}

D
Daniel Barkalow 已提交
778 779 780
static int do_fetch(struct transport *transport,
		    struct refspec *refs, int ref_count)
{
781
	struct string_list existing_refs = STRING_LIST_INIT_DUP;
782
	struct ref *ref_map;
D
Daniel Barkalow 已提交
783 784
	struct ref *rm;
	int autotags = (transport->remote->fetch_tags == 1);
785
	int retcode = 0;
786 787 788

	for_each_ref(add_existing, &existing_refs);

789 790 791 792 793 794
	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 已提交
795

796
	if (!transport->get_refs_list || !transport->fetch)
797
		die(_("Don't know how to fetch from %s"), transport->url);
D
Daniel Barkalow 已提交
798 799

	/* if not appending, truncate FETCH_HEAD */
J
Jay Soffian 已提交
800
	if (!append && !dry_run) {
801 802 803
		retcode = truncate_fetch_head();
		if (retcode)
			goto cleanup;
804
	}
D
Daniel Barkalow 已提交
805 806

	ref_map = get_ref_map(transport, refs, ref_count, tags, &autotags);
807 808
	if (!update_head_ok)
		check_not_current_branch(ref_map);
D
Daniel Barkalow 已提交
809 810

	for (rm = ref_map; rm; rm = rm->next) {
811
		if (rm->peer_ref) {
812 813 814
			struct string_list_item *peer_item =
				string_list_lookup(&existing_refs,
						   rm->peer_ref->name);
815 816 817 818
			if (peer_item)
				hashcpy(rm->peer_ref->old_sha1,
					peer_item->util);
		}
D
Daniel Barkalow 已提交
819 820
	}

821 822
	if (tags == TAGS_DEFAULT && autotags)
		transport_set_option(transport, TRANS_OPT_FOLLOWTAGS, "1");
D
Daniel Barkalow 已提交
823 824
	if (fetch_refs(transport, ref_map)) {
		free_refs(ref_map);
825 826
		retcode = 1;
		goto cleanup;
D
Daniel Barkalow 已提交
827
	}
828
	if (prune) {
829 830 831 832
		/*
		 * If --tags was specified, pretend that the user gave us
		 * the canonical tags refspec
		 */
833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850
		if (tags == TAGS_SET) {
			const char *tags_str = "refs/tags/*:refs/tags/*";
			struct refspec *tags_refspec, *refspec;

			/* Copy the refspec and add the tags to it */
			refspec = xcalloc(ref_count + 1, sizeof(struct refspec));
			tags_refspec = parse_fetch_refspec(1, &tags_str);
			memcpy(refspec, refs, ref_count * sizeof(struct refspec));
			memcpy(&refspec[ref_count], tags_refspec, sizeof(struct refspec));
			ref_count++;

			prune_refs(refspec, ref_count, ref_map);

			ref_count--;
			/* The rest of the strings belong to fetch_one */
			free_refspec(1, tags_refspec);
			free(refspec);
		} else if (ref_count) {
851
			prune_refs(refs, ref_count, ref_map);
852
		} else {
853
			prune_refs(transport->remote->fetch, transport->remote->fetch_refspec_nr, ref_map);
854
		}
855
	}
856
	free_refs(ref_map);
D
Daniel Barkalow 已提交
857 858 859

	/* if neither --no-tags nor --tags was specified, do automated tag
	 * following ... */
860
	if (tags == TAGS_DEFAULT && autotags) {
861 862 863
		struct ref **tail = &ref_map;
		ref_map = NULL;
		find_non_local_tags(transport, &ref_map, &tail);
864 865
		if (ref_map)
			backfill_tags(transport, ref_map);
D
Daniel Barkalow 已提交
866 867 868
		free_refs(ref_map);
	}

869
 cleanup:
870
	string_list_clear(&existing_refs, 1);
871
	return retcode;
D
Daniel Barkalow 已提交
872 873
}

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

	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);
920
		string_list_append(list, remote->name);
921 922 923 924
	}
	return 1;
}

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

}

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

959 960 961 962 963 964
	if (!append && !dry_run) {
		int errcode = truncate_fetch_head();
		if (errcode)
			return errcode;
	}

965 966 967
	argv_array_pushl(&argv, "fetch", "--append", NULL);
	add_options_to_argv(&argv);

968 969
	for (i = 0; i < list->nr; i++) {
		const char *name = list->items[i].string;
970
		argv_array_push(&argv, name);
971
		if (verbosity >= 0)
972
			printf(_("Fetching %s\n"), name);
973
		if (run_command_v_opt(argv.argv, RUN_GIT_CMD)) {
974
			error(_("Could not fetch %s"), name);
975 976
			result = 1;
		}
977
		argv_array_pop(&argv);
978 979
	}

980
	argv_array_clear(&argv);
981 982 983 984
	return result;
}

static int fetch_one(struct remote *remote, int argc, const char **argv)
D
Daniel Barkalow 已提交
985
{
986
	int i;
D
Daniel Barkalow 已提交
987
	static const char **refs = NULL;
J
Jim Meyering 已提交
988
	struct refspec *refspec;
D
Daniel Barkalow 已提交
989
	int ref_nr = 0;
990
	int exit_code;
D
Daniel Barkalow 已提交
991

992
	if (!remote)
993 994
		die(_("No remote repository specified.  Please, specify either a URL or a\n"
		    "remote name from which new revisions should be fetched."));
995

996
	gtransport = prepare_transport(remote);
997 998 999

	if (prune < 0) {
		/* no command line request */
1000 1001
		if (0 <= gtransport->remote->prune)
			prune = gtransport->remote->prune;
1002 1003 1004 1005 1006 1007
		else if (0 <= fetch_prune_config)
			prune = fetch_prune_config;
		else
			prune = PRUNE_BY_DEFAULT;
	}

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

1030
	sigchain_push_common(unlock_pack_on_signal);
1031
	atexit(unlock_pack);
J
Jim Meyering 已提交
1032
	refspec = parse_fetch_refspec(ref_nr, refs);
1033
	exit_code = do_fetch(gtransport, refspec, ref_nr);
1034
	free_refspec(ref_nr, refspec);
1035 1036
	transport_disconnect(gtransport);
	gtransport = NULL;
1037
	return exit_code;
D
Daniel Barkalow 已提交
1038
}
1039 1040 1041 1042

int cmd_fetch(int argc, const char **argv, const char *prefix)
{
	int i;
1043
	struct string_list list = STRING_LIST_INIT_NODUP;
1044 1045
	struct remote *remote;
	int result = 0;
J
Jeff King 已提交
1046 1047 1048
	static const char *argv_gc_auto[] = {
		"gc", "--auto", NULL,
	};
1049

J
Jeff King 已提交
1050 1051
	packet_trace_identity("fetch");

1052 1053 1054 1055 1056
	/* 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]);

1057 1058
	git_config(git_fetch_config, NULL);

1059 1060 1061
	argc = parse_options(argc, argv, prefix,
			     builtin_fetch_options, builtin_fetch_usage, 0);

1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073
	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;
		}
	}

1074 1075 1076 1077 1078 1079 1080 1081 1082
	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);
	}

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

1115
	if (!result && (recurse_submodules != RECURSE_SUBMODULES_OFF)) {
1116 1117 1118
		struct argv_array options = ARGV_ARRAY_INIT;

		add_options_to_argv(&options);
1119
		result = fetch_populated_submodules(&options,
1120
						    submodule_prefix,
1121
						    recurse_submodules,
1122
						    verbosity < 0);
1123
		argv_array_clear(&options);
1124 1125
	}

1126 1127 1128 1129
	/* All names were strdup()ed or strndup()ed */
	list.strdup_strings = 1;
	string_list_clear(&list, 0);

J
Jeff King 已提交
1130 1131
	run_command_v_opt(argv_gc_auto, RUN_GIT_CMD);

1132 1133
	return result;
}