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