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