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