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