]> Pileus Git - ~andy/git/blob - builtin/fetch.c
Merge branch 'jk/clone-progress-to-stderr' into maint
[~andy/git] / builtin / fetch.c
1 /*
2  * "git fetch"
3  */
4 #include "cache.h"
5 #include "refs.h"
6 #include "commit.h"
7 #include "builtin.h"
8 #include "string-list.h"
9 #include "remote.h"
10 #include "transport.h"
11 #include "run-command.h"
12 #include "parse-options.h"
13 #include "sigchain.h"
14 #include "transport.h"
15 #include "submodule.h"
16 #include "connected.h"
17 #include "argv-array.h"
18
19 static const char * const builtin_fetch_usage[] = {
20         N_("git fetch [<options>] [<repository> [<refspec>...]]"),
21         N_("git fetch [<options>] <group>"),
22         N_("git fetch --multiple [<options>] [(<repository> | <group>)...]"),
23         N_("git fetch --all [<options>]"),
24         NULL
25 };
26
27 enum {
28         TAGS_UNSET = 0,
29         TAGS_DEFAULT = 1,
30         TAGS_SET = 2
31 };
32
33 static int all, append, dry_run, force, keep, multiple, prune, update_head_ok, verbosity;
34 static int progress = -1, recurse_submodules = RECURSE_SUBMODULES_DEFAULT;
35 static int tags = TAGS_DEFAULT, unshallow;
36 static const char *depth;
37 static const char *upload_pack;
38 static struct strbuf default_rla = STRBUF_INIT;
39 static struct transport *gtransport;
40 static struct transport *gsecondary;
41 static const char *submodule_prefix = "";
42 static const char *recurse_submodules_default;
43
44 static int option_parse_recurse_submodules(const struct option *opt,
45                                    const char *arg, int unset)
46 {
47         if (unset) {
48                 recurse_submodules = RECURSE_SUBMODULES_OFF;
49         } else {
50                 if (arg)
51                         recurse_submodules = parse_fetch_recurse_submodules_arg(opt->long_name, arg);
52                 else
53                         recurse_submodules = RECURSE_SUBMODULES_ON;
54         }
55         return 0;
56 }
57
58 static struct option builtin_fetch_options[] = {
59         OPT__VERBOSITY(&verbosity),
60         OPT_BOOLEAN(0, "all", &all,
61                     N_("fetch from all remotes")),
62         OPT_BOOLEAN('a', "append", &append,
63                     N_("append to .git/FETCH_HEAD instead of overwriting")),
64         OPT_STRING(0, "upload-pack", &upload_pack, N_("path"),
65                    N_("path to upload pack on remote end")),
66         OPT__FORCE(&force, N_("force overwrite of local branch")),
67         OPT_BOOLEAN('m', "multiple", &multiple,
68                     N_("fetch from multiple remotes")),
69         OPT_SET_INT('t', "tags", &tags,
70                     N_("fetch all tags and associated objects"), TAGS_SET),
71         OPT_SET_INT('n', NULL, &tags,
72                     N_("do not fetch all tags (--no-tags)"), TAGS_UNSET),
73         OPT_BOOLEAN('p', "prune", &prune,
74                     N_("prune remote-tracking branches no longer on remote")),
75         { OPTION_CALLBACK, 0, "recurse-submodules", NULL, N_("on-demand"),
76                     N_("control recursive fetching of submodules"),
77                     PARSE_OPT_OPTARG, option_parse_recurse_submodules },
78         OPT_BOOLEAN(0, "dry-run", &dry_run,
79                     N_("dry run")),
80         OPT_BOOLEAN('k', "keep", &keep, N_("keep downloaded pack")),
81         OPT_BOOLEAN('u', "update-head-ok", &update_head_ok,
82                     N_("allow updating of HEAD ref")),
83         OPT_BOOL(0, "progress", &progress, N_("force progress reporting")),
84         OPT_STRING(0, "depth", &depth, N_("depth"),
85                    N_("deepen history of shallow clone")),
86         { OPTION_SET_INT, 0, "unshallow", &unshallow, NULL,
87                    N_("convert to a complete repository"),
88                    PARSE_OPT_NONEG | PARSE_OPT_NOARG, NULL, 1 },
89         { OPTION_STRING, 0, "submodule-prefix", &submodule_prefix, N_("dir"),
90                    N_("prepend this to submodule path output"), PARSE_OPT_HIDDEN },
91         { OPTION_STRING, 0, "recurse-submodules-default",
92                    &recurse_submodules_default, NULL,
93                    N_("default mode for recursion"), PARSE_OPT_HIDDEN },
94         OPT_END()
95 };
96
97 static void unlock_pack(void)
98 {
99         if (gtransport)
100                 transport_unlock_pack(gtransport);
101         if (gsecondary)
102                 transport_unlock_pack(gsecondary);
103 }
104
105 static void unlock_pack_on_signal(int signo)
106 {
107         unlock_pack();
108         sigchain_pop(signo);
109         raise(signo);
110 }
111
112 static void add_merge_config(struct ref **head,
113                            const struct ref *remote_refs,
114                            struct branch *branch,
115                            struct ref ***tail)
116 {
117         int i;
118
119         for (i = 0; i < branch->merge_nr; i++) {
120                 struct ref *rm, **old_tail = *tail;
121                 struct refspec refspec;
122
123                 for (rm = *head; rm; rm = rm->next) {
124                         if (branch_merge_matches(branch, i, rm->name)) {
125                                 rm->fetch_head_status = FETCH_HEAD_MERGE;
126                                 break;
127                         }
128                 }
129                 if (rm)
130                         continue;
131
132                 /*
133                  * Not fetched to a remote-tracking branch?  We need to fetch
134                  * it anyway to allow this branch's "branch.$name.merge"
135                  * to be honored by 'git pull', but we do not have to
136                  * fail if branch.$name.merge is misconfigured to point
137                  * at a nonexisting branch.  If we were indeed called by
138                  * 'git pull', it will notice the misconfiguration because
139                  * there is no entry in the resulting FETCH_HEAD marked
140                  * for merging.
141                  */
142                 memset(&refspec, 0, sizeof(refspec));
143                 refspec.src = branch->merge[i]->src;
144                 get_fetch_map(remote_refs, &refspec, tail, 1);
145                 for (rm = *old_tail; rm; rm = rm->next)
146                         rm->fetch_head_status = FETCH_HEAD_MERGE;
147         }
148 }
149
150 static void find_non_local_tags(struct transport *transport,
151                         struct ref **head,
152                         struct ref ***tail);
153
154 static struct ref *get_ref_map(struct transport *transport,
155                                struct refspec *refs, int ref_count, int tags,
156                                int *autotags)
157 {
158         int i;
159         struct ref *rm;
160         struct ref *ref_map = NULL;
161         struct ref **tail = &ref_map;
162
163         const struct ref *remote_refs = transport_get_remote_refs(transport);
164
165         if (ref_count || tags == TAGS_SET) {
166                 struct ref **old_tail;
167
168                 for (i = 0; i < ref_count; i++) {
169                         get_fetch_map(remote_refs, &refs[i], &tail, 0);
170                         if (refs[i].dst && refs[i].dst[0])
171                                 *autotags = 1;
172                 }
173                 /* Merge everything on the command line, but not --tags */
174                 for (rm = ref_map; rm; rm = rm->next)
175                         rm->fetch_head_status = FETCH_HEAD_MERGE;
176                 if (tags == TAGS_SET)
177                         get_fetch_map(remote_refs, tag_refspec, &tail, 0);
178
179                 /*
180                  * For any refs that we happen to be fetching via command-line
181                  * arguments, take the opportunity to update their configured
182                  * counterparts. However, we do not want to mention these
183                  * entries in FETCH_HEAD at all, as they would simply be
184                  * duplicates of existing entries.
185                  */
186                 old_tail = tail;
187                 for (i = 0; i < transport->remote->fetch_refspec_nr; i++)
188                         get_fetch_map(ref_map, &transport->remote->fetch[i],
189                                       &tail, 1);
190                 for (rm = *old_tail; rm; rm = rm->next)
191                         rm->fetch_head_status = FETCH_HEAD_IGNORE;
192         } else {
193                 /* Use the defaults */
194                 struct remote *remote = transport->remote;
195                 struct branch *branch = branch_get(NULL);
196                 int has_merge = branch_has_merge_config(branch);
197                 if (remote &&
198                     (remote->fetch_refspec_nr ||
199                      /* Note: has_merge implies non-NULL branch->remote_name */
200                      (has_merge && !strcmp(branch->remote_name, remote->name)))) {
201                         for (i = 0; i < remote->fetch_refspec_nr; i++) {
202                                 get_fetch_map(remote_refs, &remote->fetch[i], &tail, 0);
203                                 if (remote->fetch[i].dst &&
204                                     remote->fetch[i].dst[0])
205                                         *autotags = 1;
206                                 if (!i && !has_merge && ref_map &&
207                                     !remote->fetch[0].pattern)
208                                         ref_map->fetch_head_status = FETCH_HEAD_MERGE;
209                         }
210                         /*
211                          * if the remote we're fetching from is the same
212                          * as given in branch.<name>.remote, we add the
213                          * ref given in branch.<name>.merge, too.
214                          *
215                          * Note: has_merge implies non-NULL branch->remote_name
216                          */
217                         if (has_merge &&
218                             !strcmp(branch->remote_name, remote->name))
219                                 add_merge_config(&ref_map, remote_refs, branch, &tail);
220                 } else {
221                         ref_map = get_remote_ref(remote_refs, "HEAD");
222                         if (!ref_map)
223                                 die(_("Couldn't find remote ref HEAD"));
224                         ref_map->fetch_head_status = FETCH_HEAD_MERGE;
225                         tail = &ref_map->next;
226                 }
227         }
228         if (tags == TAGS_DEFAULT && *autotags)
229                 find_non_local_tags(transport, &ref_map, &tail);
230         ref_remove_duplicates(ref_map);
231
232         return ref_map;
233 }
234
235 #define STORE_REF_ERROR_OTHER 1
236 #define STORE_REF_ERROR_DF_CONFLICT 2
237
238 static int s_update_ref(const char *action,
239                         struct ref *ref,
240                         int check_old)
241 {
242         char msg[1024];
243         char *rla = getenv("GIT_REFLOG_ACTION");
244         static struct ref_lock *lock;
245
246         if (dry_run)
247                 return 0;
248         if (!rla)
249                 rla = default_rla.buf;
250         snprintf(msg, sizeof(msg), "%s: %s", rla, action);
251         lock = lock_any_ref_for_update(ref->name,
252                                        check_old ? ref->old_sha1 : NULL, 0);
253         if (!lock)
254                 return errno == ENOTDIR ? STORE_REF_ERROR_DF_CONFLICT :
255                                           STORE_REF_ERROR_OTHER;
256         if (write_ref_sha1(lock, ref->new_sha1, msg) < 0)
257                 return errno == ENOTDIR ? STORE_REF_ERROR_DF_CONFLICT :
258                                           STORE_REF_ERROR_OTHER;
259         return 0;
260 }
261
262 #define REFCOL_WIDTH  10
263
264 static int update_local_ref(struct ref *ref,
265                             const char *remote,
266                             const struct ref *remote_ref,
267                             struct strbuf *display)
268 {
269         struct commit *current = NULL, *updated;
270         enum object_type type;
271         struct branch *current_branch = branch_get(NULL);
272         const char *pretty_ref = prettify_refname(ref->name);
273
274         type = sha1_object_info(ref->new_sha1, NULL);
275         if (type < 0)
276                 die(_("object %s not found"), sha1_to_hex(ref->new_sha1));
277
278         if (!hashcmp(ref->old_sha1, ref->new_sha1)) {
279                 if (verbosity > 0)
280                         strbuf_addf(display, "= %-*s %-*s -> %s",
281                                     TRANSPORT_SUMMARY(_("[up to date]")),
282                                     REFCOL_WIDTH, remote, pretty_ref);
283                 return 0;
284         }
285
286         if (current_branch &&
287             !strcmp(ref->name, current_branch->name) &&
288             !(update_head_ok || is_bare_repository()) &&
289             !is_null_sha1(ref->old_sha1)) {
290                 /*
291                  * If this is the head, and it's not okay to update
292                  * the head, and the old value of the head isn't empty...
293                  */
294                 strbuf_addf(display,
295                             _("! %-*s %-*s -> %s  (can't fetch in current branch)"),
296                             TRANSPORT_SUMMARY(_("[rejected]")),
297                             REFCOL_WIDTH, remote, pretty_ref);
298                 return 1;
299         }
300
301         if (!is_null_sha1(ref->old_sha1) &&
302             !prefixcmp(ref->name, "refs/tags/")) {
303                 int r;
304                 r = s_update_ref("updating tag", ref, 0);
305                 strbuf_addf(display, "%c %-*s %-*s -> %s%s",
306                             r ? '!' : '-',
307                             TRANSPORT_SUMMARY(_("[tag update]")),
308                             REFCOL_WIDTH, remote, pretty_ref,
309                             r ? _("  (unable to update local ref)") : "");
310                 return r;
311         }
312
313         current = lookup_commit_reference_gently(ref->old_sha1, 1);
314         updated = lookup_commit_reference_gently(ref->new_sha1, 1);
315         if (!current || !updated) {
316                 const char *msg;
317                 const char *what;
318                 int r;
319                 /*
320                  * Nicely describe the new ref we're fetching.
321                  * Base this on the remote's ref name, as it's
322                  * more likely to follow a standard layout.
323                  */
324                 const char *name = remote_ref ? remote_ref->name : "";
325                 if (!prefixcmp(name, "refs/tags/")) {
326                         msg = "storing tag";
327                         what = _("[new tag]");
328                 } else if (!prefixcmp(name, "refs/heads/")) {
329                         msg = "storing head";
330                         what = _("[new branch]");
331                 } else {
332                         msg = "storing ref";
333                         what = _("[new ref]");
334                 }
335
336                 if ((recurse_submodules != RECURSE_SUBMODULES_OFF) &&
337                     (recurse_submodules != RECURSE_SUBMODULES_ON))
338                         check_for_new_submodule_commits(ref->new_sha1);
339                 r = s_update_ref(msg, ref, 0);
340                 strbuf_addf(display, "%c %-*s %-*s -> %s%s",
341                             r ? '!' : '*',
342                             TRANSPORT_SUMMARY(what),
343                             REFCOL_WIDTH, remote, pretty_ref,
344                             r ? _("  (unable to update local ref)") : "");
345                 return r;
346         }
347
348         if (in_merge_bases(current, updated)) {
349                 char quickref[83];
350                 int r;
351                 strcpy(quickref, find_unique_abbrev(current->object.sha1, DEFAULT_ABBREV));
352                 strcat(quickref, "..");
353                 strcat(quickref, find_unique_abbrev(ref->new_sha1, DEFAULT_ABBREV));
354                 if ((recurse_submodules != RECURSE_SUBMODULES_OFF) &&
355                     (recurse_submodules != RECURSE_SUBMODULES_ON))
356                         check_for_new_submodule_commits(ref->new_sha1);
357                 r = s_update_ref("fast-forward", ref, 1);
358                 strbuf_addf(display, "%c %-*s %-*s -> %s%s",
359                             r ? '!' : ' ',
360                             TRANSPORT_SUMMARY_WIDTH, quickref,
361                             REFCOL_WIDTH, remote, pretty_ref,
362                             r ? _("  (unable to update local ref)") : "");
363                 return r;
364         } else if (force || ref->force) {
365                 char quickref[84];
366                 int r;
367                 strcpy(quickref, find_unique_abbrev(current->object.sha1, DEFAULT_ABBREV));
368                 strcat(quickref, "...");
369                 strcat(quickref, find_unique_abbrev(ref->new_sha1, DEFAULT_ABBREV));
370                 if ((recurse_submodules != RECURSE_SUBMODULES_OFF) &&
371                     (recurse_submodules != RECURSE_SUBMODULES_ON))
372                         check_for_new_submodule_commits(ref->new_sha1);
373                 r = s_update_ref("forced-update", ref, 1);
374                 strbuf_addf(display, "%c %-*s %-*s -> %s  (%s)",
375                             r ? '!' : '+',
376                             TRANSPORT_SUMMARY_WIDTH, quickref,
377                             REFCOL_WIDTH, remote, pretty_ref,
378                             r ? _("unable to update local ref") : _("forced update"));
379                 return r;
380         } else {
381                 strbuf_addf(display, "! %-*s %-*s -> %s  %s",
382                             TRANSPORT_SUMMARY(_("[rejected]")),
383                             REFCOL_WIDTH, remote, pretty_ref,
384                             _("(non-fast-forward)"));
385                 return 1;
386         }
387 }
388
389 static int iterate_ref_map(void *cb_data, unsigned char sha1[20])
390 {
391         struct ref **rm = cb_data;
392         struct ref *ref = *rm;
393
394         if (!ref)
395                 return -1; /* end of the list */
396         *rm = ref->next;
397         hashcpy(sha1, ref->old_sha1);
398         return 0;
399 }
400
401 static int store_updated_refs(const char *raw_url, const char *remote_name,
402                 struct ref *ref_map)
403 {
404         FILE *fp;
405         struct commit *commit;
406         int url_len, i, shown_url = 0, rc = 0;
407         struct strbuf note = STRBUF_INIT;
408         const char *what, *kind;
409         struct ref *rm;
410         char *url, *filename = dry_run ? "/dev/null" : git_path("FETCH_HEAD");
411         int want_status;
412
413         fp = fopen(filename, "a");
414         if (!fp)
415                 return error(_("cannot open %s: %s\n"), filename, strerror(errno));
416
417         if (raw_url)
418                 url = transport_anonymize_url(raw_url);
419         else
420                 url = xstrdup("foreign");
421
422         rm = ref_map;
423         if (check_everything_connected(iterate_ref_map, 0, &rm)) {
424                 rc = error(_("%s did not send all necessary objects\n"), url);
425                 goto abort;
426         }
427
428         /*
429          * We do a pass for each fetch_head_status type in their enum order, so
430          * merged entries are written before not-for-merge. That lets readers
431          * use FETCH_HEAD as a refname to refer to the ref to be merged.
432          */
433         for (want_status = FETCH_HEAD_MERGE;
434              want_status <= FETCH_HEAD_IGNORE;
435              want_status++) {
436                 for (rm = ref_map; rm; rm = rm->next) {
437                         struct ref *ref = NULL;
438                         const char *merge_status_marker = "";
439
440                         commit = lookup_commit_reference_gently(rm->old_sha1, 1);
441                         if (!commit)
442                                 rm->fetch_head_status = FETCH_HEAD_NOT_FOR_MERGE;
443
444                         if (rm->fetch_head_status != want_status)
445                                 continue;
446
447                         if (rm->peer_ref) {
448                                 ref = xcalloc(1, sizeof(*ref) + strlen(rm->peer_ref->name) + 1);
449                                 strcpy(ref->name, rm->peer_ref->name);
450                                 hashcpy(ref->old_sha1, rm->peer_ref->old_sha1);
451                                 hashcpy(ref->new_sha1, rm->old_sha1);
452                                 ref->force = rm->peer_ref->force;
453                         }
454
455
456                         if (!strcmp(rm->name, "HEAD")) {
457                                 kind = "";
458                                 what = "";
459                         }
460                         else if (!prefixcmp(rm->name, "refs/heads/")) {
461                                 kind = "branch";
462                                 what = rm->name + 11;
463                         }
464                         else if (!prefixcmp(rm->name, "refs/tags/")) {
465                                 kind = "tag";
466                                 what = rm->name + 10;
467                         }
468                         else if (!prefixcmp(rm->name, "refs/remotes/")) {
469                                 kind = "remote-tracking branch";
470                                 what = rm->name + 13;
471                         }
472                         else {
473                                 kind = "";
474                                 what = rm->name;
475                         }
476
477                         url_len = strlen(url);
478                         for (i = url_len - 1; url[i] == '/' && 0 <= i; i--)
479                                 ;
480                         url_len = i + 1;
481                         if (4 < i && !strncmp(".git", url + i - 3, 4))
482                                 url_len = i - 3;
483
484                         strbuf_reset(&note);
485                         if (*what) {
486                                 if (*kind)
487                                         strbuf_addf(&note, "%s ", kind);
488                                 strbuf_addf(&note, "'%s' of ", what);
489                         }
490                         switch (rm->fetch_head_status) {
491                         case FETCH_HEAD_NOT_FOR_MERGE:
492                                 merge_status_marker = "not-for-merge";
493                                 /* fall-through */
494                         case FETCH_HEAD_MERGE:
495                                 fprintf(fp, "%s\t%s\t%s",
496                                         sha1_to_hex(rm->old_sha1),
497                                         merge_status_marker,
498                                         note.buf);
499                                 for (i = 0; i < url_len; ++i)
500                                         if ('\n' == url[i])
501                                                 fputs("\\n", fp);
502                                         else
503                                                 fputc(url[i], fp);
504                                 fputc('\n', fp);
505                                 break;
506                         default:
507                                 /* do not write anything to FETCH_HEAD */
508                                 break;
509                         }
510
511                         strbuf_reset(&note);
512                         if (ref) {
513                                 rc |= update_local_ref(ref, what, rm, &note);
514                                 free(ref);
515                         } else
516                                 strbuf_addf(&note, "* %-*s %-*s -> FETCH_HEAD",
517                                             TRANSPORT_SUMMARY_WIDTH,
518                                             *kind ? kind : "branch",
519                                             REFCOL_WIDTH,
520                                             *what ? what : "HEAD");
521                         if (note.len) {
522                                 if (verbosity >= 0 && !shown_url) {
523                                         fprintf(stderr, _("From %.*s\n"),
524                                                         url_len, url);
525                                         shown_url = 1;
526                                 }
527                                 if (verbosity >= 0)
528                                         fprintf(stderr, " %s\n", note.buf);
529                         }
530                 }
531         }
532
533         if (rc & STORE_REF_ERROR_DF_CONFLICT)
534                 error(_("some local refs could not be updated; try running\n"
535                       " 'git remote prune %s' to remove any old, conflicting "
536                       "branches"), remote_name);
537
538  abort:
539         strbuf_release(&note);
540         free(url);
541         fclose(fp);
542         return rc;
543 }
544
545 /*
546  * We would want to bypass the object transfer altogether if
547  * everything we are going to fetch already exists and is connected
548  * locally.
549  */
550 static int quickfetch(struct ref *ref_map)
551 {
552         struct ref *rm = ref_map;
553
554         /*
555          * If we are deepening a shallow clone we already have these
556          * objects reachable.  Running rev-list here will return with
557          * a good (0) exit status and we'll bypass the fetch that we
558          * really need to perform.  Claiming failure now will ensure
559          * we perform the network exchange to deepen our history.
560          */
561         if (depth)
562                 return -1;
563         return check_everything_connected(iterate_ref_map, 1, &rm);
564 }
565
566 static int fetch_refs(struct transport *transport, struct ref *ref_map)
567 {
568         int ret = quickfetch(ref_map);
569         if (ret)
570                 ret = transport_fetch_refs(transport, ref_map);
571         if (!ret)
572                 ret |= store_updated_refs(transport->url,
573                                 transport->remote->name,
574                                 ref_map);
575         transport_unlock_pack(transport);
576         return ret;
577 }
578
579 static int prune_refs(struct refspec *refs, int ref_count, struct ref *ref_map)
580 {
581         int result = 0;
582         struct ref *ref, *stale_refs = get_stale_heads(refs, ref_count, ref_map);
583         const char *dangling_msg = dry_run
584                 ? _("   (%s will become dangling)")
585                 : _("   (%s has become dangling)");
586
587         for (ref = stale_refs; ref; ref = ref->next) {
588                 if (!dry_run)
589                         result |= delete_ref(ref->name, NULL, 0);
590                 if (verbosity >= 0) {
591                         fprintf(stderr, " x %-*s %-*s -> %s\n",
592                                 TRANSPORT_SUMMARY(_("[deleted]")),
593                                 REFCOL_WIDTH, _("(none)"), prettify_refname(ref->name));
594                         warn_dangling_symref(stderr, dangling_msg, ref->name);
595                 }
596         }
597         free_refs(stale_refs);
598         return result;
599 }
600
601 static int add_existing(const char *refname, const unsigned char *sha1,
602                         int flag, void *cbdata)
603 {
604         struct string_list *list = (struct string_list *)cbdata;
605         struct string_list_item *item = string_list_insert(list, refname);
606         item->util = xmalloc(20);
607         hashcpy(item->util, sha1);
608         return 0;
609 }
610
611 static int will_fetch(struct ref **head, const unsigned char *sha1)
612 {
613         struct ref *rm = *head;
614         while (rm) {
615                 if (!hashcmp(rm->old_sha1, sha1))
616                         return 1;
617                 rm = rm->next;
618         }
619         return 0;
620 }
621
622 static void find_non_local_tags(struct transport *transport,
623                         struct ref **head,
624                         struct ref ***tail)
625 {
626         struct string_list existing_refs = STRING_LIST_INIT_DUP;
627         struct string_list remote_refs = STRING_LIST_INIT_NODUP;
628         const struct ref *ref;
629         struct string_list_item *item = NULL;
630
631         for_each_ref(add_existing, &existing_refs);
632         for (ref = transport_get_remote_refs(transport); ref; ref = ref->next) {
633                 if (prefixcmp(ref->name, "refs/tags/"))
634                         continue;
635
636                 /*
637                  * The peeled ref always follows the matching base
638                  * ref, so if we see a peeled ref that we don't want
639                  * to fetch then we can mark the ref entry in the list
640                  * as one to ignore by setting util to NULL.
641                  */
642                 if (!suffixcmp(ref->name, "^{}")) {
643                         if (item && !has_sha1_file(ref->old_sha1) &&
644                             !will_fetch(head, ref->old_sha1) &&
645                             !has_sha1_file(item->util) &&
646                             !will_fetch(head, item->util))
647                                 item->util = NULL;
648                         item = NULL;
649                         continue;
650                 }
651
652                 /*
653                  * If item is non-NULL here, then we previously saw a
654                  * ref not followed by a peeled reference, so we need
655                  * to check if it is a lightweight tag that we want to
656                  * fetch.
657                  */
658                 if (item && !has_sha1_file(item->util) &&
659                     !will_fetch(head, item->util))
660                         item->util = NULL;
661
662                 item = NULL;
663
664                 /* skip duplicates and refs that we already have */
665                 if (string_list_has_string(&remote_refs, ref->name) ||
666                     string_list_has_string(&existing_refs, ref->name))
667                         continue;
668
669                 item = string_list_insert(&remote_refs, ref->name);
670                 item->util = (void *)ref->old_sha1;
671         }
672         string_list_clear(&existing_refs, 1);
673
674         /*
675          * We may have a final lightweight tag that needs to be
676          * checked to see if it needs fetching.
677          */
678         if (item && !has_sha1_file(item->util) &&
679             !will_fetch(head, item->util))
680                 item->util = NULL;
681
682         /*
683          * For all the tags in the remote_refs string list,
684          * add them to the list of refs to be fetched
685          */
686         for_each_string_list_item(item, &remote_refs) {
687                 /* Unless we have already decided to ignore this item... */
688                 if (item->util)
689                 {
690                         struct ref *rm = alloc_ref(item->string);
691                         rm->peer_ref = alloc_ref(item->string);
692                         hashcpy(rm->old_sha1, item->util);
693                         **tail = rm;
694                         *tail = &rm->next;
695                 }
696         }
697
698         string_list_clear(&remote_refs, 0);
699 }
700
701 static void check_not_current_branch(struct ref *ref_map)
702 {
703         struct branch *current_branch = branch_get(NULL);
704
705         if (is_bare_repository() || !current_branch)
706                 return;
707
708         for (; ref_map; ref_map = ref_map->next)
709                 if (ref_map->peer_ref && !strcmp(current_branch->refname,
710                                         ref_map->peer_ref->name))
711                         die(_("Refusing to fetch into current branch %s "
712                             "of non-bare repository"), current_branch->refname);
713 }
714
715 static int truncate_fetch_head(void)
716 {
717         char *filename = git_path("FETCH_HEAD");
718         FILE *fp = fopen(filename, "w");
719
720         if (!fp)
721                 return error(_("cannot open %s: %s\n"), filename, strerror(errno));
722         fclose(fp);
723         return 0;
724 }
725
726 static void set_option(struct transport *transport, const char *name, const char *value)
727 {
728         int r = transport_set_option(transport, name, value);
729         if (r < 0)
730                 die(_("Option \"%s\" value \"%s\" is not valid for %s"),
731                     name, value, transport->url);
732         if (r > 0)
733                 warning(_("Option \"%s\" is ignored for %s\n"),
734                         name, transport->url);
735 }
736
737 static struct transport *prepare_transport(struct remote *remote)
738 {
739         struct transport *transport;
740         transport = transport_get(remote, NULL);
741         transport_set_verbosity(transport, verbosity, progress);
742         if (upload_pack)
743                 set_option(transport, TRANS_OPT_UPLOADPACK, upload_pack);
744         if (keep)
745                 set_option(transport, TRANS_OPT_KEEP, "yes");
746         if (depth)
747                 set_option(transport, TRANS_OPT_DEPTH, depth);
748         return transport;
749 }
750
751 static void backfill_tags(struct transport *transport, struct ref *ref_map)
752 {
753         if (transport->cannot_reuse) {
754                 gsecondary = prepare_transport(transport->remote);
755                 transport = gsecondary;
756         }
757
758         transport_set_option(transport, TRANS_OPT_FOLLOWTAGS, NULL);
759         transport_set_option(transport, TRANS_OPT_DEPTH, "0");
760         fetch_refs(transport, ref_map);
761
762         if (gsecondary) {
763                 transport_disconnect(gsecondary);
764                 gsecondary = NULL;
765         }
766 }
767
768 static int do_fetch(struct transport *transport,
769                     struct refspec *refs, int ref_count)
770 {
771         struct string_list existing_refs = STRING_LIST_INIT_DUP;
772         struct ref *ref_map;
773         struct ref *rm;
774         int autotags = (transport->remote->fetch_tags == 1);
775         int retcode = 0;
776
777         for_each_ref(add_existing, &existing_refs);
778
779         if (tags == TAGS_DEFAULT) {
780                 if (transport->remote->fetch_tags == 2)
781                         tags = TAGS_SET;
782                 if (transport->remote->fetch_tags == -1)
783                         tags = TAGS_UNSET;
784         }
785
786         if (!transport->get_refs_list || !transport->fetch)
787                 die(_("Don't know how to fetch from %s"), transport->url);
788
789         /* if not appending, truncate FETCH_HEAD */
790         if (!append && !dry_run) {
791                 retcode = truncate_fetch_head();
792                 if (retcode)
793                         goto cleanup;
794         }
795
796         ref_map = get_ref_map(transport, refs, ref_count, tags, &autotags);
797         if (!update_head_ok)
798                 check_not_current_branch(ref_map);
799
800         for (rm = ref_map; rm; rm = rm->next) {
801                 if (rm->peer_ref) {
802                         struct string_list_item *peer_item =
803                                 string_list_lookup(&existing_refs,
804                                                    rm->peer_ref->name);
805                         if (peer_item)
806                                 hashcpy(rm->peer_ref->old_sha1,
807                                         peer_item->util);
808                 }
809         }
810
811         if (tags == TAGS_DEFAULT && autotags)
812                 transport_set_option(transport, TRANS_OPT_FOLLOWTAGS, "1");
813         if (fetch_refs(transport, ref_map)) {
814                 free_refs(ref_map);
815                 retcode = 1;
816                 goto cleanup;
817         }
818         if (prune) {
819                 /* If --tags was specified, pretend the user gave us the canonical tags refspec */
820                 if (tags == TAGS_SET) {
821                         const char *tags_str = "refs/tags/*:refs/tags/*";
822                         struct refspec *tags_refspec, *refspec;
823
824                         /* Copy the refspec and add the tags to it */
825                         refspec = xcalloc(ref_count + 1, sizeof(struct refspec));
826                         tags_refspec = parse_fetch_refspec(1, &tags_str);
827                         memcpy(refspec, refs, ref_count * sizeof(struct refspec));
828                         memcpy(&refspec[ref_count], tags_refspec, sizeof(struct refspec));
829                         ref_count++;
830
831                         prune_refs(refspec, ref_count, ref_map);
832
833                         ref_count--;
834                         /* The rest of the strings belong to fetch_one */
835                         free_refspec(1, tags_refspec);
836                         free(refspec);
837                 } else if (ref_count) {
838                         prune_refs(refs, ref_count, ref_map);
839                 } else {
840                         prune_refs(transport->remote->fetch, transport->remote->fetch_refspec_nr, ref_map);
841                 }
842         }
843         free_refs(ref_map);
844
845         /* if neither --no-tags nor --tags was specified, do automated tag
846          * following ... */
847         if (tags == TAGS_DEFAULT && autotags) {
848                 struct ref **tail = &ref_map;
849                 ref_map = NULL;
850                 find_non_local_tags(transport, &ref_map, &tail);
851                 if (ref_map)
852                         backfill_tags(transport, ref_map);
853                 free_refs(ref_map);
854         }
855
856  cleanup:
857         string_list_clear(&existing_refs, 1);
858         return retcode;
859 }
860
861 static int get_one_remote_for_fetch(struct remote *remote, void *priv)
862 {
863         struct string_list *list = priv;
864         if (!remote->skip_default_update)
865                 string_list_append(list, remote->name);
866         return 0;
867 }
868
869 struct remote_group_data {
870         const char *name;
871         struct string_list *list;
872 };
873
874 static int get_remote_group(const char *key, const char *value, void *priv)
875 {
876         struct remote_group_data *g = priv;
877
878         if (!prefixcmp(key, "remotes.") &&
879                         !strcmp(key + 8, g->name)) {
880                 /* split list by white space */
881                 int space = strcspn(value, " \t\n");
882                 while (*value) {
883                         if (space > 1) {
884                                 string_list_append(g->list,
885                                                    xstrndup(value, space));
886                         }
887                         value += space + (value[space] != '\0');
888                         space = strcspn(value, " \t\n");
889                 }
890         }
891
892         return 0;
893 }
894
895 static int add_remote_or_group(const char *name, struct string_list *list)
896 {
897         int prev_nr = list->nr;
898         struct remote_group_data g;
899         g.name = name; g.list = list;
900
901         git_config(get_remote_group, &g);
902         if (list->nr == prev_nr) {
903                 struct remote *remote;
904                 if (!remote_is_configured(name))
905                         return 0;
906                 remote = remote_get(name);
907                 string_list_append(list, remote->name);
908         }
909         return 1;
910 }
911
912 static void add_options_to_argv(struct argv_array *argv)
913 {
914         if (dry_run)
915                 argv_array_push(argv, "--dry-run");
916         if (prune)
917                 argv_array_push(argv, "--prune");
918         if (update_head_ok)
919                 argv_array_push(argv, "--update-head-ok");
920         if (force)
921                 argv_array_push(argv, "--force");
922         if (keep)
923                 argv_array_push(argv, "--keep");
924         if (recurse_submodules == RECURSE_SUBMODULES_ON)
925                 argv_array_push(argv, "--recurse-submodules");
926         else if (recurse_submodules == RECURSE_SUBMODULES_ON_DEMAND)
927                 argv_array_push(argv, "--recurse-submodules=on-demand");
928         if (tags == TAGS_SET)
929                 argv_array_push(argv, "--tags");
930         else if (tags == TAGS_UNSET)
931                 argv_array_push(argv, "--no-tags");
932         if (verbosity >= 2)
933                 argv_array_push(argv, "-v");
934         if (verbosity >= 1)
935                 argv_array_push(argv, "-v");
936         else if (verbosity < 0)
937                 argv_array_push(argv, "-q");
938
939 }
940
941 static int fetch_multiple(struct string_list *list)
942 {
943         int i, result = 0;
944         struct argv_array argv = ARGV_ARRAY_INIT;
945
946         if (!append && !dry_run) {
947                 int errcode = truncate_fetch_head();
948                 if (errcode)
949                         return errcode;
950         }
951
952         argv_array_pushl(&argv, "fetch", "--append", NULL);
953         add_options_to_argv(&argv);
954
955         for (i = 0; i < list->nr; i++) {
956                 const char *name = list->items[i].string;
957                 argv_array_push(&argv, name);
958                 if (verbosity >= 0)
959                         printf(_("Fetching %s\n"), name);
960                 if (run_command_v_opt(argv.argv, RUN_GIT_CMD)) {
961                         error(_("Could not fetch %s"), name);
962                         result = 1;
963                 }
964                 argv_array_pop(&argv);
965         }
966
967         argv_array_clear(&argv);
968         return result;
969 }
970
971 static int fetch_one(struct remote *remote, int argc, const char **argv)
972 {
973         int i;
974         static const char **refs = NULL;
975         struct refspec *refspec;
976         int ref_nr = 0;
977         int exit_code;
978
979         if (!remote)
980                 die(_("No remote repository specified.  Please, specify either a URL or a\n"
981                     "remote name from which new revisions should be fetched."));
982
983         gtransport = prepare_transport(remote);
984         if (argc > 0) {
985                 int j = 0;
986                 refs = xcalloc(argc + 1, sizeof(const char *));
987                 for (i = 0; i < argc; i++) {
988                         if (!strcmp(argv[i], "tag")) {
989                                 char *ref;
990                                 i++;
991                                 if (i >= argc)
992                                         die(_("You need to specify a tag name."));
993                                 ref = xmalloc(strlen(argv[i]) * 2 + 22);
994                                 strcpy(ref, "refs/tags/");
995                                 strcat(ref, argv[i]);
996                                 strcat(ref, ":refs/tags/");
997                                 strcat(ref, argv[i]);
998                                 refs[j++] = ref;
999                         } else
1000                                 refs[j++] = argv[i];
1001                 }
1002                 refs[j] = NULL;
1003                 ref_nr = j;
1004         }
1005
1006         sigchain_push_common(unlock_pack_on_signal);
1007         atexit(unlock_pack);
1008         refspec = parse_fetch_refspec(ref_nr, refs);
1009         exit_code = do_fetch(gtransport, refspec, ref_nr);
1010         free_refspec(ref_nr, refspec);
1011         transport_disconnect(gtransport);
1012         gtransport = NULL;
1013         return exit_code;
1014 }
1015
1016 int cmd_fetch(int argc, const char **argv, const char *prefix)
1017 {
1018         int i;
1019         struct string_list list = STRING_LIST_INIT_NODUP;
1020         struct remote *remote;
1021         int result = 0;
1022         static const char *argv_gc_auto[] = {
1023                 "gc", "--auto", NULL,
1024         };
1025
1026         packet_trace_identity("fetch");
1027
1028         /* Record the command line for the reflog */
1029         strbuf_addstr(&default_rla, "fetch");
1030         for (i = 1; i < argc; i++)
1031                 strbuf_addf(&default_rla, " %s", argv[i]);
1032
1033         argc = parse_options(argc, argv, prefix,
1034                              builtin_fetch_options, builtin_fetch_usage, 0);
1035
1036         if (unshallow) {
1037                 if (depth)
1038                         die(_("--depth and --unshallow cannot be used together"));
1039                 else if (!is_repository_shallow())
1040                         die(_("--unshallow on a complete repository does not make sense"));
1041                 else {
1042                         static char inf_depth[12];
1043                         sprintf(inf_depth, "%d", INFINITE_DEPTH);
1044                         depth = inf_depth;
1045                 }
1046         }
1047
1048         if (recurse_submodules != RECURSE_SUBMODULES_OFF) {
1049                 if (recurse_submodules_default) {
1050                         int arg = parse_fetch_recurse_submodules_arg("--recurse-submodules-default", recurse_submodules_default);
1051                         set_config_fetch_recurse_submodules(arg);
1052                 }
1053                 gitmodules_config();
1054                 git_config(submodule_config, NULL);
1055         }
1056
1057         if (all) {
1058                 if (argc == 1)
1059                         die(_("fetch --all does not take a repository argument"));
1060                 else if (argc > 1)
1061                         die(_("fetch --all does not make sense with refspecs"));
1062                 (void) for_each_remote(get_one_remote_for_fetch, &list);
1063                 result = fetch_multiple(&list);
1064         } else if (argc == 0) {
1065                 /* No arguments -- use default remote */
1066                 remote = remote_get(NULL);
1067                 result = fetch_one(remote, argc, argv);
1068         } else if (multiple) {
1069                 /* All arguments are assumed to be remotes or groups */
1070                 for (i = 0; i < argc; i++)
1071                         if (!add_remote_or_group(argv[i], &list))
1072                                 die(_("No such remote or remote group: %s"), argv[i]);
1073                 result = fetch_multiple(&list);
1074         } else {
1075                 /* Single remote or group */
1076                 (void) add_remote_or_group(argv[0], &list);
1077                 if (list.nr > 1) {
1078                         /* More than one remote */
1079                         if (argc > 1)
1080                                 die(_("Fetching a group and specifying refspecs does not make sense"));
1081                         result = fetch_multiple(&list);
1082                 } else {
1083                         /* Zero or one remotes */
1084                         remote = remote_get(argv[0]);
1085                         result = fetch_one(remote, argc-1, argv+1);
1086                 }
1087         }
1088
1089         if (!result && (recurse_submodules != RECURSE_SUBMODULES_OFF)) {
1090                 struct argv_array options = ARGV_ARRAY_INIT;
1091
1092                 add_options_to_argv(&options);
1093                 result = fetch_populated_submodules(&options,
1094                                                     submodule_prefix,
1095                                                     recurse_submodules,
1096                                                     verbosity < 0);
1097                 argv_array_clear(&options);
1098         }
1099
1100         /* All names were strdup()ed or strndup()ed */
1101         list.strdup_strings = 1;
1102         string_list_clear(&list, 0);
1103
1104         run_command_v_opt(argv_gc_auto, RUN_GIT_CMD);
1105
1106         return result;
1107 }