fetch.c 29.9 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)) {
J
Jeff King 已提交
122
				rm->fetch_head_status = FETCH_HEAD_MERGE;
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
		for (rm = *old_tail; rm; rm = rm->next)
J
Jeff King 已提交
143
			rm->fetch_head_status = FETCH_HEAD_MERGE;
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) {
163 164
		struct ref **old_tail;

D
Daniel Barkalow 已提交
165
		for (i = 0; i < ref_count; i++) {
166
			get_fetch_map(remote_refs, &refs[i], &tail, 0);
D
Daniel Barkalow 已提交
167 168 169 170 171
			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)
J
Jeff King 已提交
172
			rm->fetch_head_status = FETCH_HEAD_MERGE;
173 174
		if (tags == TAGS_SET)
			get_fetch_map(remote_refs, tag_refspec, &tail, 0);
175 176 177 178 179 180 181 182 183 184 185 186 187 188

		/*
		 * 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],
				      &tail, 0);
		for (rm = *old_tail; rm; rm = rm->next)
			rm->fetch_head_status = FETCH_HEAD_IGNORE;
D
Daniel Barkalow 已提交
189 190 191
	} else {
		/* Use the defaults */
		struct remote *remote = transport->remote;
192 193
		struct branch *branch = branch_get(NULL);
		int has_merge = branch_has_merge_config(branch);
194 195
		if (remote &&
		    (remote->fetch_refspec_nr ||
196
		     /* Note: has_merge implies non-NULL branch->remote_name */
197
		     (has_merge && !strcmp(branch->remote_name, remote->name)))) {
D
Daniel Barkalow 已提交
198
			for (i = 0; i < remote->fetch_refspec_nr; i++) {
199
				get_fetch_map(remote_refs, &remote->fetch[i], &tail, 0);
D
Daniel Barkalow 已提交
200 201 202
				if (remote->fetch[i].dst &&
				    remote->fetch[i].dst[0])
					*autotags = 1;
203
				if (!i && !has_merge && ref_map &&
204
				    !remote->fetch[0].pattern)
J
Jeff King 已提交
205
					ref_map->fetch_head_status = FETCH_HEAD_MERGE;
D
Daniel Barkalow 已提交
206
			}
207 208 209 210
			/*
			 * 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.
211 212
			 *
			 * Note: has_merge implies non-NULL branch->remote_name
213
			 */
214 215
			if (has_merge &&
			    !strcmp(branch->remote_name, remote->name))
216
				add_merge_config(&ref_map, remote_refs, branch, &tail);
D
Daniel Barkalow 已提交
217 218
		} else {
			ref_map = get_remote_ref(remote_refs, "HEAD");
219
			if (!ref_map)
220
				die(_("Couldn't find remote ref HEAD"));
J
Jeff King 已提交
221
			ref_map->fetch_head_status = FETCH_HEAD_MERGE;
222
			tail = &ref_map->next;
D
Daniel Barkalow 已提交
223 224
		}
	}
225 226
	if (tags == TAGS_DEFAULT && *autotags)
		find_non_local_tags(transport, &ref_map, &tail);
227
	ref_remove_duplicates(ref_map);
D
Daniel Barkalow 已提交
228 229 230 231

	return ref_map;
}

232 233 234
#define STORE_REF_ERROR_OTHER 1
#define STORE_REF_ERROR_DF_CONFLICT 2

D
Daniel Barkalow 已提交
235 236 237 238 239 240 241 242
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 已提交
243 244
	if (dry_run)
		return 0;
D
Daniel Barkalow 已提交
245
	if (!rla)
246
		rla = default_rla.buf;
D
Daniel Barkalow 已提交
247 248 249 250
	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)
251 252
		return errno == ENOTDIR ? STORE_REF_ERROR_DF_CONFLICT :
					  STORE_REF_ERROR_OTHER;
D
Daniel Barkalow 已提交
253
	if (write_ref_sha1(lock, ref->new_sha1, msg) < 0)
254 255
		return errno == ENOTDIR ? STORE_REF_ERROR_DF_CONFLICT :
					  STORE_REF_ERROR_OTHER;
D
Daniel Barkalow 已提交
256 257 258
	return 0;
}

P
Pierre Habouzit 已提交
259
#define REFCOL_WIDTH  10
N
Nicolas Pitre 已提交
260

D
Daniel Barkalow 已提交
261
static int update_local_ref(struct ref *ref,
N
Nicolas Pitre 已提交
262
			    const char *remote,
263
			    const struct ref *remote_ref,
264
			    struct strbuf *display)
D
Daniel Barkalow 已提交
265 266 267 268
{
	struct commit *current = NULL, *updated;
	enum object_type type;
	struct branch *current_branch = branch_get(NULL);
269
	const char *pretty_ref = prettify_refname(ref->name);
D
Daniel Barkalow 已提交
270 271 272

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

	if (!hashcmp(ref->old_sha1, ref->new_sha1)) {
T
Tuncer Ayaz 已提交
276
		if (verbosity > 0)
277
			strbuf_addf(display, "= %-*s %-*s -> %s",
278 279
				    TRANSPORT_SUMMARY(_("[up to date]")),
				    REFCOL_WIDTH, remote, pretty_ref);
D
Daniel Barkalow 已提交
280 281 282
		return 0;
	}

283 284
	if (current_branch &&
	    !strcmp(ref->name, current_branch->name) &&
D
Daniel Barkalow 已提交
285 286 287 288 289 290
	    !(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...
		 */
291 292
		strbuf_addf(display,
			    _("! %-*s %-*s -> %s  (can't fetch in current branch)"),
293
			    TRANSPORT_SUMMARY(_("[rejected]")),
294
			    REFCOL_WIDTH, remote, pretty_ref);
D
Daniel Barkalow 已提交
295 296 297 298 299
		return 1;
	}

	if (!is_null_sha1(ref->old_sha1) &&
	    !prefixcmp(ref->name, "refs/tags/")) {
300 301
		int r;
		r = s_update_ref("updating tag", ref, 0);
302 303
		strbuf_addf(display, "%c %-*s %-*s -> %s%s",
			    r ? '!' : '-',
304
			    TRANSPORT_SUMMARY(_("[tag update]")),
305 306
			    REFCOL_WIDTH, remote, pretty_ref,
			    r ? _("  (unable to update local ref)") : "");
307
		return r;
D
Daniel Barkalow 已提交
308 309
	}

310 311
	current = lookup_commit_reference_gently(ref->old_sha1, 1);
	updated = lookup_commit_reference_gently(ref->new_sha1, 1);
D
Daniel Barkalow 已提交
312
	if (!current || !updated) {
N
Nicolas Pitre 已提交
313 314
		const char *msg;
		const char *what;
315
		int r;
316 317 318 319 320 321 322
		/*
		 * 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 已提交
323
			msg = "storing tag";
324
			what = _("[new tag]");
325
		} else if (!prefixcmp(name, "refs/heads/")) {
D
Daniel Barkalow 已提交
326
			msg = "storing head";
327
			what = _("[new branch]");
328 329 330
		} else {
			msg = "storing ref";
			what = _("[new ref]");
N
Nicolas Pitre 已提交
331 332
		}

333 334 335
		if ((recurse_submodules != RECURSE_SUBMODULES_OFF) &&
		    (recurse_submodules != RECURSE_SUBMODULES_ON))
			check_for_new_submodule_commits(ref->new_sha1);
336
		r = s_update_ref(msg, ref, 0);
337 338
		strbuf_addf(display, "%c %-*s %-*s -> %s%s",
			    r ? '!' : '*',
339
			    TRANSPORT_SUMMARY(what),
340 341
			    REFCOL_WIDTH, remote, pretty_ref,
			    r ? _("  (unable to update local ref)") : "");
342
		return r;
D
Daniel Barkalow 已提交
343 344
	}

345
	if (in_merge_bases(current, updated)) {
N
Nicolas Pitre 已提交
346
		char quickref[83];
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("fast-forward", 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)") : "");
360
		return r;
N
Nicolas Pitre 已提交
361 362
	} else if (force || ref->force) {
		char quickref[84];
363
		int r;
N
Nicolas Pitre 已提交
364 365 366
		strcpy(quickref, find_unique_abbrev(current->object.sha1, DEFAULT_ABBREV));
		strcat(quickref, "...");
		strcat(quickref, find_unique_abbrev(ref->new_sha1, DEFAULT_ABBREV));
367 368 369
		if ((recurse_submodules != RECURSE_SUBMODULES_OFF) &&
		    (recurse_submodules != RECURSE_SUBMODULES_ON))
			check_for_new_submodule_commits(ref->new_sha1);
370
		r = s_update_ref("forced-update", ref, 1);
371 372 373 374 375
		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"));
376
		return r;
N
Nicolas Pitre 已提交
377
	} else {
378
		strbuf_addf(display, "! %-*s %-*s -> %s  %s",
379
			    TRANSPORT_SUMMARY(_("[rejected]")),
380 381
			    REFCOL_WIDTH, remote, pretty_ref,
			    _("(non-fast-forward)"));
D
Daniel Barkalow 已提交
382 383 384 385
		return 1;
	}
}

386
static int iterate_ref_map(void *cb_data, unsigned char sha1[20])
387
{
388 389
	struct ref **rm = cb_data;
	struct ref *ref = *rm;
390

391 392 393 394 395
	if (!ref)
		return -1; /* end of the list */
	*rm = ref->next;
	hashcpy(sha1, ref->old_sha1);
	return 0;
396 397
}

398
static int store_updated_refs(const char *raw_url, const char *remote_name,
399
		struct ref *ref_map)
D
Daniel Barkalow 已提交
400 401 402
{
	FILE *fp;
	struct commit *commit;
403 404
	int url_len, i, shown_url = 0, rc = 0;
	struct strbuf note = STRBUF_INIT;
D
Daniel Barkalow 已提交
405 406
	const char *what, *kind;
	struct ref *rm;
J
Jay Soffian 已提交
407
	char *url, *filename = dry_run ? "/dev/null" : git_path("FETCH_HEAD");
J
Jeff King 已提交
408
	int want_status;
D
Daniel Barkalow 已提交
409

410 411
	fp = fopen(filename, "a");
	if (!fp)
412
		return error(_("cannot open %s: %s\n"), filename, strerror(errno));
413

414 415 416 417
	if (raw_url)
		url = transport_anonymize_url(raw_url);
	else
		url = xstrdup("foreign");
418

419
	rm = ref_map;
J
Junio C Hamano 已提交
420
	if (check_everything_connected(iterate_ref_map, 0, &rm)) {
421 422 423
		rc = error(_("%s did not send all necessary objects\n"), url);
		goto abort;
	}
424

425
	/*
J
Jeff King 已提交
426 427 428
	 * 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.
429
	 */
J
Jeff King 已提交
430 431 432
	for (want_status = FETCH_HEAD_MERGE;
	     want_status <= FETCH_HEAD_IGNORE;
	     want_status++) {
433 434
		for (rm = ref_map; rm; rm = rm->next) {
			struct ref *ref = NULL;
J
Jeff King 已提交
435
			const char *merge_status_marker = "";
436 437 438

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

J
Jeff King 已提交
441
			if (rm->fetch_head_status != want_status)
442 443 444 445 446 447 448 449 450
				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 已提交
451 452


453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472
			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 已提交
473

474 475 476 477 478 479 480 481 482 483 484 485 486
			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 已提交
487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506
			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;
			}
507 508 509

			strbuf_reset(&note);
			if (ref) {
510
				rc |= update_local_ref(ref, what, rm, &note);
511 512 513 514 515 516 517 518 519 520 521 522 523 524 525
				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 已提交
526 527
			}
		}
D
Daniel Barkalow 已提交
528
	}
529

530
	if (rc & STORE_REF_ERROR_DF_CONFLICT)
531
		error(_("some local refs could not be updated; try running\n"
532
		      " 'git remote prune %s' to remove any old, conflicting "
533
		      "branches"), remote_name);
534 535

 abort:
536
	strbuf_release(&note);
537 538
	free(url);
	fclose(fp);
539
	return rc;
D
Daniel Barkalow 已提交
540 541
}

542 543
/*
 * We would want to bypass the object transfer altogether if
544
 * everything we are going to fetch already exists and is connected
545 546 547 548
 * locally.
 */
static int quickfetch(struct ref *ref_map)
{
549 550
	struct ref *rm = ref_map;

551 552 553 554 555 556 557 558 559
	/*
	 * 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;
560
	return check_everything_connected(iterate_ref_map, 1, &rm);
561 562
}

D
Daniel Barkalow 已提交
563 564
static int fetch_refs(struct transport *transport, struct ref *ref_map)
{
565 566 567
	int ret = quickfetch(ref_map);
	if (ret)
		ret = transport_fetch_refs(transport, ref_map);
D
Daniel Barkalow 已提交
568
	if (!ret)
569 570 571
		ret |= store_updated_refs(transport->url,
				transport->remote->name,
				ref_map);
572
	transport_unlock_pack(transport);
D
Daniel Barkalow 已提交
573 574 575
	return ret;
}

576
static int prune_refs(struct refspec *refs, int ref_count, struct ref *ref_map)
J
Jay Soffian 已提交
577 578
{
	int result = 0;
579
	struct ref *ref, *stale_refs = get_stale_heads(refs, ref_count, ref_map);
J
Jay Soffian 已提交
580
	const char *dangling_msg = dry_run
581 582
		? _("   (%s will become dangling)")
		: _("   (%s has become dangling)");
J
Jay Soffian 已提交
583 584 585 586 587 588

	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",
589
				TRANSPORT_SUMMARY(_("[deleted]")),
590
				REFCOL_WIDTH, _("(none)"), prettify_refname(ref->name));
J
Jay Soffian 已提交
591 592 593 594 595 596 597
			warn_dangling_symref(stderr, dangling_msg, ref->name);
		}
	}
	free_refs(stale_refs);
	return result;
}

D
Daniel Barkalow 已提交
598 599 600
static int add_existing(const char *refname, const unsigned char *sha1,
			int flag, void *cbdata)
{
601
	struct string_list *list = (struct string_list *)cbdata;
602
	struct string_list_item *item = string_list_insert(list, refname);
603
	item->util = (void *)sha1;
D
Daniel Barkalow 已提交
604 605 606
	return 0;
}

607 608 609 610 611 612 613 614 615 616 617
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;
}

618 619 620
static void find_non_local_tags(struct transport *transport,
			struct ref **head,
			struct ref ***tail)
D
Daniel Barkalow 已提交
621
{
622 623
	struct string_list existing_refs = STRING_LIST_INIT_NODUP;
	struct string_list remote_refs = STRING_LIST_INIT_NODUP;
624
	const struct ref *ref;
625
	struct string_list_item *item = NULL;
D
Daniel Barkalow 已提交
626 627 628

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

632 633 634 635 636 637
		/*
		 * 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.
		 */
638
		if (!suffixcmp(ref->name, "^{}")) {
639 640 641 642 643 644 645
			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 已提交
646 647
		}

648 649 650 651 652 653 654 655 656
		/*
		 * 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 已提交
657

658
		item = NULL;
D
Daniel Barkalow 已提交
659

660 661 662 663 664
		/* 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;

665
		item = string_list_insert(&remote_refs, ref->name);
666
		item->util = (void *)ref->old_sha1;
D
Daniel Barkalow 已提交
667
	}
668
	string_list_clear(&existing_refs, 0);
669 670 671 672 673 674 675 676 677 678

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

	/*
679 680
	 * For all the tags in the remote_refs string list,
	 * add them to the list of refs to be fetched
681
	 */
682 683 684 685 686 687 688 689 690 691 692
	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;
		}
	}
693 694

	string_list_clear(&remote_refs, 0);
D
Daniel Barkalow 已提交
695 696
}

697 698 699 700 701 702 703 704 705 706
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))
707 708
			die(_("Refusing to fetch into current branch %s "
			    "of non-bare repository"), current_branch->refname);
709 710
}

711 712 713 714 715 716
static int truncate_fetch_head(void)
{
	char *filename = git_path("FETCH_HEAD");
	FILE *fp = fopen(filename, "w");

	if (!fp)
717
		return error(_("cannot open %s: %s\n"), filename, strerror(errno));
718 719 720 721
	fclose(fp);
	return 0;
}

D
Daniel Barkalow 已提交
722 723 724
static int do_fetch(struct transport *transport,
		    struct refspec *refs, int ref_count)
{
725
	struct string_list existing_refs = STRING_LIST_INIT_NODUP;
726
	struct string_list_item *peer_item = NULL;
727
	struct ref *ref_map;
D
Daniel Barkalow 已提交
728 729
	struct ref *rm;
	int autotags = (transport->remote->fetch_tags == 1);
730 731 732

	for_each_ref(add_existing, &existing_refs);

733 734 735 736 737 738
	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 已提交
739

740
	if (!transport->get_refs_list || !transport->fetch)
741
		die(_("Don't know how to fetch from %s"), transport->url);
D
Daniel Barkalow 已提交
742 743

	/* if not appending, truncate FETCH_HEAD */
J
Jay Soffian 已提交
744
	if (!append && !dry_run) {
745 746 747
		int errcode = truncate_fetch_head();
		if (errcode)
			return errcode;
748
	}
D
Daniel Barkalow 已提交
749 750

	ref_map = get_ref_map(transport, refs, ref_count, tags, &autotags);
751 752
	if (!update_head_ok)
		check_not_current_branch(ref_map);
D
Daniel Barkalow 已提交
753 754

	for (rm = ref_map; rm; rm = rm->next) {
755
		if (rm->peer_ref) {
756 757
			peer_item = string_list_lookup(&existing_refs,
						       rm->peer_ref->name);
758 759 760 761
			if (peer_item)
				hashcpy(rm->peer_ref->old_sha1,
					peer_item->util);
		}
D
Daniel Barkalow 已提交
762 763
	}

764 765
	if (tags == TAGS_DEFAULT && autotags)
		transport_set_option(transport, TRANS_OPT_FOLLOWTAGS, "1");
D
Daniel Barkalow 已提交
766 767 768 769
	if (fetch_refs(transport, ref_map)) {
		free_refs(ref_map);
		return 1;
	}
770
	if (prune) {
771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789
		/* 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) {
790
			prune_refs(refs, ref_count, ref_map);
791
		} else {
792
			prune_refs(transport->remote->fetch, transport->remote->fetch_refspec_nr, ref_map);
793
		}
794
	}
795
	free_refs(ref_map);
D
Daniel Barkalow 已提交
796 797 798

	/* if neither --no-tags nor --tags was specified, do automated tag
	 * following ... */
799
	if (tags == TAGS_DEFAULT && autotags) {
800 801 802
		struct ref **tail = &ref_map;
		ref_map = NULL;
		find_non_local_tags(transport, &ref_map, &tail);
D
Daniel Barkalow 已提交
803
		if (ref_map) {
804
			transport_set_option(transport, TRANS_OPT_FOLLOWTAGS, NULL);
D
Daniel Barkalow 已提交
805 806 807 808 809 810 811 812 813
			transport_set_option(transport, TRANS_OPT_DEPTH, "0");
			fetch_refs(transport, ref_map);
		}
		free_refs(ref_map);
	}

	return 0;
}

814 815 816 817
static void set_option(const char *name, const char *value)
{
	int r = transport_set_option(transport, name, value);
	if (r < 0)
818
		die(_("Option \"%s\" value \"%s\" is not valid for %s"),
819 820
			name, value, transport->url);
	if (r > 0)
821
		warning(_("Option \"%s\" is ignored for %s\n"),
822 823 824
			name, transport->url);
}

825 826 827
static int get_one_remote_for_fetch(struct remote *remote, void *priv)
{
	struct string_list *list = priv;
828
	if (!remote->skip_default_update)
829
		string_list_append(list, remote->name);
830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847
	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) {
848 849
				string_list_append(g->list,
						   xstrndup(value, space));
850 851 852 853 854 855 856 857 858 859 860 861
			}
			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;
862 863
	struct remote_group_data g;
	g.name = name; g.list = list;
864 865 866 867 868 869 870

	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);
871
		string_list_append(list, remote->name);
872 873 874 875
	}
	return 1;
}

876
static void add_options_to_argv(struct argv_array *argv)
877
{
J
Jay Soffian 已提交
878
	if (dry_run)
879
		argv_array_push(argv, "--dry-run");
J
Jay Soffian 已提交
880
	if (prune)
881
		argv_array_push(argv, "--prune");
882
	if (update_head_ok)
883
		argv_array_push(argv, "--update-head-ok");
884
	if (force)
885
		argv_array_push(argv, "--force");
886
	if (keep)
887
		argv_array_push(argv, "--keep");
888
	if (recurse_submodules == RECURSE_SUBMODULES_ON)
889
		argv_array_push(argv, "--recurse-submodules");
890
	else if (recurse_submodules == RECURSE_SUBMODULES_ON_DEMAND)
891
		argv_array_push(argv, "--recurse-submodules=on-demand");
892 893 894 895
	if (tags == TAGS_SET)
		argv_array_push(argv, "--tags");
	else if (tags == TAGS_UNSET)
		argv_array_push(argv, "--no-tags");
896
	if (verbosity >= 2)
897
		argv_array_push(argv, "-v");
898
	if (verbosity >= 1)
899
		argv_array_push(argv, "-v");
900
	else if (verbosity < 0)
901
		argv_array_push(argv, "-q");
902 903 904 905 906 907

}

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

910 911 912 913 914 915
	if (!append && !dry_run) {
		int errcode = truncate_fetch_head();
		if (errcode)
			return errcode;
	}

916 917 918
	argv_array_pushl(&argv, "fetch", "--append", NULL);
	add_options_to_argv(&argv);

919 920
	for (i = 0; i < list->nr; i++) {
		const char *name = list->items[i].string;
921
		argv_array_push(&argv, name);
922
		if (verbosity >= 0)
923
			printf(_("Fetching %s\n"), name);
924
		if (run_command_v_opt(argv.argv, RUN_GIT_CMD)) {
925
			error(_("Could not fetch %s"), name);
926 927
			result = 1;
		}
928
		argv_array_pop(&argv);
929 930
	}

931
	argv_array_clear(&argv);
932 933 934 935
	return result;
}

static int fetch_one(struct remote *remote, int argc, const char **argv)
D
Daniel Barkalow 已提交
936
{
937
	int i;
D
Daniel Barkalow 已提交
938
	static const char **refs = NULL;
J
Jim Meyering 已提交
939
	struct refspec *refspec;
D
Daniel Barkalow 已提交
940
	int ref_nr = 0;
941
	int exit_code;
D
Daniel Barkalow 已提交
942

943
	if (!remote)
944 945
		die(_("No remote repository specified.  Please, specify either a URL or a\n"
		    "remote name from which new revisions should be fetched."));
946

947
	transport = transport_get(remote, NULL);
T
Tay Ray Chuan 已提交
948
	transport_set_verbosity(transport, verbosity, progress);
D
Daniel Barkalow 已提交
949
	if (upload_pack)
950
		set_option(TRANS_OPT_UPLOADPACK, upload_pack);
D
Daniel Barkalow 已提交
951
	if (keep)
952 953 954
		set_option(TRANS_OPT_KEEP, "yes");
	if (depth)
		set_option(TRANS_OPT_DEPTH, depth);
D
Daniel Barkalow 已提交
955

956
	if (argc > 0) {
D
Daniel Barkalow 已提交
957
		int j = 0;
958
		refs = xcalloc(argc + 1, sizeof(const char *));
959
		for (i = 0; i < argc; i++) {
D
Daniel Barkalow 已提交
960 961 962
			if (!strcmp(argv[i], "tag")) {
				char *ref;
				i++;
963
				if (i >= argc)
964
					die(_("You need to specify a tag name."));
D
Daniel Barkalow 已提交
965 966 967 968 969 970 971 972 973 974 975 976 977
				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;
	}

978
	sigchain_push_common(unlock_pack_on_signal);
979
	atexit(unlock_pack);
J
Jim Meyering 已提交
980 981
	refspec = parse_fetch_refspec(ref_nr, refs);
	exit_code = do_fetch(transport, refspec, ref_nr);
982
	free_refspec(ref_nr, refspec);
983 984 985
	transport_disconnect(transport);
	transport = NULL;
	return exit_code;
D
Daniel Barkalow 已提交
986
}
987 988 989 990

int cmd_fetch(int argc, const char **argv, const char *prefix)
{
	int i;
991
	struct string_list list = STRING_LIST_INIT_NODUP;
992 993
	struct remote *remote;
	int result = 0;
J
Jeff King 已提交
994 995 996
	static const char *argv_gc_auto[] = {
		"gc", "--auto", NULL,
	};
997

J
Jeff King 已提交
998 999
	packet_trace_identity("fetch");

1000 1001 1002 1003 1004 1005 1006 1007
	/* 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);

1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019
	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;
		}
	}

1020 1021 1022 1023 1024 1025 1026 1027 1028
	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);
	}

1029 1030
	if (all) {
		if (argc == 1)
1031
			die(_("fetch --all does not take a repository argument"));
1032
		else if (argc > 1)
1033
			die(_("fetch --all does not make sense with refspecs"));
1034 1035 1036 1037 1038 1039
		(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);
1040 1041 1042 1043
	} 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))
1044
				die(_("No such remote or remote group: %s"), argv[i]);
1045
		result = fetch_multiple(&list);
1046 1047 1048 1049 1050 1051
	} else {
		/* Single remote or group */
		(void) add_remote_or_group(argv[0], &list);
		if (list.nr > 1) {
			/* More than one remote */
			if (argc > 1)
1052
				die(_("Fetching a group and specifying refspecs does not make sense"));
1053 1054 1055 1056 1057 1058 1059 1060
			result = fetch_multiple(&list);
		} else {
			/* Zero or one remotes */
			remote = remote_get(argv[0]);
			result = fetch_one(remote, argc-1, argv+1);
		}
	}

1061
	if (!result && (recurse_submodules != RECURSE_SUBMODULES_OFF)) {
1062 1063 1064
		struct argv_array options = ARGV_ARRAY_INIT;

		add_options_to_argv(&options);
1065
		result = fetch_populated_submodules(&options,
1066
						    submodule_prefix,
1067
						    recurse_submodules,
1068
						    verbosity < 0);
1069
		argv_array_clear(&options);
1070 1071
	}

1072 1073 1074 1075
	/* All names were strdup()ed or strndup()ed */
	list.strdup_strings = 1;
	string_list_clear(&list, 0);

J
Jeff King 已提交
1076 1077
	run_command_v_opt(argv_gc_auto, RUN_GIT_CMD);

1078 1079
	return result;
}