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