Merge branch 'sg/subtree-signed-commits' into pu
[git] / builtin / fetch.c
1 /*
2  * "git fetch"
3  */
4 #include "cache.h"
5 #include "config.h"
6 #include "repository.h"
7 #include "refs.h"
8 #include "commit.h"
9 #include "builtin.h"
10 #include "string-list.h"
11 #include "remote.h"
12 #include "transport.h"
13 #include "run-command.h"
14 #include "parse-options.h"
15 #include "sigchain.h"
16 #include "submodule-config.h"
17 #include "submodule.h"
18 #include "connected.h"
19 #include "argv-array.h"
20 #include "utf8.h"
21 #include "packfile.h"
22 #include "list-objects-filter-options.h"
23
24 static const char * const builtin_fetch_usage[] = {
25         N_("git fetch [<options>] [<repository> [<refspec>...]]"),
26         N_("git fetch [<options>] <group>"),
27         N_("git fetch --multiple [<options>] [(<repository> | <group>)...]"),
28         N_("git fetch --all [<options>]"),
29         NULL
30 };
31
32 enum {
33         TAGS_UNSET = 0,
34         TAGS_DEFAULT = 1,
35         TAGS_SET = 2
36 };
37
38 static int fetch_prune_config = -1; /* unspecified */
39 static int prune = -1; /* unspecified */
40 #define PRUNE_BY_DEFAULT 0 /* do we prune by default? */
41
42 static int fetch_prune_tags_config = -1; /* unspecified */
43 static int prune_tags = -1; /* unspecified */
44 #define PRUNE_TAGS_BY_DEFAULT 0 /* do we prune tags by default? */
45
46 static int all, append, dry_run, force, keep, multiple, update_head_ok, verbosity, deepen_relative;
47 static int progress = -1;
48 static int tags = TAGS_DEFAULT, unshallow, update_shallow, deepen;
49 static int max_children = 1;
50 static enum transport_family family;
51 static const char *depth;
52 static const char *deepen_since;
53 static const char *upload_pack;
54 static struct string_list deepen_not = STRING_LIST_INIT_NODUP;
55 static struct strbuf default_rla = STRBUF_INIT;
56 static struct transport *gtransport;
57 static struct transport *gsecondary;
58 static const char *submodule_prefix = "";
59 static int recurse_submodules = RECURSE_SUBMODULES_DEFAULT;
60 static int recurse_submodules_default = RECURSE_SUBMODULES_ON_DEMAND;
61 static int shown_url = 0;
62 static int refmap_alloc, refmap_nr;
63 static const char **refmap_array;
64 static struct list_objects_filter_options filter_options;
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
73         if (!strcmp(k, "fetch.prunetags")) {
74                 fetch_prune_tags_config = git_config_bool(k, v);
75                 return 0;
76         }
77
78         if (!strcmp(k, "submodule.recurse")) {
79                 int r = git_config_bool(k, v) ?
80                         RECURSE_SUBMODULES_ON : RECURSE_SUBMODULES_OFF;
81                 recurse_submodules = r;
82         }
83
84         if (!strcmp(k, "submodule.fetchjobs")) {
85                 max_children = parse_submodule_fetchjobs(k, v);
86                 return 0;
87         } else if (!strcmp(k, "fetch.recursesubmodules")) {
88                 recurse_submodules = parse_fetch_recurse_submodules_arg(k, v);
89                 return 0;
90         }
91
92         return git_default_config(k, v, cb);
93 }
94
95 static int gitmodules_fetch_config(const char *var, const char *value, void *cb)
96 {
97         if (!strcmp(var, "submodule.fetchjobs")) {
98                 max_children = parse_submodule_fetchjobs(var, value);
99                 return 0;
100         } else if (!strcmp(var, "fetch.recursesubmodules")) {
101                 recurse_submodules = parse_fetch_recurse_submodules_arg(var, value);
102                 return 0;
103         }
104
105         return 0;
106 }
107
108 static int parse_refmap_arg(const struct option *opt, const char *arg, int unset)
109 {
110         ALLOC_GROW(refmap_array, refmap_nr + 1, refmap_alloc);
111
112         /*
113          * "git fetch --refmap='' origin foo"
114          * can be used to tell the command not to store anywhere
115          */
116         if (*arg)
117                 refmap_array[refmap_nr++] = arg;
118         return 0;
119 }
120
121 static struct option builtin_fetch_options[] = {
122         OPT__VERBOSITY(&verbosity),
123         OPT_BOOL(0, "all", &all,
124                  N_("fetch from all remotes")),
125         OPT_BOOL('a', "append", &append,
126                  N_("append to .git/FETCH_HEAD instead of overwriting")),
127         OPT_STRING(0, "upload-pack", &upload_pack, N_("path"),
128                    N_("path to upload pack on remote end")),
129         OPT__FORCE(&force, N_("force overwrite of local branch"), 0),
130         OPT_BOOL('m', "multiple", &multiple,
131                  N_("fetch from multiple remotes")),
132         OPT_SET_INT('t', "tags", &tags,
133                     N_("fetch all tags and associated objects"), TAGS_SET),
134         OPT_SET_INT('n', NULL, &tags,
135                     N_("do not fetch all tags (--no-tags)"), TAGS_UNSET),
136         OPT_INTEGER('j', "jobs", &max_children,
137                     N_("number of submodules fetched in parallel")),
138         OPT_BOOL('p', "prune", &prune,
139                  N_("prune remote-tracking branches no longer on remote")),
140         OPT_BOOL('P', "prune-tags", &prune_tags,
141                  N_("prune local tags no longer on remote and clobber changed tags")),
142         { OPTION_CALLBACK, 0, "recurse-submodules", &recurse_submodules, N_("on-demand"),
143                     N_("control recursive fetching of submodules"),
144                     PARSE_OPT_OPTARG, option_fetch_parse_recurse_submodules },
145         OPT_BOOL(0, "dry-run", &dry_run,
146                  N_("dry run")),
147         OPT_BOOL('k', "keep", &keep, N_("keep downloaded pack")),
148         OPT_BOOL('u', "update-head-ok", &update_head_ok,
149                     N_("allow updating of HEAD ref")),
150         OPT_BOOL(0, "progress", &progress, N_("force progress reporting")),
151         OPT_STRING(0, "depth", &depth, N_("depth"),
152                    N_("deepen history of shallow clone")),
153         OPT_STRING(0, "shallow-since", &deepen_since, N_("time"),
154                    N_("deepen history of shallow repository based on time")),
155         OPT_STRING_LIST(0, "shallow-exclude", &deepen_not, N_("revision"),
156                         N_("deepen history of shallow clone, excluding rev")),
157         OPT_INTEGER(0, "deepen", &deepen_relative,
158                     N_("deepen history of shallow clone")),
159         { OPTION_SET_INT, 0, "unshallow", &unshallow, NULL,
160                    N_("convert to a complete repository"),
161                    PARSE_OPT_NONEG | PARSE_OPT_NOARG, NULL, 1 },
162         { OPTION_STRING, 0, "submodule-prefix", &submodule_prefix, N_("dir"),
163                    N_("prepend this to submodule path output"), PARSE_OPT_HIDDEN },
164         { OPTION_CALLBACK, 0, "recurse-submodules-default",
165                    &recurse_submodules_default, N_("on-demand"),
166                    N_("default for recursive fetching of submodules "
167                       "(lower priority than config files)"),
168                    PARSE_OPT_HIDDEN, option_fetch_parse_recurse_submodules },
169         OPT_BOOL(0, "update-shallow", &update_shallow,
170                  N_("accept refs that update .git/shallow")),
171         { OPTION_CALLBACK, 0, "refmap", NULL, N_("refmap"),
172           N_("specify fetch refmap"), PARSE_OPT_NONEG, parse_refmap_arg },
173         OPT_SET_INT('4', "ipv4", &family, N_("use IPv4 addresses only"),
174                         TRANSPORT_FAMILY_IPV4),
175         OPT_SET_INT('6', "ipv6", &family, N_("use IPv6 addresses only"),
176                         TRANSPORT_FAMILY_IPV6),
177         OPT_PARSE_LIST_OBJECTS_FILTER(&filter_options),
178         OPT_END()
179 };
180
181 static void unlock_pack(void)
182 {
183         if (gtransport)
184                 transport_unlock_pack(gtransport);
185         if (gsecondary)
186                 transport_unlock_pack(gsecondary);
187 }
188
189 static void unlock_pack_on_signal(int signo)
190 {
191         unlock_pack();
192         sigchain_pop(signo);
193         raise(signo);
194 }
195
196 static void add_merge_config(struct ref **head,
197                            const struct ref *remote_refs,
198                            struct branch *branch,
199                            struct ref ***tail)
200 {
201         int i;
202
203         for (i = 0; i < branch->merge_nr; i++) {
204                 struct ref *rm, **old_tail = *tail;
205                 struct refspec refspec;
206
207                 for (rm = *head; rm; rm = rm->next) {
208                         if (branch_merge_matches(branch, i, rm->name)) {
209                                 rm->fetch_head_status = FETCH_HEAD_MERGE;
210                                 break;
211                         }
212                 }
213                 if (rm)
214                         continue;
215
216                 /*
217                  * Not fetched to a remote-tracking branch?  We need to fetch
218                  * it anyway to allow this branch's "branch.$name.merge"
219                  * to be honored by 'git pull', but we do not have to
220                  * fail if branch.$name.merge is misconfigured to point
221                  * at a nonexisting branch.  If we were indeed called by
222                  * 'git pull', it will notice the misconfiguration because
223                  * there is no entry in the resulting FETCH_HEAD marked
224                  * for merging.
225                  */
226                 memset(&refspec, 0, sizeof(refspec));
227                 refspec.src = branch->merge[i]->src;
228                 get_fetch_map(remote_refs, &refspec, tail, 1);
229                 for (rm = *old_tail; rm; rm = rm->next)
230                         rm->fetch_head_status = FETCH_HEAD_MERGE;
231         }
232 }
233
234 static int add_existing(const char *refname, const struct object_id *oid,
235                         int flag, void *cbdata)
236 {
237         struct string_list *list = (struct string_list *)cbdata;
238         struct string_list_item *item = string_list_insert(list, refname);
239         struct object_id *old_oid = xmalloc(sizeof(*old_oid));
240
241         oidcpy(old_oid, oid);
242         item->util = old_oid;
243         return 0;
244 }
245
246 static int will_fetch(struct ref **head, const unsigned char *sha1)
247 {
248         struct ref *rm = *head;
249         while (rm) {
250                 if (!hashcmp(rm->old_oid.hash, sha1))
251                         return 1;
252                 rm = rm->next;
253         }
254         return 0;
255 }
256
257 static void find_non_local_tags(struct transport *transport,
258                         struct ref **head,
259                         struct ref ***tail)
260 {
261         struct string_list existing_refs = STRING_LIST_INIT_DUP;
262         struct string_list remote_refs = STRING_LIST_INIT_NODUP;
263         const struct ref *ref;
264         struct string_list_item *item = NULL;
265
266         for_each_ref(add_existing, &existing_refs);
267         for (ref = transport_get_remote_refs(transport, NULL); ref; ref = ref->next) {
268                 if (!starts_with(ref->name, "refs/tags/"))
269                         continue;
270
271                 /*
272                  * The peeled ref always follows the matching base
273                  * ref, so if we see a peeled ref that we don't want
274                  * to fetch then we can mark the ref entry in the list
275                  * as one to ignore by setting util to NULL.
276                  */
277                 if (ends_with(ref->name, "^{}")) {
278                         if (item &&
279                             !has_object_file_with_flags(&ref->old_oid,
280                                                         OBJECT_INFO_QUICK) &&
281                             !will_fetch(head, ref->old_oid.hash) &&
282                             !has_sha1_file_with_flags(item->util,
283                                                       OBJECT_INFO_QUICK) &&
284                             !will_fetch(head, item->util))
285                                 item->util = NULL;
286                         item = NULL;
287                         continue;
288                 }
289
290                 /*
291                  * If item is non-NULL here, then we previously saw a
292                  * ref not followed by a peeled reference, so we need
293                  * to check if it is a lightweight tag that we want to
294                  * fetch.
295                  */
296                 if (item &&
297                     !has_sha1_file_with_flags(item->util, OBJECT_INFO_QUICK) &&
298                     !will_fetch(head, item->util))
299                         item->util = NULL;
300
301                 item = NULL;
302
303                 /* skip duplicates and refs that we already have */
304                 if (string_list_has_string(&remote_refs, ref->name) ||
305                     string_list_has_string(&existing_refs, ref->name))
306                         continue;
307
308                 item = string_list_insert(&remote_refs, ref->name);
309                 item->util = (void *)&ref->old_oid;
310         }
311         string_list_clear(&existing_refs, 1);
312
313         /*
314          * We may have a final lightweight tag that needs to be
315          * checked to see if it needs fetching.
316          */
317         if (item &&
318             !has_sha1_file_with_flags(item->util, OBJECT_INFO_QUICK) &&
319             !will_fetch(head, item->util))
320                 item->util = NULL;
321
322         /*
323          * For all the tags in the remote_refs string list,
324          * add them to the list of refs to be fetched
325          */
326         for_each_string_list_item(item, &remote_refs) {
327                 /* Unless we have already decided to ignore this item... */
328                 if (item->util)
329                 {
330                         struct ref *rm = alloc_ref(item->string);
331                         rm->peer_ref = alloc_ref(item->string);
332                         oidcpy(&rm->old_oid, item->util);
333                         **tail = rm;
334                         *tail = &rm->next;
335                 }
336         }
337
338         string_list_clear(&remote_refs, 0);
339 }
340
341 static struct ref *get_ref_map(struct transport *transport,
342                                struct refspec *refspecs, int refspec_count,
343                                int tags, int *autotags)
344 {
345         int i;
346         struct ref *rm;
347         struct ref *ref_map = NULL;
348         struct ref **tail = &ref_map;
349         struct argv_array ref_patterns = ARGV_ARRAY_INIT;
350
351         /* opportunistically-updated references: */
352         struct ref *orefs = NULL, **oref_tail = &orefs;
353
354         const struct ref *remote_refs;
355
356         for (i = 0; i < refspec_count; i++) {
357                 if (!refspecs[i].exact_sha1)
358                         argv_array_push(&ref_patterns, refspecs[i].src);
359         }
360
361         remote_refs = transport_get_remote_refs(transport, &ref_patterns);
362
363         argv_array_clear(&ref_patterns);
364
365         if (refspec_count) {
366                 struct refspec *fetch_refspec;
367                 int fetch_refspec_nr;
368
369                 for (i = 0; i < refspec_count; i++) {
370                         get_fetch_map(remote_refs, &refspecs[i], &tail, 0);
371                         if (refspecs[i].dst && refspecs[i].dst[0])
372                                 *autotags = 1;
373                 }
374                 /* Merge everything on the command line (but not --tags) */
375                 for (rm = ref_map; rm; rm = rm->next)
376                         rm->fetch_head_status = FETCH_HEAD_MERGE;
377
378                 /*
379                  * For any refs that we happen to be fetching via
380                  * command-line arguments, the destination ref might
381                  * have been missing or have been different than the
382                  * remote-tracking ref that would be derived from the
383                  * configured refspec.  In these cases, we want to
384                  * take the opportunity to update their configured
385                  * remote-tracking reference.  However, we do not want
386                  * to mention these entries in FETCH_HEAD at all, as
387                  * they would simply be duplicates of existing
388                  * entries, so we set them FETCH_HEAD_IGNORE below.
389                  *
390                  * We compute these entries now, based only on the
391                  * refspecs specified on the command line.  But we add
392                  * them to the list following the refspecs resulting
393                  * from the tags option so that one of the latter,
394                  * which has FETCH_HEAD_NOT_FOR_MERGE, is not removed
395                  * by ref_remove_duplicates() in favor of one of these
396                  * opportunistic entries with FETCH_HEAD_IGNORE.
397                  */
398                 if (refmap_array) {
399                         fetch_refspec = parse_fetch_refspec(refmap_nr, refmap_array);
400                         fetch_refspec_nr = refmap_nr;
401                 } else {
402                         fetch_refspec = transport->remote->fetch;
403                         fetch_refspec_nr = transport->remote->fetch_refspec_nr;
404                 }
405
406                 for (i = 0; i < fetch_refspec_nr; i++)
407                         get_fetch_map(ref_map, &fetch_refspec[i], &oref_tail, 1);
408         } else if (refmap_array) {
409                 die("--refmap option is only meaningful with command-line refspec(s).");
410         } else {
411                 /* Use the defaults */
412                 struct remote *remote = transport->remote;
413                 struct branch *branch = branch_get(NULL);
414                 int has_merge = branch_has_merge_config(branch);
415                 if (remote &&
416                     (remote->fetch_refspec_nr ||
417                      /* Note: has_merge implies non-NULL branch->remote_name */
418                      (has_merge && !strcmp(branch->remote_name, remote->name)))) {
419                         for (i = 0; i < remote->fetch_refspec_nr; i++) {
420                                 get_fetch_map(remote_refs, &remote->fetch[i], &tail, 0);
421                                 if (remote->fetch[i].dst &&
422                                     remote->fetch[i].dst[0])
423                                         *autotags = 1;
424                                 if (!i && !has_merge && ref_map &&
425                                     !remote->fetch[0].pattern)
426                                         ref_map->fetch_head_status = FETCH_HEAD_MERGE;
427                         }
428                         /*
429                          * if the remote we're fetching from is the same
430                          * as given in branch.<name>.remote, we add the
431                          * ref given in branch.<name>.merge, too.
432                          *
433                          * Note: has_merge implies non-NULL branch->remote_name
434                          */
435                         if (has_merge &&
436                             !strcmp(branch->remote_name, remote->name))
437                                 add_merge_config(&ref_map, remote_refs, branch, &tail);
438                 } else {
439                         ref_map = get_remote_ref(remote_refs, "HEAD");
440                         if (!ref_map)
441                                 die(_("Couldn't find remote ref HEAD"));
442                         ref_map->fetch_head_status = FETCH_HEAD_MERGE;
443                         tail = &ref_map->next;
444                 }
445         }
446
447         if (tags == TAGS_SET)
448                 /* also fetch all tags */
449                 get_fetch_map(remote_refs, tag_refspec, &tail, 0);
450         else if (tags == TAGS_DEFAULT && *autotags)
451                 find_non_local_tags(transport, &ref_map, &tail);
452
453         /* Now append any refs to be updated opportunistically: */
454         *tail = orefs;
455         for (rm = orefs; rm; rm = rm->next) {
456                 rm->fetch_head_status = FETCH_HEAD_IGNORE;
457                 tail = &rm->next;
458         }
459
460         return ref_remove_duplicates(ref_map);
461 }
462
463 #define STORE_REF_ERROR_OTHER 1
464 #define STORE_REF_ERROR_DF_CONFLICT 2
465
466 static int s_update_ref(const char *action,
467                         struct ref *ref,
468                         int check_old)
469 {
470         char *msg;
471         char *rla = getenv("GIT_REFLOG_ACTION");
472         struct ref_transaction *transaction;
473         struct strbuf err = STRBUF_INIT;
474         int ret, df_conflict = 0;
475
476         if (dry_run)
477                 return 0;
478         if (!rla)
479                 rla = default_rla.buf;
480         msg = xstrfmt("%s: %s", rla, action);
481
482         transaction = ref_transaction_begin(&err);
483         if (!transaction ||
484             ref_transaction_update(transaction, ref->name,
485                                    &ref->new_oid,
486                                    check_old ? &ref->old_oid : NULL,
487                                    0, msg, &err))
488                 goto fail;
489
490         ret = ref_transaction_commit(transaction, &err);
491         if (ret) {
492                 df_conflict = (ret == TRANSACTION_NAME_CONFLICT);
493                 goto fail;
494         }
495
496         ref_transaction_free(transaction);
497         strbuf_release(&err);
498         free(msg);
499         return 0;
500 fail:
501         ref_transaction_free(transaction);
502         error("%s", err.buf);
503         strbuf_release(&err);
504         free(msg);
505         return df_conflict ? STORE_REF_ERROR_DF_CONFLICT
506                            : STORE_REF_ERROR_OTHER;
507 }
508
509 static int refcol_width = 10;
510 static int compact_format;
511
512 static void adjust_refcol_width(const struct ref *ref)
513 {
514         int max, rlen, llen, len;
515
516         /* uptodate lines are only shown on high verbosity level */
517         if (!verbosity && !oidcmp(&ref->peer_ref->old_oid, &ref->old_oid))
518                 return;
519
520         max    = term_columns();
521         rlen   = utf8_strwidth(prettify_refname(ref->name));
522
523         llen   = utf8_strwidth(prettify_refname(ref->peer_ref->name));
524
525         /*
526          * rough estimation to see if the output line is too long and
527          * should not be counted (we can't do precise calculation
528          * anyway because we don't know if the error explanation part
529          * will be printed in update_local_ref)
530          */
531         if (compact_format) {
532                 llen = 0;
533                 max = max * 2 / 3;
534         }
535         len = 21 /* flag and summary */ + rlen + 4 /* -> */ + llen;
536         if (len >= max)
537                 return;
538
539         /*
540          * Not precise calculation for compact mode because '*' can
541          * appear on the left hand side of '->' and shrink the column
542          * back.
543          */
544         if (refcol_width < rlen)
545                 refcol_width = rlen;
546 }
547
548 static void prepare_format_display(struct ref *ref_map)
549 {
550         struct ref *rm;
551         const char *format = "full";
552
553         git_config_get_string_const("fetch.output", &format);
554         if (!strcasecmp(format, "full"))
555                 compact_format = 0;
556         else if (!strcasecmp(format, "compact"))
557                 compact_format = 1;
558         else
559                 die(_("configuration fetch.output contains invalid value %s"),
560                     format);
561
562         for (rm = ref_map; rm; rm = rm->next) {
563                 if (rm->status == REF_STATUS_REJECT_SHALLOW ||
564                     !rm->peer_ref ||
565                     !strcmp(rm->name, "HEAD"))
566                         continue;
567
568                 adjust_refcol_width(rm);
569         }
570 }
571
572 static void print_remote_to_local(struct strbuf *display,
573                                   const char *remote, const char *local)
574 {
575         strbuf_addf(display, "%-*s -> %s", refcol_width, remote, local);
576 }
577
578 static int find_and_replace(struct strbuf *haystack,
579                             const char *needle,
580                             const char *placeholder)
581 {
582         const char *p = strstr(haystack->buf, needle);
583         int plen, nlen;
584
585         if (!p)
586                 return 0;
587
588         if (p > haystack->buf && p[-1] != '/')
589                 return 0;
590
591         plen = strlen(p);
592         nlen = strlen(needle);
593         if (plen > nlen && p[nlen] != '/')
594                 return 0;
595
596         strbuf_splice(haystack, p - haystack->buf, nlen,
597                       placeholder, strlen(placeholder));
598         return 1;
599 }
600
601 static void print_compact(struct strbuf *display,
602                           const char *remote, const char *local)
603 {
604         struct strbuf r = STRBUF_INIT;
605         struct strbuf l = STRBUF_INIT;
606
607         if (!strcmp(remote, local)) {
608                 strbuf_addf(display, "%-*s -> *", refcol_width, remote);
609                 return;
610         }
611
612         strbuf_addstr(&r, remote);
613         strbuf_addstr(&l, local);
614
615         if (!find_and_replace(&r, local, "*"))
616                 find_and_replace(&l, remote, "*");
617         print_remote_to_local(display, r.buf, l.buf);
618
619         strbuf_release(&r);
620         strbuf_release(&l);
621 }
622
623 static void format_display(struct strbuf *display, char code,
624                            const char *summary, const char *error,
625                            const char *remote, const char *local,
626                            int summary_width)
627 {
628         int width = (summary_width + strlen(summary) - gettext_width(summary));
629
630         strbuf_addf(display, "%c %-*s ", code, width, summary);
631         if (!compact_format)
632                 print_remote_to_local(display, remote, local);
633         else
634                 print_compact(display, remote, local);
635         if (error)
636                 strbuf_addf(display, "  (%s)", error);
637 }
638
639 static int update_local_ref(struct ref *ref,
640                             const char *remote,
641                             const struct ref *remote_ref,
642                             struct strbuf *display,
643                             int summary_width)
644 {
645         struct commit *current = NULL, *updated;
646         enum object_type type;
647         struct branch *current_branch = branch_get(NULL);
648         const char *pretty_ref = prettify_refname(ref->name);
649
650         type = sha1_object_info(ref->new_oid.hash, NULL);
651         if (type < 0)
652                 die(_("object %s not found"), oid_to_hex(&ref->new_oid));
653
654         if (!oidcmp(&ref->old_oid, &ref->new_oid)) {
655                 if (verbosity > 0)
656                         format_display(display, '=', _("[up to date]"), NULL,
657                                        remote, pretty_ref, summary_width);
658                 return 0;
659         }
660
661         if (current_branch &&
662             !strcmp(ref->name, current_branch->name) &&
663             !(update_head_ok || is_bare_repository()) &&
664             !is_null_oid(&ref->old_oid)) {
665                 /*
666                  * If this is the head, and it's not okay to update
667                  * the head, and the old value of the head isn't empty...
668                  */
669                 format_display(display, '!', _("[rejected]"),
670                                _("can't fetch in current branch"),
671                                remote, pretty_ref, summary_width);
672                 return 1;
673         }
674
675         if (!is_null_oid(&ref->old_oid) &&
676             starts_with(ref->name, "refs/tags/")) {
677                 int r;
678                 r = s_update_ref("updating tag", ref, 0);
679                 format_display(display, r ? '!' : 't', _("[tag update]"),
680                                r ? _("unable to update local ref") : NULL,
681                                remote, pretty_ref, summary_width);
682                 return r;
683         }
684
685         current = lookup_commit_reference_gently(&ref->old_oid, 1);
686         updated = lookup_commit_reference_gently(&ref->new_oid, 1);
687         if (!current || !updated) {
688                 const char *msg;
689                 const char *what;
690                 int r;
691                 /*
692                  * Nicely describe the new ref we're fetching.
693                  * Base this on the remote's ref name, as it's
694                  * more likely to follow a standard layout.
695                  */
696                 const char *name = remote_ref ? remote_ref->name : "";
697                 if (starts_with(name, "refs/tags/")) {
698                         msg = "storing tag";
699                         what = _("[new tag]");
700                 } else if (starts_with(name, "refs/heads/")) {
701                         msg = "storing head";
702                         what = _("[new branch]");
703                 } else {
704                         msg = "storing ref";
705                         what = _("[new ref]");
706                 }
707
708                 if ((recurse_submodules != RECURSE_SUBMODULES_OFF) &&
709                     (recurse_submodules != RECURSE_SUBMODULES_ON))
710                         check_for_new_submodule_commits(&ref->new_oid);
711                 r = s_update_ref(msg, ref, 0);
712                 format_display(display, r ? '!' : '*', what,
713                                r ? _("unable to update local ref") : NULL,
714                                remote, pretty_ref, summary_width);
715                 return r;
716         }
717
718         if (in_merge_bases(current, updated)) {
719                 struct strbuf quickref = STRBUF_INIT;
720                 int r;
721                 strbuf_add_unique_abbrev(&quickref, current->object.oid.hash, DEFAULT_ABBREV);
722                 strbuf_addstr(&quickref, "..");
723                 strbuf_add_unique_abbrev(&quickref, ref->new_oid.hash, DEFAULT_ABBREV);
724                 if ((recurse_submodules != RECURSE_SUBMODULES_OFF) &&
725                     (recurse_submodules != RECURSE_SUBMODULES_ON))
726                         check_for_new_submodule_commits(&ref->new_oid);
727                 r = s_update_ref("fast-forward", ref, 1);
728                 format_display(display, r ? '!' : ' ', quickref.buf,
729                                r ? _("unable to update local ref") : NULL,
730                                remote, pretty_ref, summary_width);
731                 strbuf_release(&quickref);
732                 return r;
733         } else if (force || ref->force) {
734                 struct strbuf quickref = STRBUF_INIT;
735                 int r;
736                 strbuf_add_unique_abbrev(&quickref, current->object.oid.hash, DEFAULT_ABBREV);
737                 strbuf_addstr(&quickref, "...");
738                 strbuf_add_unique_abbrev(&quickref, ref->new_oid.hash, DEFAULT_ABBREV);
739                 if ((recurse_submodules != RECURSE_SUBMODULES_OFF) &&
740                     (recurse_submodules != RECURSE_SUBMODULES_ON))
741                         check_for_new_submodule_commits(&ref->new_oid);
742                 r = s_update_ref("forced-update", ref, 1);
743                 format_display(display, r ? '!' : '+', quickref.buf,
744                                r ? _("unable to update local ref") : _("forced update"),
745                                remote, pretty_ref, summary_width);
746                 strbuf_release(&quickref);
747                 return r;
748         } else {
749                 format_display(display, '!', _("[rejected]"), _("non-fast-forward"),
750                                remote, pretty_ref, summary_width);
751                 return 1;
752         }
753 }
754
755 static int iterate_ref_map(void *cb_data, struct object_id *oid)
756 {
757         struct ref **rm = cb_data;
758         struct ref *ref = *rm;
759
760         while (ref && ref->status == REF_STATUS_REJECT_SHALLOW)
761                 ref = ref->next;
762         if (!ref)
763                 return -1; /* end of the list */
764         *rm = ref->next;
765         oidcpy(oid, &ref->old_oid);
766         return 0;
767 }
768
769 static int store_updated_refs(const char *raw_url, const char *remote_name,
770                 struct ref *ref_map)
771 {
772         FILE *fp;
773         struct commit *commit;
774         int url_len, i, rc = 0;
775         struct strbuf note = STRBUF_INIT;
776         const char *what, *kind;
777         struct ref *rm;
778         char *url;
779         const char *filename = dry_run ? "/dev/null" : git_path_fetch_head();
780         int want_status;
781         int summary_width = transport_summary_width(ref_map);
782
783         fp = fopen(filename, "a");
784         if (!fp)
785                 return error_errno(_("cannot open %s"), filename);
786
787         if (raw_url)
788                 url = transport_anonymize_url(raw_url);
789         else
790                 url = xstrdup("foreign");
791
792         rm = ref_map;
793         if (check_connected(iterate_ref_map, &rm, NULL)) {
794                 rc = error(_("%s did not send all necessary objects\n"), url);
795                 goto abort;
796         }
797
798         prepare_format_display(ref_map);
799
800         /*
801          * We do a pass for each fetch_head_status type in their enum order, so
802          * merged entries are written before not-for-merge. That lets readers
803          * use FETCH_HEAD as a refname to refer to the ref to be merged.
804          */
805         for (want_status = FETCH_HEAD_MERGE;
806              want_status <= FETCH_HEAD_IGNORE;
807              want_status++) {
808                 for (rm = ref_map; rm; rm = rm->next) {
809                         struct ref *ref = NULL;
810                         const char *merge_status_marker = "";
811
812                         if (rm->status == REF_STATUS_REJECT_SHALLOW) {
813                                 if (want_status == FETCH_HEAD_MERGE)
814                                         warning(_("reject %s because shallow roots are not allowed to be updated"),
815                                                 rm->peer_ref ? rm->peer_ref->name : rm->name);
816                                 continue;
817                         }
818
819                         commit = lookup_commit_reference_gently(&rm->old_oid,
820                                                                 1);
821                         if (!commit)
822                                 rm->fetch_head_status = FETCH_HEAD_NOT_FOR_MERGE;
823
824                         if (rm->fetch_head_status != want_status)
825                                 continue;
826
827                         if (rm->peer_ref) {
828                                 ref = alloc_ref(rm->peer_ref->name);
829                                 oidcpy(&ref->old_oid, &rm->peer_ref->old_oid);
830                                 oidcpy(&ref->new_oid, &rm->old_oid);
831                                 ref->force = rm->peer_ref->force;
832                         }
833
834
835                         if (!strcmp(rm->name, "HEAD")) {
836                                 kind = "";
837                                 what = "";
838                         }
839                         else if (starts_with(rm->name, "refs/heads/")) {
840                                 kind = "branch";
841                                 what = rm->name + 11;
842                         }
843                         else if (starts_with(rm->name, "refs/tags/")) {
844                                 kind = "tag";
845                                 what = rm->name + 10;
846                         }
847                         else if (starts_with(rm->name, "refs/remotes/")) {
848                                 kind = "remote-tracking branch";
849                                 what = rm->name + 13;
850                         }
851                         else {
852                                 kind = "";
853                                 what = rm->name;
854                         }
855
856                         url_len = strlen(url);
857                         for (i = url_len - 1; url[i] == '/' && 0 <= i; i--)
858                                 ;
859                         url_len = i + 1;
860                         if (4 < i && !strncmp(".git", url + i - 3, 4))
861                                 url_len = i - 3;
862
863                         strbuf_reset(&note);
864                         if (*what) {
865                                 if (*kind)
866                                         strbuf_addf(&note, "%s ", kind);
867                                 strbuf_addf(&note, "'%s' of ", what);
868                         }
869                         switch (rm->fetch_head_status) {
870                         case FETCH_HEAD_NOT_FOR_MERGE:
871                                 merge_status_marker = "not-for-merge";
872                                 /* fall-through */
873                         case FETCH_HEAD_MERGE:
874                                 fprintf(fp, "%s\t%s\t%s",
875                                         oid_to_hex(&rm->old_oid),
876                                         merge_status_marker,
877                                         note.buf);
878                                 for (i = 0; i < url_len; ++i)
879                                         if ('\n' == url[i])
880                                                 fputs("\\n", fp);
881                                         else
882                                                 fputc(url[i], fp);
883                                 fputc('\n', fp);
884                                 break;
885                         default:
886                                 /* do not write anything to FETCH_HEAD */
887                                 break;
888                         }
889
890                         strbuf_reset(&note);
891                         if (ref) {
892                                 rc |= update_local_ref(ref, what, rm, &note,
893                                                        summary_width);
894                                 free(ref);
895                         } else
896                                 format_display(&note, '*',
897                                                *kind ? kind : "branch", NULL,
898                                                *what ? what : "HEAD",
899                                                "FETCH_HEAD", summary_width);
900                         if (note.len) {
901                                 if (verbosity >= 0 && !shown_url) {
902                                         fprintf(stderr, _("From %.*s\n"),
903                                                         url_len, url);
904                                         shown_url = 1;
905                                 }
906                                 if (verbosity >= 0)
907                                         fprintf(stderr, " %s\n", note.buf);
908                         }
909                 }
910         }
911
912         if (rc & STORE_REF_ERROR_DF_CONFLICT)
913                 error(_("some local refs could not be updated; try running\n"
914                       " 'git remote prune %s' to remove any old, conflicting "
915                       "branches"), remote_name);
916
917  abort:
918         strbuf_release(&note);
919         free(url);
920         fclose(fp);
921         return rc;
922 }
923
924 /*
925  * We would want to bypass the object transfer altogether if
926  * everything we are going to fetch already exists and is connected
927  * locally.
928  */
929 static int quickfetch(struct ref *ref_map)
930 {
931         struct ref *rm = ref_map;
932         struct check_connected_options opt = CHECK_CONNECTED_INIT;
933
934         /*
935          * If we are deepening a shallow clone we already have these
936          * objects reachable.  Running rev-list here will return with
937          * a good (0) exit status and we'll bypass the fetch that we
938          * really need to perform.  Claiming failure now will ensure
939          * we perform the network exchange to deepen our history.
940          */
941         if (deepen)
942                 return -1;
943         opt.quiet = 1;
944         return check_connected(iterate_ref_map, &rm, &opt);
945 }
946
947 static int fetch_refs(struct transport *transport, struct ref *ref_map)
948 {
949         int ret = quickfetch(ref_map);
950         if (ret)
951                 ret = transport_fetch_refs(transport, ref_map);
952         if (!ret)
953                 ret |= store_updated_refs(transport->url,
954                                 transport->remote->name,
955                                 ref_map);
956         transport_unlock_pack(transport);
957         return ret;
958 }
959
960 static int prune_refs(struct refspec *refs, int ref_count, struct ref *ref_map,
961                 const char *raw_url)
962 {
963         int url_len, i, result = 0;
964         struct ref *ref, *stale_refs = get_stale_heads(refs, ref_count, ref_map);
965         char *url;
966         int summary_width = transport_summary_width(stale_refs);
967         const char *dangling_msg = dry_run
968                 ? _("   (%s will become dangling)")
969                 : _("   (%s has become dangling)");
970
971         if (raw_url)
972                 url = transport_anonymize_url(raw_url);
973         else
974                 url = xstrdup("foreign");
975
976         url_len = strlen(url);
977         for (i = url_len - 1; url[i] == '/' && 0 <= i; i--)
978                 ;
979
980         url_len = i + 1;
981         if (4 < i && !strncmp(".git", url + i - 3, 4))
982                 url_len = i - 3;
983
984         if (!dry_run) {
985                 struct string_list refnames = STRING_LIST_INIT_NODUP;
986
987                 for (ref = stale_refs; ref; ref = ref->next)
988                         string_list_append(&refnames, ref->name);
989
990                 result = delete_refs("fetch: prune", &refnames, 0);
991                 string_list_clear(&refnames, 0);
992         }
993
994         if (verbosity >= 0) {
995                 for (ref = stale_refs; ref; ref = ref->next) {
996                         struct strbuf sb = STRBUF_INIT;
997                         if (!shown_url) {
998                                 fprintf(stderr, _("From %.*s\n"), url_len, url);
999                                 shown_url = 1;
1000                         }
1001                         format_display(&sb, '-', _("[deleted]"), NULL,
1002                                        _("(none)"), prettify_refname(ref->name),
1003                                        summary_width);
1004                         fprintf(stderr, " %s\n",sb.buf);
1005                         strbuf_release(&sb);
1006                         warn_dangling_symref(stderr, dangling_msg, ref->name);
1007                 }
1008         }
1009
1010         free(url);
1011         free_refs(stale_refs);
1012         return result;
1013 }
1014
1015 static void check_not_current_branch(struct ref *ref_map)
1016 {
1017         struct branch *current_branch = branch_get(NULL);
1018
1019         if (is_bare_repository() || !current_branch)
1020                 return;
1021
1022         for (; ref_map; ref_map = ref_map->next)
1023                 if (ref_map->peer_ref && !strcmp(current_branch->refname,
1024                                         ref_map->peer_ref->name))
1025                         die(_("Refusing to fetch into current branch %s "
1026                             "of non-bare repository"), current_branch->refname);
1027 }
1028
1029 static int truncate_fetch_head(void)
1030 {
1031         const char *filename = git_path_fetch_head();
1032         FILE *fp = fopen_for_writing(filename);
1033
1034         if (!fp)
1035                 return error_errno(_("cannot open %s"), filename);
1036         fclose(fp);
1037         return 0;
1038 }
1039
1040 static void set_option(struct transport *transport, const char *name, const char *value)
1041 {
1042         int r = transport_set_option(transport, name, value);
1043         if (r < 0)
1044                 die(_("Option \"%s\" value \"%s\" is not valid for %s"),
1045                     name, value, transport->url);
1046         if (r > 0)
1047                 warning(_("Option \"%s\" is ignored for %s\n"),
1048                         name, transport->url);
1049 }
1050
1051 static struct transport *prepare_transport(struct remote *remote, int deepen)
1052 {
1053         struct transport *transport;
1054         transport = transport_get(remote, NULL);
1055         transport_set_verbosity(transport, verbosity, progress);
1056         transport->family = family;
1057         if (upload_pack)
1058                 set_option(transport, TRANS_OPT_UPLOADPACK, upload_pack);
1059         if (keep)
1060                 set_option(transport, TRANS_OPT_KEEP, "yes");
1061         if (depth)
1062                 set_option(transport, TRANS_OPT_DEPTH, depth);
1063         if (deepen && deepen_since)
1064                 set_option(transport, TRANS_OPT_DEEPEN_SINCE, deepen_since);
1065         if (deepen && deepen_not.nr)
1066                 set_option(transport, TRANS_OPT_DEEPEN_NOT,
1067                            (const char *)&deepen_not);
1068         if (deepen_relative)
1069                 set_option(transport, TRANS_OPT_DEEPEN_RELATIVE, "yes");
1070         if (update_shallow)
1071                 set_option(transport, TRANS_OPT_UPDATE_SHALLOW, "yes");
1072         if (filter_options.choice) {
1073                 set_option(transport, TRANS_OPT_LIST_OBJECTS_FILTER,
1074                            filter_options.filter_spec);
1075                 set_option(transport, TRANS_OPT_FROM_PROMISOR, "1");
1076         }
1077         return transport;
1078 }
1079
1080 static void backfill_tags(struct transport *transport, struct ref *ref_map)
1081 {
1082         int cannot_reuse;
1083
1084         /*
1085          * Once we have set TRANS_OPT_DEEPEN_SINCE, we can't unset it
1086          * when remote helper is used (setting it to an empty string
1087          * is not unsetting). We could extend the remote helper
1088          * protocol for that, but for now, just force a new connection
1089          * without deepen-since. Similar story for deepen-not.
1090          */
1091         cannot_reuse = transport->cannot_reuse ||
1092                 deepen_since || deepen_not.nr;
1093         if (cannot_reuse) {
1094                 gsecondary = prepare_transport(transport->remote, 0);
1095                 transport = gsecondary;
1096         }
1097
1098         transport_set_option(transport, TRANS_OPT_FOLLOWTAGS, NULL);
1099         transport_set_option(transport, TRANS_OPT_DEPTH, "0");
1100         transport_set_option(transport, TRANS_OPT_DEEPEN_RELATIVE, NULL);
1101         fetch_refs(transport, ref_map);
1102
1103         if (gsecondary) {
1104                 transport_disconnect(gsecondary);
1105                 gsecondary = NULL;
1106         }
1107 }
1108
1109 static int do_fetch(struct transport *transport,
1110                     struct refspec *refs, int ref_count)
1111 {
1112         struct string_list existing_refs = STRING_LIST_INIT_DUP;
1113         struct ref *ref_map;
1114         struct ref *rm;
1115         int autotags = (transport->remote->fetch_tags == 1);
1116         int retcode = 0;
1117
1118         for_each_ref(add_existing, &existing_refs);
1119
1120         if (tags == TAGS_DEFAULT) {
1121                 if (transport->remote->fetch_tags == 2)
1122                         tags = TAGS_SET;
1123                 if (transport->remote->fetch_tags == -1)
1124                         tags = TAGS_UNSET;
1125         }
1126
1127         /* if not appending, truncate FETCH_HEAD */
1128         if (!append && !dry_run) {
1129                 retcode = truncate_fetch_head();
1130                 if (retcode)
1131                         goto cleanup;
1132         }
1133
1134         ref_map = get_ref_map(transport, refs, ref_count, tags, &autotags);
1135         if (!update_head_ok)
1136                 check_not_current_branch(ref_map);
1137
1138         for (rm = ref_map; rm; rm = rm->next) {
1139                 if (rm->peer_ref) {
1140                         struct string_list_item *peer_item =
1141                                 string_list_lookup(&existing_refs,
1142                                                    rm->peer_ref->name);
1143                         if (peer_item) {
1144                                 struct object_id *old_oid = peer_item->util;
1145                                 oidcpy(&rm->peer_ref->old_oid, old_oid);
1146                         }
1147                 }
1148         }
1149
1150         if (tags == TAGS_DEFAULT && autotags)
1151                 transport_set_option(transport, TRANS_OPT_FOLLOWTAGS, "1");
1152         if (prune) {
1153                 /*
1154                  * We only prune based on refspecs specified
1155                  * explicitly (via command line or configuration); we
1156                  * don't care whether --tags was specified.
1157                  */
1158                 if (ref_count) {
1159                         prune_refs(refs, ref_count, ref_map, transport->url);
1160                 } else {
1161                         prune_refs(transport->remote->fetch,
1162                                    transport->remote->fetch_refspec_nr,
1163                                    ref_map,
1164                                    transport->url);
1165                 }
1166         }
1167         if (fetch_refs(transport, ref_map)) {
1168                 free_refs(ref_map);
1169                 retcode = 1;
1170                 goto cleanup;
1171         }
1172         free_refs(ref_map);
1173
1174         /* if neither --no-tags nor --tags was specified, do automated tag
1175          * following ... */
1176         if (tags == TAGS_DEFAULT && autotags) {
1177                 struct ref **tail = &ref_map;
1178                 ref_map = NULL;
1179                 find_non_local_tags(transport, &ref_map, &tail);
1180                 if (ref_map)
1181                         backfill_tags(transport, ref_map);
1182                 free_refs(ref_map);
1183         }
1184
1185  cleanup:
1186         string_list_clear(&existing_refs, 1);
1187         return retcode;
1188 }
1189
1190 static int get_one_remote_for_fetch(struct remote *remote, void *priv)
1191 {
1192         struct string_list *list = priv;
1193         if (!remote->skip_default_update)
1194                 string_list_append(list, remote->name);
1195         return 0;
1196 }
1197
1198 struct remote_group_data {
1199         const char *name;
1200         struct string_list *list;
1201 };
1202
1203 static int get_remote_group(const char *key, const char *value, void *priv)
1204 {
1205         struct remote_group_data *g = priv;
1206
1207         if (skip_prefix(key, "remotes.", &key) && !strcmp(key, g->name)) {
1208                 /* split list by white space */
1209                 while (*value) {
1210                         size_t wordlen = strcspn(value, " \t\n");
1211
1212                         if (wordlen >= 1)
1213                                 string_list_append_nodup(g->list,
1214                                                    xstrndup(value, wordlen));
1215                         value += wordlen + (value[wordlen] != '\0');
1216                 }
1217         }
1218
1219         return 0;
1220 }
1221
1222 static int add_remote_or_group(const char *name, struct string_list *list)
1223 {
1224         int prev_nr = list->nr;
1225         struct remote_group_data g;
1226         g.name = name; g.list = list;
1227
1228         git_config(get_remote_group, &g);
1229         if (list->nr == prev_nr) {
1230                 struct remote *remote = remote_get(name);
1231                 if (!remote_is_configured(remote, 0))
1232                         return 0;
1233                 string_list_append(list, remote->name);
1234         }
1235         return 1;
1236 }
1237
1238 static void add_options_to_argv(struct argv_array *argv)
1239 {
1240         if (dry_run)
1241                 argv_array_push(argv, "--dry-run");
1242         if (prune != -1)
1243                 argv_array_push(argv, prune ? "--prune" : "--no-prune");
1244         if (prune_tags != -1)
1245                 argv_array_push(argv, prune_tags ? "--prune-tags" : "--no-prune-tags");
1246         if (update_head_ok)
1247                 argv_array_push(argv, "--update-head-ok");
1248         if (force)
1249                 argv_array_push(argv, "--force");
1250         if (keep)
1251                 argv_array_push(argv, "--keep");
1252         if (recurse_submodules == RECURSE_SUBMODULES_ON)
1253                 argv_array_push(argv, "--recurse-submodules");
1254         else if (recurse_submodules == RECURSE_SUBMODULES_ON_DEMAND)
1255                 argv_array_push(argv, "--recurse-submodules=on-demand");
1256         if (tags == TAGS_SET)
1257                 argv_array_push(argv, "--tags");
1258         else if (tags == TAGS_UNSET)
1259                 argv_array_push(argv, "--no-tags");
1260         if (verbosity >= 2)
1261                 argv_array_push(argv, "-v");
1262         if (verbosity >= 1)
1263                 argv_array_push(argv, "-v");
1264         else if (verbosity < 0)
1265                 argv_array_push(argv, "-q");
1266
1267 }
1268
1269 static int fetch_multiple(struct string_list *list)
1270 {
1271         int i, result = 0;
1272         struct argv_array argv = ARGV_ARRAY_INIT;
1273
1274         if (!append && !dry_run) {
1275                 int errcode = truncate_fetch_head();
1276                 if (errcode)
1277                         return errcode;
1278         }
1279
1280         argv_array_pushl(&argv, "fetch", "--append", NULL);
1281         add_options_to_argv(&argv);
1282
1283         for (i = 0; i < list->nr; i++) {
1284                 const char *name = list->items[i].string;
1285                 argv_array_push(&argv, name);
1286                 if (verbosity >= 0)
1287                         printf(_("Fetching %s\n"), name);
1288                 if (run_command_v_opt(argv.argv, RUN_GIT_CMD)) {
1289                         error(_("Could not fetch %s"), name);
1290                         result = 1;
1291                 }
1292                 argv_array_pop(&argv);
1293         }
1294
1295         argv_array_clear(&argv);
1296         return result;
1297 }
1298
1299 /*
1300  * Fetching from the promisor remote should use the given filter-spec
1301  * or inherit the default filter-spec from the config.
1302  */
1303 static inline void fetch_one_setup_partial(struct remote *remote)
1304 {
1305         /*
1306          * Explicit --no-filter argument overrides everything, regardless
1307          * of any prior partial clones and fetches.
1308          */
1309         if (filter_options.no_filter)
1310                 return;
1311
1312         /*
1313          * If no prior partial clone/fetch and the current fetch DID NOT
1314          * request a partial-fetch, do a normal fetch.
1315          */
1316         if (!repository_format_partial_clone && !filter_options.choice)
1317                 return;
1318
1319         /*
1320          * If this is the FIRST partial-fetch request, we enable partial
1321          * on this repo and remember the given filter-spec as the default
1322          * for subsequent fetches to this remote.
1323          */
1324         if (!repository_format_partial_clone && filter_options.choice) {
1325                 partial_clone_register(remote->name, &filter_options);
1326                 return;
1327         }
1328
1329         /*
1330          * We are currently limited to only ONE promisor remote and only
1331          * allow partial-fetches from the promisor remote.
1332          */
1333         if (strcmp(remote->name, repository_format_partial_clone)) {
1334                 if (filter_options.choice)
1335                         die(_("--filter can only be used with the remote configured in core.partialClone"));
1336                 return;
1337         }
1338
1339         /*
1340          * Do a partial-fetch from the promisor remote using either the
1341          * explicitly given filter-spec or inherit the filter-spec from
1342          * the config.
1343          */
1344         if (!filter_options.choice)
1345                 partial_clone_get_default_filter_spec(&filter_options);
1346         return;
1347 }
1348
1349 static int fetch_one(struct remote *remote, int argc, const char **argv, int prune_tags_ok)
1350 {
1351         static const char **refs = NULL;
1352         struct refspec *refspec;
1353         int ref_nr = 0;
1354         int j = 0;
1355         int exit_code;
1356         int maybe_prune_tags;
1357         int remote_via_config = remote_is_configured(remote, 0);
1358
1359         if (!remote)
1360                 die(_("No remote repository specified.  Please, specify either a URL or a\n"
1361                     "remote name from which new revisions should be fetched."));
1362
1363         gtransport = prepare_transport(remote, 1);
1364
1365         if (prune < 0) {
1366                 /* no command line request */
1367                 if (0 <= remote->prune)
1368                         prune = remote->prune;
1369                 else if (0 <= fetch_prune_config)
1370                         prune = fetch_prune_config;
1371                 else
1372                         prune = PRUNE_BY_DEFAULT;
1373         }
1374
1375         if (prune_tags < 0) {
1376                 /* no command line request */
1377                 if (0 <= remote->prune_tags)
1378                         prune_tags = remote->prune_tags;
1379                 else if (0 <= fetch_prune_tags_config)
1380                         prune_tags = fetch_prune_tags_config;
1381                 else
1382                         prune_tags = PRUNE_TAGS_BY_DEFAULT;
1383         }
1384
1385         maybe_prune_tags = prune_tags_ok && prune_tags;
1386         if (maybe_prune_tags && remote_via_config)
1387                 add_prune_tags_to_fetch_refspec(remote);
1388
1389         if (argc > 0 || (maybe_prune_tags && !remote_via_config)) {
1390                 size_t nr_alloc = st_add3(argc, maybe_prune_tags, 1);
1391                 refs = xcalloc(nr_alloc, sizeof(const char *));
1392                 if (maybe_prune_tags) {
1393                         refs[j++] = xstrdup("refs/tags/*:refs/tags/*");
1394                         ref_nr++;
1395                 }
1396         }
1397
1398         if (argc > 0) {
1399                 int i;
1400                 for (i = 0; i < argc; i++) {
1401                         if (!strcmp(argv[i], "tag")) {
1402                                 i++;
1403                                 if (i >= argc)
1404                                         die(_("You need to specify a tag name."));
1405                                 refs[j++] = xstrfmt("refs/tags/%s:refs/tags/%s",
1406                                                     argv[i], argv[i]);
1407                         } else
1408                                 refs[j++] = argv[i];
1409                         ref_nr++;
1410                 }
1411         }
1412
1413         sigchain_push_common(unlock_pack_on_signal);
1414         atexit(unlock_pack);
1415         refspec = parse_fetch_refspec(ref_nr, refs);
1416         exit_code = do_fetch(gtransport, refspec, ref_nr);
1417         free_refspec(ref_nr, refspec);
1418         transport_disconnect(gtransport);
1419         gtransport = NULL;
1420         return exit_code;
1421 }
1422
1423 int cmd_fetch(int argc, const char **argv, const char *prefix)
1424 {
1425         int i;
1426         struct string_list list = STRING_LIST_INIT_DUP;
1427         struct remote *remote = NULL;
1428         int result = 0;
1429         int prune_tags_ok = 1;
1430         struct argv_array argv_gc_auto = ARGV_ARRAY_INIT;
1431
1432         packet_trace_identity("fetch");
1433
1434         fetch_if_missing = 0;
1435
1436         /* Record the command line for the reflog */
1437         strbuf_addstr(&default_rla, "fetch");
1438         for (i = 1; i < argc; i++)
1439                 strbuf_addf(&default_rla, " %s", argv[i]);
1440
1441         config_from_gitmodules(gitmodules_fetch_config, NULL);
1442         git_config(git_fetch_config, NULL);
1443
1444         argc = parse_options(argc, argv, prefix,
1445                              builtin_fetch_options, builtin_fetch_usage, 0);
1446
1447         if (deepen_relative) {
1448                 if (deepen_relative < 0)
1449                         die(_("Negative depth in --deepen is not supported"));
1450                 if (depth)
1451                         die(_("--deepen and --depth are mutually exclusive"));
1452                 depth = xstrfmt("%d", deepen_relative);
1453         }
1454         if (unshallow) {
1455                 if (depth)
1456                         die(_("--depth and --unshallow cannot be used together"));
1457                 else if (!is_repository_shallow())
1458                         die(_("--unshallow on a complete repository does not make sense"));
1459                 else
1460                         depth = xstrfmt("%d", INFINITE_DEPTH);
1461         }
1462
1463         /* no need to be strict, transport_set_option() will validate it again */
1464         if (depth && atoi(depth) < 1)
1465                 die(_("depth %s is not a positive number"), depth);
1466         if (depth || deepen_since || deepen_not.nr)
1467                 deepen = 1;
1468
1469         if (filter_options.choice && !repository_format_partial_clone)
1470                 die("--filter can only be used when extensions.partialClone is set");
1471
1472         if (all) {
1473                 if (argc == 1)
1474                         die(_("fetch --all does not take a repository argument"));
1475                 else if (argc > 1)
1476                         die(_("fetch --all does not make sense with refspecs"));
1477                 (void) for_each_remote(get_one_remote_for_fetch, &list);
1478         } else if (argc == 0) {
1479                 /* No arguments -- use default remote */
1480                 remote = remote_get(NULL);
1481         } else if (multiple) {
1482                 /* All arguments are assumed to be remotes or groups */
1483                 for (i = 0; i < argc; i++)
1484                         if (!add_remote_or_group(argv[i], &list))
1485                                 die(_("No such remote or remote group: %s"), argv[i]);
1486         } else {
1487                 /* Single remote or group */
1488                 (void) add_remote_or_group(argv[0], &list);
1489                 if (list.nr > 1) {
1490                         /* More than one remote */
1491                         if (argc > 1)
1492                                 die(_("Fetching a group and specifying refspecs does not make sense"));
1493                 } else {
1494                         /* Zero or one remotes */
1495                         remote = remote_get(argv[0]);
1496                         prune_tags_ok = (argc == 1);
1497                         argc--;
1498                         argv++;
1499                 }
1500         }
1501
1502         if (remote) {
1503                 if (filter_options.choice || repository_format_partial_clone)
1504                         fetch_one_setup_partial(remote);
1505                 result = fetch_one(remote, argc, argv, prune_tags_ok);
1506         } else {
1507                 if (filter_options.choice)
1508                         die(_("--filter can only be used with the remote configured in core.partialClone"));
1509                 /* TODO should this also die if we have a previous partial-clone? */
1510                 result = fetch_multiple(&list);
1511         }
1512
1513         if (!result && (recurse_submodules != RECURSE_SUBMODULES_OFF)) {
1514                 struct argv_array options = ARGV_ARRAY_INIT;
1515
1516                 add_options_to_argv(&options);
1517                 result = fetch_populated_submodules(the_repository,
1518                                                     &options,
1519                                                     submodule_prefix,
1520                                                     recurse_submodules,
1521                                                     recurse_submodules_default,
1522                                                     verbosity < 0,
1523                                                     max_children);
1524                 argv_array_clear(&options);
1525         }
1526
1527         string_list_clear(&list, 0);
1528
1529         close_all_packs();
1530
1531         argv_array_pushl(&argv_gc_auto, "gc", "--auto", NULL);
1532         if (verbosity < 0)
1533                 argv_array_push(&argv_gc_auto, "--quiet");
1534         run_command_v_opt(argv_gc_auto.argv, RUN_GIT_CMD);
1535         argv_array_clear(&argv_gc_auto);
1536
1537         return result;
1538 }