1/*
2 * "git fetch"
3 */
4#include "cache.h"
5#include "refs.h"
6#include "commit.h"
7#include "builtin.h"
8#include "string-list.h"
9#include "remote.h"
10#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"
18
19static const char * const builtin_fetch_usage[] = {
20 N_("git fetch [<options>] [<repository> [<refspec>...]]"),
21 N_("git fetch [<options>] <group>"),
22 N_("git fetch --multiple [<options>] [(<repository> | <group>)...]"),
23 N_("git fetch --all [<options>]"),
24 NULL
25};
26
27enum {
28 TAGS_UNSET = 0,
29 TAGS_DEFAULT = 1,
30 TAGS_SET = 2
31};
32
33static int fetch_prune_config = -1; /* unspecified */
34static int prune = -1; /* unspecified */
35#define PRUNE_BY_DEFAULT 0 /* do we prune by default? */
36
37static int all, append, dry_run, force, keep, multiple, update_head_ok, verbosity;
38static int progress = -1, recurse_submodules = RECURSE_SUBMODULES_DEFAULT;
39static int tags = TAGS_DEFAULT, unshallow;
40static const char *depth;
41static const char *upload_pack;
42static struct strbuf default_rla = STRBUF_INIT;
43static struct transport *gtransport;
44static struct transport *gsecondary;
45static const char *submodule_prefix = "";
46static const char *recurse_submodules_default;
47
48static int option_parse_recurse_submodules(const struct option *opt,
49 const char *arg, int unset)
50{
51 if (unset) {
52 recurse_submodules = RECURSE_SUBMODULES_OFF;
53 } else {
54 if (arg)
55 recurse_submodules = parse_fetch_recurse_submodules_arg(opt->long_name, arg);
56 else
57 recurse_submodules = RECURSE_SUBMODULES_ON;
58 }
59 return 0;
60}
61
62static int git_fetch_config(const char *k, const char *v, void *cb)
63{
64 if (!strcmp(k, "fetch.prune")) {
65 fetch_prune_config = git_config_bool(k, v);
66 return 0;
67 }
68 return 0;
69}
70
71static struct option builtin_fetch_options[] = {
72 OPT__VERBOSITY(&verbosity),
73 OPT_BOOL(0, "all", &all,
74 N_("fetch from all remotes")),
75 OPT_BOOL('a', "append", &append,
76 N_("append to .git/FETCH_HEAD instead of overwriting")),
77 OPT_STRING(0, "upload-pack", &upload_pack, N_("path"),
78 N_("path to upload pack on remote end")),
79 OPT__FORCE(&force, N_("force overwrite of local branch")),
80 OPT_BOOL('m', "multiple", &multiple,
81 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 OPT_BOOL('p', "prune", &prune,
87 N_("prune remote-tracking branches no longer on remote")),
88 { OPTION_CALLBACK, 0, "recurse-submodules", NULL, N_("on-demand"),
89 N_("control recursive fetching of submodules"),
90 PARSE_OPT_OPTARG, option_parse_recurse_submodules },
91 OPT_BOOL(0, "dry-run", &dry_run,
92 N_("dry run")),
93 OPT_BOOL('k', "keep", &keep, N_("keep downloaded pack")),
94 OPT_BOOL('u', "update-head-ok", &update_head_ok,
95 N_("allow updating of HEAD ref")),
96 OPT_BOOL(0, "progress", &progress, N_("force progress reporting")),
97 OPT_STRING(0, "depth", &depth, N_("depth"),
98 N_("deepen history of shallow clone")),
99 { OPTION_SET_INT, 0, "unshallow", &unshallow, NULL,
100 N_("convert to a complete repository"),
101 PARSE_OPT_NONEG | PARSE_OPT_NOARG, NULL, 1 },
102 { OPTION_STRING, 0, "submodule-prefix", &submodule_prefix, N_("dir"),
103 N_("prepend this to submodule path output"), PARSE_OPT_HIDDEN },
104 { OPTION_STRING, 0, "recurse-submodules-default",
105 &recurse_submodules_default, NULL,
106 N_("default mode for recursion"), PARSE_OPT_HIDDEN },
107 OPT_END()
108};
109
110static void unlock_pack(void)
111{
112 if (gtransport)
113 transport_unlock_pack(gtransport);
114 if (gsecondary)
115 transport_unlock_pack(gsecondary);
116}
117
118static void unlock_pack_on_signal(int signo)
119{
120 unlock_pack();
121 sigchain_pop(signo);
122 raise(signo);
123}
124
125static void add_merge_config(struct ref **head,
126 const struct ref *remote_refs,
127 struct branch *branch,
128 struct ref ***tail)
129{
130 int i;
131
132 for (i = 0; i < branch->merge_nr; i++) {
133 struct ref *rm, **old_tail = *tail;
134 struct refspec refspec;
135
136 for (rm = *head; rm; rm = rm->next) {
137 if (branch_merge_matches(branch, i, rm->name)) {
138 rm->fetch_head_status = FETCH_HEAD_MERGE;
139 break;
140 }
141 }
142 if (rm)
143 continue;
144
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 * fail if branch.$name.merge is misconfigured to point
150 * at a nonexisting branch. If we were indeed called by
151 * 'git pull', it will notice the misconfiguration because
152 * there is no entry in the resulting FETCH_HEAD marked
153 * 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)
159 rm->fetch_head_status = FETCH_HEAD_MERGE;
160 }
161}
162
163static void find_non_local_tags(struct transport *transport,
164 struct ref **head,
165 struct ref ***tail);
166
167static struct ref *get_ref_map(struct transport *transport,
168 struct refspec *refs, int ref_count, int tags,
169 int *autotags)
170{
171 int i;
172 struct ref *rm;
173 struct ref *ref_map = NULL;
174 struct ref **tail = &ref_map;
175
176 const struct ref *remote_refs = transport_get_remote_refs(transport);
177
178 if (ref_count || tags == TAGS_SET) {
179 struct ref **old_tail;
180
181 for (i = 0; i < ref_count; i++) {
182 get_fetch_map(remote_refs, &refs[i], &tail, 0);
183 if (refs[i].dst && refs[i].dst[0])
184 *autotags = 1;
185 }
186 /* Merge everything on the command line, but not --tags */
187 for (rm = ref_map; rm; rm = rm->next)
188 rm->fetch_head_status = FETCH_HEAD_MERGE;
189 if (tags == TAGS_SET)
190 get_fetch_map(remote_refs, tag_refspec, &tail, 0);
191
192 /*
193 * For any refs that we happen to be fetching via command-line
194 * arguments, take the opportunity to update their configured
195 * counterparts. However, we do not want to mention these
196 * entries in FETCH_HEAD at all, as they would simply be
197 * duplicates of existing entries.
198 */
199 old_tail = tail;
200 for (i = 0; i < transport->remote->fetch_refspec_nr; i++)
201 get_fetch_map(ref_map, &transport->remote->fetch[i],
202 &tail, 1);
203 for (rm = *old_tail; rm; rm = rm->next)
204 rm->fetch_head_status = FETCH_HEAD_IGNORE;
205 } else {
206 /* Use the defaults */
207 struct remote *remote = transport->remote;
208 struct branch *branch = branch_get(NULL);
209 int has_merge = branch_has_merge_config(branch);
210 if (remote &&
211 (remote->fetch_refspec_nr ||
212 /* Note: has_merge implies non-NULL branch->remote_name */
213 (has_merge && !strcmp(branch->remote_name, remote->name)))) {
214 for (i = 0; i < remote->fetch_refspec_nr; i++) {
215 get_fetch_map(remote_refs, &remote->fetch[i], &tail, 0);
216 if (remote->fetch[i].dst &&
217 remote->fetch[i].dst[0])
218 *autotags = 1;
219 if (!i && !has_merge && ref_map &&
220 !remote->fetch[0].pattern)
221 ref_map->fetch_head_status = FETCH_HEAD_MERGE;
222 }
223 /*
224 * if the remote we're fetching from is the same
225 * as given in branch.<name>.remote, we add the
226 * ref given in branch.<name>.merge, too.
227 *
228 * Note: has_merge implies non-NULL branch->remote_name
229 */
230 if (has_merge &&
231 !strcmp(branch->remote_name, remote->name))
232 add_merge_config(&ref_map, remote_refs, branch, &tail);
233 } else {
234 ref_map = get_remote_ref(remote_refs, "HEAD");
235 if (!ref_map)
236 die(_("Couldn't find remote ref HEAD"));
237 ref_map->fetch_head_status = FETCH_HEAD_MERGE;
238 tail = &ref_map->next;
239 }
240 }
241 if (tags == TAGS_DEFAULT && *autotags)
242 find_non_local_tags(transport, &ref_map, &tail);
243 ref_remove_duplicates(ref_map);
244
245 return ref_map;
246}
247
248#define STORE_REF_ERROR_OTHER 1
249#define STORE_REF_ERROR_DF_CONFLICT 2
250
251static int s_update_ref(const char *action,
252 struct ref *ref,
253 int check_old)
254{
255 char msg[1024];
256 char *rla = getenv("GIT_REFLOG_ACTION");
257 static struct ref_lock *lock;
258
259 if (dry_run)
260 return 0;
261 if (!rla)
262 rla = default_rla.buf;
263 snprintf(msg, sizeof(msg), "%s: %s", rla, action);
264 lock = lock_any_ref_for_update(ref->name,
265 check_old ? ref->old_sha1 : NULL,
266 0, NULL);
267 if (!lock)
268 return errno == ENOTDIR ? STORE_REF_ERROR_DF_CONFLICT :
269 STORE_REF_ERROR_OTHER;
270 if (write_ref_sha1(lock, ref->new_sha1, msg) < 0)
271 return errno == ENOTDIR ? STORE_REF_ERROR_DF_CONFLICT :
272 STORE_REF_ERROR_OTHER;
273 return 0;
274}
275
276#define REFCOL_WIDTH 10
277
278static int update_local_ref(struct ref *ref,
279 const char *remote,
280 const struct ref *remote_ref,
281 struct strbuf *display)
282{
283 struct commit *current = NULL, *updated;
284 enum object_type type;
285 struct branch *current_branch = branch_get(NULL);
286 const char *pretty_ref = prettify_refname(ref->name);
287
288 type = sha1_object_info(ref->new_sha1, NULL);
289 if (type < 0)
290 die(_("object %s not found"), sha1_to_hex(ref->new_sha1));
291
292 if (!hashcmp(ref->old_sha1, ref->new_sha1)) {
293 if (verbosity > 0)
294 strbuf_addf(display, "= %-*s %-*s -> %s",
295 TRANSPORT_SUMMARY(_("[up to date]")),
296 REFCOL_WIDTH, remote, pretty_ref);
297 return 0;
298 }
299
300 if (current_branch &&
301 !strcmp(ref->name, current_branch->name) &&
302 !(update_head_ok || is_bare_repository()) &&
303 !is_null_sha1(ref->old_sha1)) {
304 /*
305 * If this is the head, and it's not okay to update
306 * the head, and the old value of the head isn't empty...
307 */
308 strbuf_addf(display,
309 _("! %-*s %-*s -> %s (can't fetch in current branch)"),
310 TRANSPORT_SUMMARY(_("[rejected]")),
311 REFCOL_WIDTH, remote, pretty_ref);
312 return 1;
313 }
314
315 if (!is_null_sha1(ref->old_sha1) &&
316 !prefixcmp(ref->name, "refs/tags/")) {
317 int r;
318 r = s_update_ref("updating tag", ref, 0);
319 strbuf_addf(display, "%c %-*s %-*s -> %s%s",
320 r ? '!' : '-',
321 TRANSPORT_SUMMARY(_("[tag update]")),
322 REFCOL_WIDTH, remote, pretty_ref,
323 r ? _(" (unable to update local ref)") : "");
324 return r;
325 }
326
327 current = lookup_commit_reference_gently(ref->old_sha1, 1);
328 updated = lookup_commit_reference_gently(ref->new_sha1, 1);
329 if (!current || !updated) {
330 const char *msg;
331 const char *what;
332 int r;
333 /*
334 * Nicely describe the new ref we're fetching.
335 * Base this on the remote's ref name, as it's
336 * more likely to follow a standard layout.
337 */
338 const char *name = remote_ref ? remote_ref->name : "";
339 if (!prefixcmp(name, "refs/tags/")) {
340 msg = "storing tag";
341 what = _("[new tag]");
342 } else if (!prefixcmp(name, "refs/heads/")) {
343 msg = "storing head";
344 what = _("[new branch]");
345 } else {
346 msg = "storing ref";
347 what = _("[new ref]");
348 }
349
350 if ((recurse_submodules != RECURSE_SUBMODULES_OFF) &&
351 (recurse_submodules != RECURSE_SUBMODULES_ON))
352 check_for_new_submodule_commits(ref->new_sha1);
353 r = s_update_ref(msg, ref, 0);
354 strbuf_addf(display, "%c %-*s %-*s -> %s%s",
355 r ? '!' : '*',
356 TRANSPORT_SUMMARY(what),
357 REFCOL_WIDTH, remote, pretty_ref,
358 r ? _(" (unable to update local ref)") : "");
359 return r;
360 }
361
362 if (in_merge_bases(current, updated)) {
363 char quickref[83];
364 int r;
365 strcpy(quickref, find_unique_abbrev(current->object.sha1, DEFAULT_ABBREV));
366 strcat(quickref, "..");
367 strcat(quickref, find_unique_abbrev(ref->new_sha1, DEFAULT_ABBREV));
368 if ((recurse_submodules != RECURSE_SUBMODULES_OFF) &&
369 (recurse_submodules != RECURSE_SUBMODULES_ON))
370 check_for_new_submodule_commits(ref->new_sha1);
371 r = s_update_ref("fast-forward", ref, 1);
372 strbuf_addf(display, "%c %-*s %-*s -> %s%s",
373 r ? '!' : ' ',
374 TRANSPORT_SUMMARY_WIDTH, quickref,
375 REFCOL_WIDTH, remote, pretty_ref,
376 r ? _(" (unable to update local ref)") : "");
377 return r;
378 } else if (force || ref->force) {
379 char quickref[84];
380 int r;
381 strcpy(quickref, find_unique_abbrev(current->object.sha1, DEFAULT_ABBREV));
382 strcat(quickref, "...");
383 strcat(quickref, find_unique_abbrev(ref->new_sha1, DEFAULT_ABBREV));
384 if ((recurse_submodules != RECURSE_SUBMODULES_OFF) &&
385 (recurse_submodules != RECURSE_SUBMODULES_ON))
386 check_for_new_submodule_commits(ref->new_sha1);
387 r = s_update_ref("forced-update", ref, 1);
388 strbuf_addf(display, "%c %-*s %-*s -> %s (%s)",
389 r ? '!' : '+',
390 TRANSPORT_SUMMARY_WIDTH, quickref,
391 REFCOL_WIDTH, remote, pretty_ref,
392 r ? _("unable to update local ref") : _("forced update"));
393 return r;
394 } else {
395 strbuf_addf(display, "! %-*s %-*s -> %s %s",
396 TRANSPORT_SUMMARY(_("[rejected]")),
397 REFCOL_WIDTH, remote, pretty_ref,
398 _("(non-fast-forward)"));
399 return 1;
400 }
401}
402
403static int iterate_ref_map(void *cb_data, unsigned char sha1[20])
404{
405 struct ref **rm = cb_data;
406 struct ref *ref = *rm;
407
408 if (!ref)
409 return -1; /* end of the list */
410 *rm = ref->next;
411 hashcpy(sha1, ref->old_sha1);
412 return 0;
413}
414
415static int store_updated_refs(const char *raw_url, const char *remote_name,
416 struct ref *ref_map)
417{
418 FILE *fp;
419 struct commit *commit;
420 int url_len, i, shown_url = 0, rc = 0;
421 struct strbuf note = STRBUF_INIT;
422 const char *what, *kind;
423 struct ref *rm;
424 char *url, *filename = dry_run ? "/dev/null" : git_path("FETCH_HEAD");
425 int want_status;
426
427 fp = fopen(filename, "a");
428 if (!fp)
429 return error(_("cannot open %s: %s\n"), filename, strerror(errno));
430
431 if (raw_url)
432 url = transport_anonymize_url(raw_url);
433 else
434 url = xstrdup("foreign");
435
436 rm = ref_map;
437 if (check_everything_connected(iterate_ref_map, 0, &rm)) {
438 rc = error(_("%s did not send all necessary objects\n"), url);
439 goto abort;
440 }
441
442 /*
443 * We do a pass for each fetch_head_status type in their enum order, so
444 * merged entries are written before not-for-merge. That lets readers
445 * use FETCH_HEAD as a refname to refer to the ref to be merged.
446 */
447 for (want_status = FETCH_HEAD_MERGE;
448 want_status <= FETCH_HEAD_IGNORE;
449 want_status++) {
450 for (rm = ref_map; rm; rm = rm->next) {
451 struct ref *ref = NULL;
452 const char *merge_status_marker = "";
453
454 commit = lookup_commit_reference_gently(rm->old_sha1, 1);
455 if (!commit)
456 rm->fetch_head_status = FETCH_HEAD_NOT_FOR_MERGE;
457
458 if (rm->fetch_head_status != want_status)
459 continue;
460
461 if (rm->peer_ref) {
462 ref = xcalloc(1, sizeof(*ref) + strlen(rm->peer_ref->name) + 1);
463 strcpy(ref->name, rm->peer_ref->name);
464 hashcpy(ref->old_sha1, rm->peer_ref->old_sha1);
465 hashcpy(ref->new_sha1, rm->old_sha1);
466 ref->force = rm->peer_ref->force;
467 }
468
469
470 if (!strcmp(rm->name, "HEAD")) {
471 kind = "";
472 what = "";
473 }
474 else if (!prefixcmp(rm->name, "refs/heads/")) {
475 kind = "branch";
476 what = rm->name + 11;
477 }
478 else if (!prefixcmp(rm->name, "refs/tags/")) {
479 kind = "tag";
480 what = rm->name + 10;
481 }
482 else if (!prefixcmp(rm->name, "refs/remotes/")) {
483 kind = "remote-tracking branch";
484 what = rm->name + 13;
485 }
486 else {
487 kind = "";
488 what = rm->name;
489 }
490
491 url_len = strlen(url);
492 for (i = url_len - 1; url[i] == '/' && 0 <= i; i--)
493 ;
494 url_len = i + 1;
495 if (4 < i && !strncmp(".git", url + i - 3, 4))
496 url_len = i - 3;
497
498 strbuf_reset(¬e);
499 if (*what) {
500 if (*kind)
501 strbuf_addf(¬e, "%s ", kind);
502 strbuf_addf(¬e, "'%s' of ", what);
503 }
504 switch (rm->fetch_head_status) {
505 case FETCH_HEAD_NOT_FOR_MERGE:
506 merge_status_marker = "not-for-merge";
507 /* fall-through */
508 case FETCH_HEAD_MERGE:
509 fprintf(fp, "%s\t%s\t%s",
510 sha1_to_hex(rm->old_sha1),
511 merge_status_marker,
512 note.buf);
513 for (i = 0; i < url_len; ++i)
514 if ('\n' == url[i])
515 fputs("\\n", fp);
516 else
517 fputc(url[i], fp);
518 fputc('\n', fp);
519 break;
520 default:
521 /* do not write anything to FETCH_HEAD */
522 break;
523 }
524
525 strbuf_reset(¬e);
526 if (ref) {
527 rc |= update_local_ref(ref, what, rm, ¬e);
528 free(ref);
529 } else
530 strbuf_addf(¬e, "* %-*s %-*s -> FETCH_HEAD",
531 TRANSPORT_SUMMARY_WIDTH,
532 *kind ? kind : "branch",
533 REFCOL_WIDTH,
534 *what ? what : "HEAD");
535 if (note.len) {
536 if (verbosity >= 0 && !shown_url) {
537 fprintf(stderr, _("From %.*s\n"),
538 url_len, url);
539 shown_url = 1;
540 }
541 if (verbosity >= 0)
542 fprintf(stderr, " %s\n", note.buf);
543 }
544 }
545 }
546
547 if (rc & STORE_REF_ERROR_DF_CONFLICT)
548 error(_("some local refs could not be updated; try running\n"
549 " 'git remote prune %s' to remove any old, conflicting "
550 "branches"), remote_name);
551
552 abort:
553 strbuf_release(¬e);
554 free(url);
555 fclose(fp);
556 return rc;
557}
558
559/*
560 * We would want to bypass the object transfer altogether if
561 * everything we are going to fetch already exists and is connected
562 * locally.
563 */
564static int quickfetch(struct ref *ref_map)
565{
566 struct ref *rm = ref_map;
567
568 /*
569 * If we are deepening a shallow clone we already have these
570 * objects reachable. Running rev-list here will return with
571 * a good (0) exit status and we'll bypass the fetch that we
572 * really need to perform. Claiming failure now will ensure
573 * we perform the network exchange to deepen our history.
574 */
575 if (depth)
576 return -1;
577 return check_everything_connected(iterate_ref_map, 1, &rm);
578}
579
580static int fetch_refs(struct transport *transport, struct ref *ref_map)
581{
582 int ret = quickfetch(ref_map);
583 if (ret)
584 ret = transport_fetch_refs(transport, ref_map);
585 if (!ret)
586 ret |= store_updated_refs(transport->url,
587 transport->remote->name,
588 ref_map);
589 transport_unlock_pack(transport);
590 return ret;
591}
592
593static int prune_refs(struct refspec *refs, int ref_count, struct ref *ref_map)
594{
595 int result = 0;
596 struct ref *ref, *stale_refs = get_stale_heads(refs, ref_count, ref_map);
597 const char *dangling_msg = dry_run
598 ? _(" (%s will become dangling)")
599 : _(" (%s has become dangling)");
600
601 for (ref = stale_refs; ref; ref = ref->next) {
602 if (!dry_run)
603 result |= delete_ref(ref->name, NULL, 0);
604 if (verbosity >= 0) {
605 fprintf(stderr, " x %-*s %-*s -> %s\n",
606 TRANSPORT_SUMMARY(_("[deleted]")),
607 REFCOL_WIDTH, _("(none)"), prettify_refname(ref->name));
608 warn_dangling_symref(stderr, dangling_msg, ref->name);
609 }
610 }
611 free_refs(stale_refs);
612 return result;
613}
614
615static int add_existing(const char *refname, const unsigned char *sha1,
616 int flag, void *cbdata)
617{
618 struct string_list *list = (struct string_list *)cbdata;
619 struct string_list_item *item = string_list_insert(list, refname);
620 item->util = xmalloc(20);
621 hashcpy(item->util, sha1);
622 return 0;
623}
624
625static int will_fetch(struct ref **head, const unsigned char *sha1)
626{
627 struct ref *rm = *head;
628 while (rm) {
629 if (!hashcmp(rm->old_sha1, sha1))
630 return 1;
631 rm = rm->next;
632 }
633 return 0;
634}
635
636static void find_non_local_tags(struct transport *transport,
637 struct ref **head,
638 struct ref ***tail)
639{
640 struct string_list existing_refs = STRING_LIST_INIT_DUP;
641 struct string_list remote_refs = STRING_LIST_INIT_NODUP;
642 const struct ref *ref;
643 struct string_list_item *item = NULL;
644
645 for_each_ref(add_existing, &existing_refs);
646 for (ref = transport_get_remote_refs(transport); ref; ref = ref->next) {
647 if (prefixcmp(ref->name, "refs/tags/"))
648 continue;
649
650 /*
651 * The peeled ref always follows the matching base
652 * ref, so if we see a peeled ref that we don't want
653 * to fetch then we can mark the ref entry in the list
654 * as one to ignore by setting util to NULL.
655 */
656 if (!suffixcmp(ref->name, "^{}")) {
657 if (item && !has_sha1_file(ref->old_sha1) &&
658 !will_fetch(head, ref->old_sha1) &&
659 !has_sha1_file(item->util) &&
660 !will_fetch(head, item->util))
661 item->util = NULL;
662 item = NULL;
663 continue;
664 }
665
666 /*
667 * If item is non-NULL here, then we previously saw a
668 * ref not followed by a peeled reference, so we need
669 * to check if it is a lightweight tag that we want to
670 * fetch.
671 */
672 if (item && !has_sha1_file(item->util) &&
673 !will_fetch(head, item->util))
674 item->util = NULL;
675
676 item = NULL;
677
678 /* skip duplicates and refs that we already have */
679 if (string_list_has_string(&remote_refs, ref->name) ||
680 string_list_has_string(&existing_refs, ref->name))
681 continue;
682
683 item = string_list_insert(&remote_refs, ref->name);
684 item->util = (void *)ref->old_sha1;
685 }
686 string_list_clear(&existing_refs, 1);
687
688 /*
689 * We may have a final lightweight tag that needs to be
690 * checked to see if it needs fetching.
691 */
692 if (item && !has_sha1_file(item->util) &&
693 !will_fetch(head, item->util))
694 item->util = NULL;
695
696 /*
697 * For all the tags in the remote_refs string list,
698 * add them to the list of refs to be fetched
699 */
700 for_each_string_list_item(item, &remote_refs) {
701 /* Unless we have already decided to ignore this item... */
702 if (item->util)
703 {
704 struct ref *rm = alloc_ref(item->string);
705 rm->peer_ref = alloc_ref(item->string);
706 hashcpy(rm->old_sha1, item->util);
707 **tail = rm;
708 *tail = &rm->next;
709 }
710 }
711
712 string_list_clear(&remote_refs, 0);
713}
714
715static void check_not_current_branch(struct ref *ref_map)
716{
717 struct branch *current_branch = branch_get(NULL);
718
719 if (is_bare_repository() || !current_branch)
720 return;
721
722 for (; ref_map; ref_map = ref_map->next)
723 if (ref_map->peer_ref && !strcmp(current_branch->refname,
724 ref_map->peer_ref->name))
725 die(_("Refusing to fetch into current branch %s "
726 "of non-bare repository"), current_branch->refname);
727}
728
729static int truncate_fetch_head(void)
730{
731 char *filename = git_path("FETCH_HEAD");
732 FILE *fp = fopen(filename, "w");
733
734 if (!fp)
735 return error(_("cannot open %s: %s\n"), filename, strerror(errno));
736 fclose(fp);
737 return 0;
738}
739
740static void set_option(struct transport *transport, const char *name, const char *value)
741{
742 int r = transport_set_option(transport, name, value);
743 if (r < 0)
744 die(_("Option \"%s\" value \"%s\" is not valid for %s"),
745 name, value, transport->url);
746 if (r > 0)
747 warning(_("Option \"%s\" is ignored for %s\n"),
748 name, transport->url);
749}
750
751static struct transport *prepare_transport(struct remote *remote)
752{
753 struct transport *transport;
754 transport = transport_get(remote, NULL);
755 transport_set_verbosity(transport, verbosity, progress);
756 if (upload_pack)
757 set_option(transport, TRANS_OPT_UPLOADPACK, upload_pack);
758 if (keep)
759 set_option(transport, TRANS_OPT_KEEP, "yes");
760 if (depth)
761 set_option(transport, TRANS_OPT_DEPTH, depth);
762 return transport;
763}
764
765static void backfill_tags(struct transport *transport, struct ref *ref_map)
766{
767 if (transport->cannot_reuse) {
768 gsecondary = prepare_transport(transport->remote);
769 transport = gsecondary;
770 }
771
772 transport_set_option(transport, TRANS_OPT_FOLLOWTAGS, NULL);
773 transport_set_option(transport, TRANS_OPT_DEPTH, "0");
774 fetch_refs(transport, ref_map);
775
776 if (gsecondary) {
777 transport_disconnect(gsecondary);
778 gsecondary = NULL;
779 }
780}
781
782static int do_fetch(struct transport *transport,
783 struct refspec *refs, int ref_count)
784{
785 struct string_list existing_refs = STRING_LIST_INIT_DUP;
786 struct ref *ref_map;
787 struct ref *rm;
788 int autotags = (transport->remote->fetch_tags == 1);
789 int retcode = 0;
790
791 for_each_ref(add_existing, &existing_refs);
792
793 if (tags == TAGS_DEFAULT) {
794 if (transport->remote->fetch_tags == 2)
795 tags = TAGS_SET;
796 if (transport->remote->fetch_tags == -1)
797 tags = TAGS_UNSET;
798 }
799
800 if (!transport->get_refs_list || !transport->fetch)
801 die(_("Don't know how to fetch from %s"), transport->url);
802
803 /* if not appending, truncate FETCH_HEAD */
804 if (!append && !dry_run) {
805 retcode = truncate_fetch_head();
806 if (retcode)
807 goto cleanup;
808 }
809
810 ref_map = get_ref_map(transport, refs, ref_count, tags, &autotags);
811 if (!update_head_ok)
812 check_not_current_branch(ref_map);
813
814 for (rm = ref_map; rm; rm = rm->next) {
815 if (rm->peer_ref) {
816 struct string_list_item *peer_item =
817 string_list_lookup(&existing_refs,
818 rm->peer_ref->name);
819 if (peer_item)
820 hashcpy(rm->peer_ref->old_sha1,
821 peer_item->util);
822 }
823 }
824
825 if (tags == TAGS_DEFAULT && autotags)
826 transport_set_option(transport, TRANS_OPT_FOLLOWTAGS, "1");
827 if (fetch_refs(transport, ref_map)) {
828 free_refs(ref_map);
829 retcode = 1;
830 goto cleanup;
831 }
832 if (prune) {
833 /*
834 * If --tags was specified, pretend that the user gave us
835 * the canonical tags refspec
836 */
837 if (tags == TAGS_SET) {
838 const char *tags_str = "refs/tags/*:refs/tags/*";
839 struct refspec *tags_refspec, *refspec;
840
841 /* Copy the refspec and add the tags to it */
842 refspec = xcalloc(ref_count + 1, sizeof(struct refspec));
843 tags_refspec = parse_fetch_refspec(1, &tags_str);
844 memcpy(refspec, refs, ref_count * sizeof(struct refspec));
845 memcpy(&refspec[ref_count], tags_refspec, sizeof(struct refspec));
846 ref_count++;
847
848 prune_refs(refspec, ref_count, ref_map);
849
850 ref_count--;
851 /* The rest of the strings belong to fetch_one */
852 free_refspec(1, tags_refspec);
853 free(refspec);
854 } else if (ref_count) {
855 prune_refs(refs, ref_count, ref_map);
856 } else {
857 prune_refs(transport->remote->fetch, transport->remote->fetch_refspec_nr, ref_map);
858 }
859 }
860 free_refs(ref_map);
861
862 /* if neither --no-tags nor --tags was specified, do automated tag
863 * following ... */
864 if (tags == TAGS_DEFAULT && autotags) {
865 struct ref **tail = &ref_map;
866 ref_map = NULL;
867 find_non_local_tags(transport, &ref_map, &tail);
868 if (ref_map)
869 backfill_tags(transport, ref_map);
870 free_refs(ref_map);
871 }
872
873 cleanup:
874 string_list_clear(&existing_refs, 1);
875 return retcode;
876}
877
878static int get_one_remote_for_fetch(struct remote *remote, void *priv)
879{
880 struct string_list *list = priv;
881 if (!remote->skip_default_update)
882 string_list_append(list, remote->name);
883 return 0;
884}
885
886struct remote_group_data {
887 const char *name;
888 struct string_list *list;
889};
890
891static int get_remote_group(const char *key, const char *value, void *priv)
892{
893 struct remote_group_data *g = priv;
894
895 if (!prefixcmp(key, "remotes.") &&
896 !strcmp(key + 8, g->name)) {
897 /* split list by white space */
898 int space = strcspn(value, " \t\n");
899 while (*value) {
900 if (space > 1) {
901 string_list_append(g->list,
902 xstrndup(value, space));
903 }
904 value += space + (value[space] != '\0');
905 space = strcspn(value, " \t\n");
906 }
907 }
908
909 return 0;
910}
911
912static int add_remote_or_group(const char *name, struct string_list *list)
913{
914 int prev_nr = list->nr;
915 struct remote_group_data g;
916 g.name = name; g.list = list;
917
918 git_config(get_remote_group, &g);
919 if (list->nr == prev_nr) {
920 struct remote *remote;
921 if (!remote_is_configured(name))
922 return 0;
923 remote = remote_get(name);
924 string_list_append(list, remote->name);
925 }
926 return 1;
927}
928
929static void add_options_to_argv(struct argv_array *argv)
930{
931 if (dry_run)
932 argv_array_push(argv, "--dry-run");
933 if (prune > 0)
934 argv_array_push(argv, "--prune");
935 if (update_head_ok)
936 argv_array_push(argv, "--update-head-ok");
937 if (force)
938 argv_array_push(argv, "--force");
939 if (keep)
940 argv_array_push(argv, "--keep");
941 if (recurse_submodules == RECURSE_SUBMODULES_ON)
942 argv_array_push(argv, "--recurse-submodules");
943 else if (recurse_submodules == RECURSE_SUBMODULES_ON_DEMAND)
944 argv_array_push(argv, "--recurse-submodules=on-demand");
945 if (tags == TAGS_SET)
946 argv_array_push(argv, "--tags");
947 else if (tags == TAGS_UNSET)
948 argv_array_push(argv, "--no-tags");
949 if (verbosity >= 2)
950 argv_array_push(argv, "-v");
951 if (verbosity >= 1)
952 argv_array_push(argv, "-v");
953 else if (verbosity < 0)
954 argv_array_push(argv, "-q");
955
956}
957
958static int fetch_multiple(struct string_list *list)
959{
960 int i, result = 0;
961 struct argv_array argv = ARGV_ARRAY_INIT;
962
963 if (!append && !dry_run) {
964 int errcode = truncate_fetch_head();
965 if (errcode)
966 return errcode;
967 }
968
969 argv_array_pushl(&argv, "fetch", "--append", NULL);
970 add_options_to_argv(&argv);
971
972 for (i = 0; i < list->nr; i++) {
973 const char *name = list->items[i].string;
974 argv_array_push(&argv, name);
975 if (verbosity >= 0)
976 printf(_("Fetching %s\n"), name);
977 if (run_command_v_opt(argv.argv, RUN_GIT_CMD)) {
978 error(_("Could not fetch %s"), name);
979 result = 1;
980 }
981 argv_array_pop(&argv);
982 }
983
984 argv_array_clear(&argv);
985 return result;
986}
987
988static int fetch_one(struct remote *remote, int argc, const char **argv)
989{
990 int i;
991 static const char **refs = NULL;
992 struct refspec *refspec;
993 int ref_nr = 0;
994 int exit_code;
995
996 if (!remote)
997 die(_("No remote repository specified. Please, specify either a URL or a\n"
998 "remote name from which new revisions should be fetched."));
999
1000 gtransport = prepare_transport(remote);
1001
1002 if (prune < 0) {
1003 /* no command line request */
1004 if (0 <= gtransport->remote->prune)
1005 prune = gtransport->remote->prune;
1006 else if (0 <= fetch_prune_config)
1007 prune = fetch_prune_config;
1008 else
1009 prune = PRUNE_BY_DEFAULT;
1010 }
1011
1012 if (argc > 0) {
1013 int j = 0;
1014 refs = xcalloc(argc + 1, sizeof(const char *));
1015 for (i = 0; i < argc; i++) {
1016 if (!strcmp(argv[i], "tag")) {
1017 char *ref;
1018 i++;
1019 if (i >= argc)
1020 die(_("You need to specify a tag name."));
1021 ref = xmalloc(strlen(argv[i]) * 2 + 22);
1022 strcpy(ref, "refs/tags/");
1023 strcat(ref, argv[i]);
1024 strcat(ref, ":refs/tags/");
1025 strcat(ref, argv[i]);
1026 refs[j++] = ref;
1027 } else
1028 refs[j++] = argv[i];
1029 }
1030 refs[j] = NULL;
1031 ref_nr = j;
1032 }
1033
1034 sigchain_push_common(unlock_pack_on_signal);
1035 atexit(unlock_pack);
1036 refspec = parse_fetch_refspec(ref_nr, refs);
1037 exit_code = do_fetch(gtransport, refspec, ref_nr);
1038 free_refspec(ref_nr, refspec);
1039 transport_disconnect(gtransport);
1040 gtransport = NULL;
1041 return exit_code;
1042}
1043
1044int cmd_fetch(int argc, const char **argv, const char *prefix)
1045{
1046 int i;
1047 struct string_list list = STRING_LIST_INIT_NODUP;
1048 struct remote *remote;
1049 int result = 0;
1050 static const char *argv_gc_auto[] = {
1051 "gc", "--auto", NULL,
1052 };
1053
1054 packet_trace_identity("fetch");
1055
1056 /* Record the command line for the reflog */
1057 strbuf_addstr(&default_rla, "fetch");
1058 for (i = 1; i < argc; i++)
1059 strbuf_addf(&default_rla, " %s", argv[i]);
1060
1061 git_config(git_fetch_config, NULL);
1062
1063 argc = parse_options(argc, argv, prefix,
1064 builtin_fetch_options, builtin_fetch_usage, 0);
1065
1066 if (unshallow) {
1067 if (depth)
1068 die(_("--depth and --unshallow cannot be used together"));
1069 else if (!is_repository_shallow())
1070 die(_("--unshallow on a complete repository does not make sense"));
1071 else {
1072 static char inf_depth[12];
1073 sprintf(inf_depth, "%d", INFINITE_DEPTH);
1074 depth = inf_depth;
1075 }
1076 }
1077
1078 /* no need to be strict, transport_set_option() will validate it again */
1079 if (depth && atoi(depth) < 1)
1080 die(_("depth %s is not a positive number"), depth);
1081
1082 if (recurse_submodules != RECURSE_SUBMODULES_OFF) {
1083 if (recurse_submodules_default) {
1084 int arg = parse_fetch_recurse_submodules_arg("--recurse-submodules-default", recurse_submodules_default);
1085 set_config_fetch_recurse_submodules(arg);
1086 }
1087 gitmodules_config();
1088 git_config(submodule_config, NULL);
1089 }
1090
1091 if (all) {
1092 if (argc == 1)
1093 die(_("fetch --all does not take a repository argument"));
1094 else if (argc > 1)
1095 die(_("fetch --all does not make sense with refspecs"));
1096 (void) for_each_remote(get_one_remote_for_fetch, &list);
1097 result = fetch_multiple(&list);
1098 } else if (argc == 0) {
1099 /* No arguments -- use default remote */
1100 remote = remote_get(NULL);
1101 result = fetch_one(remote, argc, argv);
1102 } else if (multiple) {
1103 /* All arguments are assumed to be remotes or groups */
1104 for (i = 0; i < argc; i++)
1105 if (!add_remote_or_group(argv[i], &list))
1106 die(_("No such remote or remote group: %s"), argv[i]);
1107 result = fetch_multiple(&list);
1108 } else {
1109 /* Single remote or group */
1110 (void) add_remote_or_group(argv[0], &list);
1111 if (list.nr > 1) {
1112 /* More than one remote */
1113 if (argc > 1)
1114 die(_("Fetching a group and specifying refspecs does not make sense"));
1115 result = fetch_multiple(&list);
1116 } else {
1117 /* Zero or one remotes */
1118 remote = remote_get(argv[0]);
1119 result = fetch_one(remote, argc-1, argv+1);
1120 }
1121 }
1122
1123 if (!result && (recurse_submodules != RECURSE_SUBMODULES_OFF)) {
1124 struct argv_array options = ARGV_ARRAY_INIT;
1125
1126 add_options_to_argv(&options);
1127 result = fetch_populated_submodules(&options,
1128 submodule_prefix,
1129 recurse_submodules,
1130 verbosity < 0);
1131 argv_array_clear(&options);
1132 }
1133
1134 /* All names were strdup()ed or strndup()ed */
1135 list.strdup_strings = 1;
1136 string_list_clear(&list, 0);
1137
1138 run_command_v_opt(argv_gc_auto, RUN_GIT_CMD);
1139
1140 return result;
1141}