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