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