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