fetch.c 28.8 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
};

J
Jay Soffian 已提交
33
static int all, append, dry_run, force, keep, multiple, prune, update_head_ok, verbosity;
34
static int progress = -1, recurse_submodules = RECURSE_SUBMODULES_DEFAULT;
35
static int tags = TAGS_DEFAULT, unshallow;
36
static const char *depth;
37
static const char *upload_pack;
38
static struct strbuf default_rla = STRBUF_INIT;
39
static struct transport *transport;
40
static const char *submodule_prefix = "";
41
static const char *recurse_submodules_default;
42

43 44 45 46 47 48 49 50 51 52 53 54 55
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;
}
56

57
static struct option builtin_fetch_options[] = {
T
Tuncer Ayaz 已提交
58
	OPT__VERBOSITY(&verbosity),
59
	OPT_BOOLEAN(0, "all", &all,
60
		    N_("fetch from all remotes")),
61
	OPT_BOOLEAN('a', "append", &append,
62 63 64 65
		    N_("append to .git/FETCH_HEAD instead of overwriting")),
	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")),
66
	OPT_BOOLEAN('m', "multiple", &multiple,
67
		    N_("fetch from multiple remotes")),
68
	OPT_SET_INT('t', "tags", &tags,
69
		    N_("fetch all tags and associated objects"), TAGS_SET),
70
	OPT_SET_INT('n', NULL, &tags,
71
		    N_("do not fetch all tags (--no-tags)"), TAGS_UNSET),
J
Jay Soffian 已提交
72
	OPT_BOOLEAN('p', "prune", &prune,
73 74 75
		    N_("prune remote-tracking branches no longer on remote")),
	{ OPTION_CALLBACK, 0, "recurse-submodules", NULL, N_("on-demand"),
		    N_("control recursive fetching of submodules"),
76
		    PARSE_OPT_OPTARG, option_parse_recurse_submodules },
J
Jay Soffian 已提交
77
	OPT_BOOLEAN(0, "dry-run", &dry_run,
78 79
		    N_("dry run")),
	OPT_BOOLEAN('k', "keep", &keep, N_("keep downloaded pack")),
80
	OPT_BOOLEAN('u', "update-head-ok", &update_head_ok,
81 82 83 84
		    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")),
85 86 87
	{ OPTION_SET_INT, 0, "unshallow", &unshallow, NULL,
		   N_("convert to a complete repository"),
		   PARSE_OPT_NONEG | PARSE_OPT_NOARG, NULL, 1 },
88 89
	{ OPTION_STRING, 0, "submodule-prefix", &submodule_prefix, N_("dir"),
		   N_("prepend this to submodule path output"), PARSE_OPT_HIDDEN },
90 91
	{ OPTION_STRING, 0, "recurse-submodules-default",
		   &recurse_submodules_default, NULL,
92
		   N_("default mode for recursion"), PARSE_OPT_HIDDEN },
93 94 95
	OPT_END()
};

96 97 98 99 100 101 102 103 104
static void unlock_pack(void)
{
	if (transport)
		transport_unlock_pack(transport);
}

static void unlock_pack_on_signal(int signo)
{
	unlock_pack();
105
	sigchain_pop(signo);
106 107
	raise(signo);
}
D
Daniel Barkalow 已提交
108

109
static void add_merge_config(struct ref **head,
110
			   const struct ref *remote_refs,
111 112
		           struct branch *branch,
		           struct ref ***tail)
D
Daniel Barkalow 已提交
113
{
114
	int i;
D
Daniel Barkalow 已提交
115

116 117 118 119 120 121
	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)) {
D
Daniel Barkalow 已提交
122
				rm->merge = 1;
123 124
				break;
			}
D
Daniel Barkalow 已提交
125
		}
126 127 128
		if (rm)
			continue;

129
		/*
130
		 * Not fetched to a remote-tracking branch?  We need to fetch
131
		 * it anyway to allow this branch's "branch.$name.merge"
132
		 * to be honored by 'git pull', but we do not have to
133 134
		 * fail if branch.$name.merge is misconfigured to point
		 * at a nonexisting branch.  If we were indeed called by
135
		 * 'git pull', it will notice the misconfiguration because
136 137
		 * there is no entry in the resulting FETCH_HEAD marked
		 * for merging.
138
		 */
139
		memset(&refspec, 0, sizeof(refspec));
140
		refspec.src = branch->merge[i]->src;
141
		get_fetch_map(remote_refs, &refspec, tail, 1);
142 143
		for (rm = *old_tail; rm; rm = rm->next)
			rm->merge = 1;
D
Daniel Barkalow 已提交
144 145 146
	}
}

147 148 149 150
static void find_non_local_tags(struct transport *transport,
			struct ref **head,
			struct ref ***tail);

D
Daniel Barkalow 已提交
151 152 153 154 155 156 157 158 159
static struct ref *get_ref_map(struct transport *transport,
			       struct refspec *refs, int ref_count, int tags,
			       int *autotags)
{
	int i;
	struct ref *rm;
	struct ref *ref_map = NULL;
	struct ref **tail = &ref_map;

160
	const struct ref *remote_refs = transport_get_remote_refs(transport);
D
Daniel Barkalow 已提交
161

162
	if (ref_count || tags == TAGS_SET) {
D
Daniel Barkalow 已提交
163
		for (i = 0; i < ref_count; i++) {
164
			get_fetch_map(remote_refs, &refs[i], &tail, 0);
D
Daniel Barkalow 已提交
165 166 167 168 169 170
			if (refs[i].dst && refs[i].dst[0])
				*autotags = 1;
		}
		/* Merge everything on the command line, but not --tags */
		for (rm = ref_map; rm; rm = rm->next)
			rm->merge = 1;
171 172
		if (tags == TAGS_SET)
			get_fetch_map(remote_refs, tag_refspec, &tail, 0);
D
Daniel Barkalow 已提交
173 174 175
	} else {
		/* Use the defaults */
		struct remote *remote = transport->remote;
176 177
		struct branch *branch = branch_get(NULL);
		int has_merge = branch_has_merge_config(branch);
178 179
		if (remote &&
		    (remote->fetch_refspec_nr ||
180
		     /* Note: has_merge implies non-NULL branch->remote_name */
181
		     (has_merge && !strcmp(branch->remote_name, remote->name)))) {
D
Daniel Barkalow 已提交
182
			for (i = 0; i < remote->fetch_refspec_nr; i++) {
183
				get_fetch_map(remote_refs, &remote->fetch[i], &tail, 0);
D
Daniel Barkalow 已提交
184 185 186
				if (remote->fetch[i].dst &&
				    remote->fetch[i].dst[0])
					*autotags = 1;
187
				if (!i && !has_merge && ref_map &&
188
				    !remote->fetch[0].pattern)
189
					ref_map->merge = 1;
D
Daniel Barkalow 已提交
190
			}
191 192 193 194
			/*
			 * 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.
195 196
			 *
			 * Note: has_merge implies non-NULL branch->remote_name
197
			 */
198 199
			if (has_merge &&
			    !strcmp(branch->remote_name, remote->name))
200
				add_merge_config(&ref_map, remote_refs, branch, &tail);
D
Daniel Barkalow 已提交
201 202
		} else {
			ref_map = get_remote_ref(remote_refs, "HEAD");
203
			if (!ref_map)
204
				die(_("Couldn't find remote ref HEAD"));
D
Daniel Barkalow 已提交
205
			ref_map->merge = 1;
206
			tail = &ref_map->next;
D
Daniel Barkalow 已提交
207 208
		}
	}
209 210
	if (tags == TAGS_DEFAULT && *autotags)
		find_non_local_tags(transport, &ref_map, &tail);
211
	ref_remove_duplicates(ref_map);
D
Daniel Barkalow 已提交
212 213 214 215

	return ref_map;
}

216 217 218
#define STORE_REF_ERROR_OTHER 1
#define STORE_REF_ERROR_DF_CONFLICT 2

D
Daniel Barkalow 已提交
219 220 221 222 223 224 225 226
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 已提交
227 228
	if (dry_run)
		return 0;
D
Daniel Barkalow 已提交
229
	if (!rla)
230
		rla = default_rla.buf;
D
Daniel Barkalow 已提交
231 232 233 234
	snprintf(msg, sizeof(msg), "%s: %s", rla, action);
	lock = lock_any_ref_for_update(ref->name,
				       check_old ? ref->old_sha1 : NULL, 0);
	if (!lock)
235 236
		return errno == ENOTDIR ? STORE_REF_ERROR_DF_CONFLICT :
					  STORE_REF_ERROR_OTHER;
D
Daniel Barkalow 已提交
237
	if (write_ref_sha1(lock, ref->new_sha1, msg) < 0)
238 239
		return errno == ENOTDIR ? STORE_REF_ERROR_DF_CONFLICT :
					  STORE_REF_ERROR_OTHER;
D
Daniel Barkalow 已提交
240 241 242
	return 0;
}

P
Pierre Habouzit 已提交
243
#define REFCOL_WIDTH  10
N
Nicolas Pitre 已提交
244

D
Daniel Barkalow 已提交
245
static int update_local_ref(struct ref *ref,
N
Nicolas Pitre 已提交
246
			    const char *remote,
247
			    const struct ref *remote_ref,
248
			    struct strbuf *display)
D
Daniel Barkalow 已提交
249 250 251 252
{
	struct commit *current = NULL, *updated;
	enum object_type type;
	struct branch *current_branch = branch_get(NULL);
253
	const char *pretty_ref = prettify_refname(ref->name);
D
Daniel Barkalow 已提交
254 255 256

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

	if (!hashcmp(ref->old_sha1, ref->new_sha1)) {
T
Tuncer Ayaz 已提交
260
		if (verbosity > 0)
261
			strbuf_addf(display, "= %-*s %-*s -> %s",
262 263
				    TRANSPORT_SUMMARY(_("[up to date]")),
				    REFCOL_WIDTH, remote, pretty_ref);
D
Daniel Barkalow 已提交
264 265 266
		return 0;
	}

267 268
	if (current_branch &&
	    !strcmp(ref->name, current_branch->name) &&
D
Daniel Barkalow 已提交
269 270 271 272 273 274
	    !(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...
		 */
275 276
		strbuf_addf(display,
			    _("! %-*s %-*s -> %s  (can't fetch in current branch)"),
277
			    TRANSPORT_SUMMARY(_("[rejected]")),
278
			    REFCOL_WIDTH, remote, pretty_ref);
D
Daniel Barkalow 已提交
279 280 281 282 283
		return 1;
	}

	if (!is_null_sha1(ref->old_sha1) &&
	    !prefixcmp(ref->name, "refs/tags/")) {
284 285
		int r;
		r = s_update_ref("updating tag", ref, 0);
286 287
		strbuf_addf(display, "%c %-*s %-*s -> %s%s",
			    r ? '!' : '-',
288
			    TRANSPORT_SUMMARY(_("[tag update]")),
289 290
			    REFCOL_WIDTH, remote, pretty_ref,
			    r ? _("  (unable to update local ref)") : "");
291
		return r;
D
Daniel Barkalow 已提交
292 293
	}

294 295
	current = lookup_commit_reference_gently(ref->old_sha1, 1);
	updated = lookup_commit_reference_gently(ref->new_sha1, 1);
D
Daniel Barkalow 已提交
296
	if (!current || !updated) {
N
Nicolas Pitre 已提交
297 298
		const char *msg;
		const char *what;
299
		int r;
300 301 302 303 304 305 306
		/*
		 * 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 已提交
307
			msg = "storing tag";
308
			what = _("[new tag]");
309
		} else if (!prefixcmp(name, "refs/heads/")) {
D
Daniel Barkalow 已提交
310
			msg = "storing head";
311
			what = _("[new branch]");
312 313 314
		} else {
			msg = "storing ref";
			what = _("[new ref]");
N
Nicolas Pitre 已提交
315 316
		}

317 318 319
		if ((recurse_submodules != RECURSE_SUBMODULES_OFF) &&
		    (recurse_submodules != RECURSE_SUBMODULES_ON))
			check_for_new_submodule_commits(ref->new_sha1);
320
		r = s_update_ref(msg, ref, 0);
321 322
		strbuf_addf(display, "%c %-*s %-*s -> %s%s",
			    r ? '!' : '*',
323
			    TRANSPORT_SUMMARY(what),
324 325
			    REFCOL_WIDTH, remote, pretty_ref,
			    r ? _("  (unable to update local ref)") : "");
326
		return r;
D
Daniel Barkalow 已提交
327 328
	}

329
	if (in_merge_bases(current, updated)) {
N
Nicolas Pitre 已提交
330
		char quickref[83];
331
		int r;
N
Nicolas Pitre 已提交
332 333 334
		strcpy(quickref, find_unique_abbrev(current->object.sha1, DEFAULT_ABBREV));
		strcat(quickref, "..");
		strcat(quickref, find_unique_abbrev(ref->new_sha1, DEFAULT_ABBREV));
335 336 337
		if ((recurse_submodules != RECURSE_SUBMODULES_OFF) &&
		    (recurse_submodules != RECURSE_SUBMODULES_ON))
			check_for_new_submodule_commits(ref->new_sha1);
338
		r = s_update_ref("fast-forward", ref, 1);
339 340 341 342 343
		strbuf_addf(display, "%c %-*s %-*s -> %s%s",
			    r ? '!' : ' ',
			    TRANSPORT_SUMMARY_WIDTH, quickref,
			    REFCOL_WIDTH, remote, pretty_ref,
			    r ? _("  (unable to update local ref)") : "");
344
		return r;
N
Nicolas Pitre 已提交
345 346
	} else if (force || ref->force) {
		char quickref[84];
347
		int r;
N
Nicolas Pitre 已提交
348 349 350
		strcpy(quickref, find_unique_abbrev(current->object.sha1, DEFAULT_ABBREV));
		strcat(quickref, "...");
		strcat(quickref, find_unique_abbrev(ref->new_sha1, DEFAULT_ABBREV));
351 352 353
		if ((recurse_submodules != RECURSE_SUBMODULES_OFF) &&
		    (recurse_submodules != RECURSE_SUBMODULES_ON))
			check_for_new_submodule_commits(ref->new_sha1);
354
		r = s_update_ref("forced-update", ref, 1);
355 356 357 358 359
		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"));
360
		return r;
N
Nicolas Pitre 已提交
361
	} else {
362
		strbuf_addf(display, "! %-*s %-*s -> %s  %s",
363
			    TRANSPORT_SUMMARY(_("[rejected]")),
364 365
			    REFCOL_WIDTH, remote, pretty_ref,
			    _("(non-fast-forward)"));
D
Daniel Barkalow 已提交
366 367 368 369
		return 1;
	}
}

370
static int iterate_ref_map(void *cb_data, unsigned char sha1[20])
371
{
372 373
	struct ref **rm = cb_data;
	struct ref *ref = *rm;
374

375 376 377 378 379
	if (!ref)
		return -1; /* end of the list */
	*rm = ref->next;
	hashcpy(sha1, ref->old_sha1);
	return 0;
380 381
}

382
static int store_updated_refs(const char *raw_url, const char *remote_name,
383
		struct ref *ref_map)
D
Daniel Barkalow 已提交
384 385 386
{
	FILE *fp;
	struct commit *commit;
387 388
	int url_len, i, shown_url = 0, rc = 0;
	struct strbuf note = STRBUF_INIT;
D
Daniel Barkalow 已提交
389 390
	const char *what, *kind;
	struct ref *rm;
J
Jay Soffian 已提交
391
	char *url, *filename = dry_run ? "/dev/null" : git_path("FETCH_HEAD");
392
	int want_merge;
D
Daniel Barkalow 已提交
393

394 395
	fp = fopen(filename, "a");
	if (!fp)
396
		return error(_("cannot open %s: %s\n"), filename, strerror(errno));
397

398 399 400 401
	if (raw_url)
		url = transport_anonymize_url(raw_url);
	else
		url = xstrdup("foreign");
402

403
	rm = ref_map;
J
Junio C Hamano 已提交
404
	if (check_everything_connected(iterate_ref_map, 0, &rm)) {
405 406 407
		rc = error(_("%s did not send all necessary objects\n"), url);
		goto abort;
	}
408

409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431
	/*
	 * The first pass writes objects to be merged and then the
	 * second pass writes the rest, in order to allow using
	 * FETCH_HEAD as a refname to refer to the ref to be merged.
	 */
	for (want_merge = 1; 0 <= want_merge; want_merge--) {
		for (rm = ref_map; rm; rm = rm->next) {
			struct ref *ref = NULL;

			commit = lookup_commit_reference_gently(rm->old_sha1, 1);
			if (!commit)
				rm->merge = 0;

			if (rm->merge != want_merge)
				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 已提交
432 433


434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453
			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 已提交
454

455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480
			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);
			}
			fprintf(fp, "%s\t%s\t%s",
				sha1_to_hex(rm->old_sha1),
				rm->merge ? "" : "not-for-merge",
				note.buf);
			for (i = 0; i < url_len; ++i)
				if ('\n' == url[i])
					fputs("\\n", fp);
				else
					fputc(url[i], fp);
			fputc('\n', fp);

			strbuf_reset(&note);
			if (ref) {
481
				rc |= update_local_ref(ref, what, rm, &note);
482 483 484 485 486 487 488 489 490 491 492 493 494 495 496
				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 已提交
497 498
			}
		}
D
Daniel Barkalow 已提交
499
	}
500

501
	if (rc & STORE_REF_ERROR_DF_CONFLICT)
502
		error(_("some local refs could not be updated; try running\n"
503
		      " 'git remote prune %s' to remove any old, conflicting "
504
		      "branches"), remote_name);
505 506

 abort:
507
	strbuf_release(&note);
508 509
	free(url);
	fclose(fp);
510
	return rc;
D
Daniel Barkalow 已提交
511 512
}

513 514
/*
 * We would want to bypass the object transfer altogether if
515
 * everything we are going to fetch already exists and is connected
516 517 518 519
 * locally.
 */
static int quickfetch(struct ref *ref_map)
{
520 521
	struct ref *rm = ref_map;

522 523 524 525 526 527 528 529 530
	/*
	 * 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;
531
	return check_everything_connected(iterate_ref_map, 1, &rm);
532 533
}

D
Daniel Barkalow 已提交
534 535
static int fetch_refs(struct transport *transport, struct ref *ref_map)
{
536 537 538
	int ret = quickfetch(ref_map);
	if (ret)
		ret = transport_fetch_refs(transport, ref_map);
D
Daniel Barkalow 已提交
539
	if (!ret)
540 541 542
		ret |= store_updated_refs(transport->url,
				transport->remote->name,
				ref_map);
543
	transport_unlock_pack(transport);
D
Daniel Barkalow 已提交
544 545 546
	return ret;
}

547
static int prune_refs(struct refspec *refs, int ref_count, struct ref *ref_map)
J
Jay Soffian 已提交
548 549
{
	int result = 0;
550
	struct ref *ref, *stale_refs = get_stale_heads(refs, ref_count, ref_map);
J
Jay Soffian 已提交
551
	const char *dangling_msg = dry_run
552 553
		? _("   (%s will become dangling)")
		: _("   (%s has become dangling)");
J
Jay Soffian 已提交
554 555 556 557 558 559

	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",
560
				TRANSPORT_SUMMARY(_("[deleted]")),
561
				REFCOL_WIDTH, _("(none)"), prettify_refname(ref->name));
J
Jay Soffian 已提交
562 563 564 565 566 567 568
			warn_dangling_symref(stderr, dangling_msg, ref->name);
		}
	}
	free_refs(stale_refs);
	return result;
}

D
Daniel Barkalow 已提交
569 570 571
static int add_existing(const char *refname, const unsigned char *sha1,
			int flag, void *cbdata)
{
572
	struct string_list *list = (struct string_list *)cbdata;
573
	struct string_list_item *item = string_list_insert(list, refname);
574
	item->util = (void *)sha1;
D
Daniel Barkalow 已提交
575 576 577
	return 0;
}

578 579 580 581 582 583 584 585 586 587 588
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;
}

589 590 591
static void find_non_local_tags(struct transport *transport,
			struct ref **head,
			struct ref ***tail)
D
Daniel Barkalow 已提交
592
{
593 594
	struct string_list existing_refs = STRING_LIST_INIT_NODUP;
	struct string_list remote_refs = STRING_LIST_INIT_NODUP;
595
	const struct ref *ref;
596
	struct string_list_item *item = NULL;
D
Daniel Barkalow 已提交
597 598 599

	for_each_ref(add_existing, &existing_refs);
	for (ref = transport_get_remote_refs(transport); ref; ref = ref->next) {
600
		if (prefixcmp(ref->name, "refs/tags/"))
D
Daniel Barkalow 已提交
601 602
			continue;

603 604 605 606 607 608
		/*
		 * 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.
		 */
609
		if (!suffixcmp(ref->name, "^{}")) {
610 611 612 613 614 615 616
			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;
D
Daniel Barkalow 已提交
617 618
		}

619 620 621 622 623 624 625 626 627
		/*
		 * 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;
D
Daniel Barkalow 已提交
628

629
		item = NULL;
D
Daniel Barkalow 已提交
630

631 632 633 634 635
		/* 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;

636
		item = string_list_insert(&remote_refs, ref->name);
637
		item->util = (void *)ref->old_sha1;
D
Daniel Barkalow 已提交
638
	}
639
	string_list_clear(&existing_refs, 0);
640 641 642 643 644 645 646 647 648 649

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

	/*
650 651
	 * For all the tags in the remote_refs string list,
	 * add them to the list of refs to be fetched
652
	 */
653 654 655 656 657 658 659 660 661 662 663
	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;
		}
	}
664 665

	string_list_clear(&remote_refs, 0);
D
Daniel Barkalow 已提交
666 667
}

668 669 670 671 672 673 674 675 676 677
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))
678 679
			die(_("Refusing to fetch into current branch %s "
			    "of non-bare repository"), current_branch->refname);
680 681
}

682 683 684 685 686 687
static int truncate_fetch_head(void)
{
	char *filename = git_path("FETCH_HEAD");
	FILE *fp = fopen(filename, "w");

	if (!fp)
688
		return error(_("cannot open %s: %s\n"), filename, strerror(errno));
689 690 691 692
	fclose(fp);
	return 0;
}

D
Daniel Barkalow 已提交
693 694 695
static int do_fetch(struct transport *transport,
		    struct refspec *refs, int ref_count)
{
696
	struct string_list existing_refs = STRING_LIST_INIT_NODUP;
697
	struct string_list_item *peer_item = NULL;
698
	struct ref *ref_map;
D
Daniel Barkalow 已提交
699 700
	struct ref *rm;
	int autotags = (transport->remote->fetch_tags == 1);
701 702 703

	for_each_ref(add_existing, &existing_refs);

704 705 706 707 708 709
	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 已提交
710

711
	if (!transport->get_refs_list || !transport->fetch)
712
		die(_("Don't know how to fetch from %s"), transport->url);
D
Daniel Barkalow 已提交
713 714

	/* if not appending, truncate FETCH_HEAD */
J
Jay Soffian 已提交
715
	if (!append && !dry_run) {
716 717 718
		int errcode = truncate_fetch_head();
		if (errcode)
			return errcode;
719
	}
D
Daniel Barkalow 已提交
720 721

	ref_map = get_ref_map(transport, refs, ref_count, tags, &autotags);
722 723
	if (!update_head_ok)
		check_not_current_branch(ref_map);
D
Daniel Barkalow 已提交
724 725

	for (rm = ref_map; rm; rm = rm->next) {
726
		if (rm->peer_ref) {
727 728
			peer_item = string_list_lookup(&existing_refs,
						       rm->peer_ref->name);
729 730 731 732
			if (peer_item)
				hashcpy(rm->peer_ref->old_sha1,
					peer_item->util);
		}
D
Daniel Barkalow 已提交
733 734
	}

735 736
	if (tags == TAGS_DEFAULT && autotags)
		transport_set_option(transport, TRANS_OPT_FOLLOWTAGS, "1");
D
Daniel Barkalow 已提交
737 738 739 740
	if (fetch_refs(transport, ref_map)) {
		free_refs(ref_map);
		return 1;
	}
741
	if (prune) {
742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760
		/* If --tags was specified, pretend the user gave us the canonical tags refspec */
		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) {
761
			prune_refs(refs, ref_count, ref_map);
762
		} else {
763
			prune_refs(transport->remote->fetch, transport->remote->fetch_refspec_nr, ref_map);
764
		}
765
	}
766
	free_refs(ref_map);
D
Daniel Barkalow 已提交
767 768 769

	/* if neither --no-tags nor --tags was specified, do automated tag
	 * following ... */
770
	if (tags == TAGS_DEFAULT && autotags) {
771 772 773
		struct ref **tail = &ref_map;
		ref_map = NULL;
		find_non_local_tags(transport, &ref_map, &tail);
D
Daniel Barkalow 已提交
774
		if (ref_map) {
775
			transport_set_option(transport, TRANS_OPT_FOLLOWTAGS, NULL);
D
Daniel Barkalow 已提交
776 777 778 779 780 781 782 783 784
			transport_set_option(transport, TRANS_OPT_DEPTH, "0");
			fetch_refs(transport, ref_map);
		}
		free_refs(ref_map);
	}

	return 0;
}

785 786 787 788
static void set_option(const char *name, const char *value)
{
	int r = transport_set_option(transport, name, value);
	if (r < 0)
789
		die(_("Option \"%s\" value \"%s\" is not valid for %s"),
790 791
			name, value, transport->url);
	if (r > 0)
792
		warning(_("Option \"%s\" is ignored for %s\n"),
793 794 795
			name, transport->url);
}

796 797 798
static int get_one_remote_for_fetch(struct remote *remote, void *priv)
{
	struct string_list *list = priv;
799
	if (!remote->skip_default_update)
800
		string_list_append(list, remote->name);
801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818
	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) {
819 820
				string_list_append(g->list,
						   xstrndup(value, space));
821 822 823 824 825 826 827 828 829 830 831 832
			}
			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;
833 834
	struct remote_group_data g;
	g.name = name; g.list = list;
835 836 837 838 839 840 841

	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);
842
		string_list_append(list, remote->name);
843 844 845 846
	}
	return 1;
}

847
static void add_options_to_argv(struct argv_array *argv)
848
{
J
Jay Soffian 已提交
849
	if (dry_run)
850
		argv_array_push(argv, "--dry-run");
J
Jay Soffian 已提交
851
	if (prune)
852
		argv_array_push(argv, "--prune");
853
	if (update_head_ok)
854
		argv_array_push(argv, "--update-head-ok");
855
	if (force)
856
		argv_array_push(argv, "--force");
857
	if (keep)
858
		argv_array_push(argv, "--keep");
859
	if (recurse_submodules == RECURSE_SUBMODULES_ON)
860
		argv_array_push(argv, "--recurse-submodules");
861
	else if (recurse_submodules == RECURSE_SUBMODULES_ON_DEMAND)
862
		argv_array_push(argv, "--recurse-submodules=on-demand");
863 864 865 866
	if (tags == TAGS_SET)
		argv_array_push(argv, "--tags");
	else if (tags == TAGS_UNSET)
		argv_array_push(argv, "--no-tags");
867
	if (verbosity >= 2)
868
		argv_array_push(argv, "-v");
869
	if (verbosity >= 1)
870
		argv_array_push(argv, "-v");
871
	else if (verbosity < 0)
872
		argv_array_push(argv, "-q");
873 874 875 876 877 878

}

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

881 882 883 884 885 886
	if (!append && !dry_run) {
		int errcode = truncate_fetch_head();
		if (errcode)
			return errcode;
	}

887 888 889
	argv_array_pushl(&argv, "fetch", "--append", NULL);
	add_options_to_argv(&argv);

890 891
	for (i = 0; i < list->nr; i++) {
		const char *name = list->items[i].string;
892
		argv_array_push(&argv, name);
893
		if (verbosity >= 0)
894
			printf(_("Fetching %s\n"), name);
895
		if (run_command_v_opt(argv.argv, RUN_GIT_CMD)) {
896
			error(_("Could not fetch %s"), name);
897 898
			result = 1;
		}
899
		argv_array_pop(&argv);
900 901
	}

902
	argv_array_clear(&argv);
903 904 905 906
	return result;
}

static int fetch_one(struct remote *remote, int argc, const char **argv)
D
Daniel Barkalow 已提交
907
{
908
	int i;
D
Daniel Barkalow 已提交
909
	static const char **refs = NULL;
J
Jim Meyering 已提交
910
	struct refspec *refspec;
D
Daniel Barkalow 已提交
911
	int ref_nr = 0;
912
	int exit_code;
D
Daniel Barkalow 已提交
913

914
	if (!remote)
915 916
		die(_("No remote repository specified.  Please, specify either a URL or a\n"
		    "remote name from which new revisions should be fetched."));
917

918
	transport = transport_get(remote, NULL);
T
Tay Ray Chuan 已提交
919
	transport_set_verbosity(transport, verbosity, progress);
D
Daniel Barkalow 已提交
920
	if (upload_pack)
921
		set_option(TRANS_OPT_UPLOADPACK, upload_pack);
D
Daniel Barkalow 已提交
922
	if (keep)
923 924 925
		set_option(TRANS_OPT_KEEP, "yes");
	if (depth)
		set_option(TRANS_OPT_DEPTH, depth);
D
Daniel Barkalow 已提交
926

927
	if (argc > 0) {
D
Daniel Barkalow 已提交
928
		int j = 0;
929
		refs = xcalloc(argc + 1, sizeof(const char *));
930
		for (i = 0; i < argc; i++) {
D
Daniel Barkalow 已提交
931 932 933
			if (!strcmp(argv[i], "tag")) {
				char *ref;
				i++;
934
				if (i >= argc)
935
					die(_("You need to specify a tag name."));
D
Daniel Barkalow 已提交
936 937 938 939 940 941 942 943 944 945 946 947 948
				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;
	}

949
	sigchain_push_common(unlock_pack_on_signal);
950
	atexit(unlock_pack);
J
Jim Meyering 已提交
951 952
	refspec = parse_fetch_refspec(ref_nr, refs);
	exit_code = do_fetch(transport, refspec, ref_nr);
953
	free_refspec(ref_nr, refspec);
954 955 956
	transport_disconnect(transport);
	transport = NULL;
	return exit_code;
D
Daniel Barkalow 已提交
957
}
958 959 960 961

int cmd_fetch(int argc, const char **argv, const char *prefix)
{
	int i;
962
	struct string_list list = STRING_LIST_INIT_NODUP;
963 964
	struct remote *remote;
	int result = 0;
J
Jeff King 已提交
965 966 967
	static const char *argv_gc_auto[] = {
		"gc", "--auto", NULL,
	};
968

J
Jeff King 已提交
969 970
	packet_trace_identity("fetch");

971 972 973 974 975 976 977 978
	/* 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]);

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

979 980 981 982 983 984 985 986 987 988 989 990
	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;
		}
	}

991 992 993 994 995 996 997 998 999
	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);
	}

1000 1001
	if (all) {
		if (argc == 1)
1002
			die(_("fetch --all does not take a repository argument"));
1003
		else if (argc > 1)
1004
			die(_("fetch --all does not make sense with refspecs"));
1005 1006 1007 1008 1009 1010
		(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);
1011 1012 1013 1014
	} 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))
1015
				die(_("No such remote or remote group: %s"), argv[i]);
1016
		result = fetch_multiple(&list);
1017 1018 1019 1020 1021 1022
	} else {
		/* Single remote or group */
		(void) add_remote_or_group(argv[0], &list);
		if (list.nr > 1) {
			/* More than one remote */
			if (argc > 1)
1023
				die(_("Fetching a group and specifying refspecs does not make sense"));
1024 1025 1026 1027 1028 1029 1030 1031
			result = fetch_multiple(&list);
		} else {
			/* Zero or one remotes */
			remote = remote_get(argv[0]);
			result = fetch_one(remote, argc-1, argv+1);
		}
	}

1032
	if (!result && (recurse_submodules != RECURSE_SUBMODULES_OFF)) {
1033 1034 1035
		struct argv_array options = ARGV_ARRAY_INIT;

		add_options_to_argv(&options);
1036
		result = fetch_populated_submodules(&options,
1037
						    submodule_prefix,
1038
						    recurse_submodules,
1039
						    verbosity < 0);
1040
		argv_array_clear(&options);
1041 1042
	}

1043 1044 1045 1046
	/* All names were strdup()ed or strndup()ed */
	list.strdup_strings = 1;
	string_list_clear(&list, 0);

J
Jeff King 已提交
1047 1048
	run_command_v_opt(argv_gc_auto, RUN_GIT_CMD);

1049 1050
	return result;
}