Code

Add the 'fetch.recurseSubmodules' config setting
[git.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"
17 static const char * const builtin_fetch_usage[] = {
18         "git fetch [<options>] [<repository> [<refspec>...]]",
19         "git fetch [<options>] <group>",
20         "git fetch --multiple [<options>] [<repository> | <group>]...",
21         "git fetch --all [<options>]",
22         NULL
23 };
25 enum {
26         TAGS_UNSET = 0,
27         TAGS_DEFAULT = 1,
28         TAGS_SET = 2
29 };
31 enum {
32         RECURSE_SUBMODULES_OFF = 0,
33         RECURSE_SUBMODULES_DEFAULT = 1,
34         RECURSE_SUBMODULES_ON = 2
35 };
37 static int all, append, dry_run, force, keep, multiple, prune, update_head_ok, verbosity;
38 static int progress, recurse_submodules = RECURSE_SUBMODULES_DEFAULT;
39 static int tags = TAGS_DEFAULT;
40 static const char *depth;
41 static const char *upload_pack;
42 static struct strbuf default_rla = STRBUF_INIT;
43 static struct transport *transport;
44 static const char *submodule_prefix = "";
46 static struct option builtin_fetch_options[] = {
47         OPT__VERBOSITY(&verbosity),
48         OPT_BOOLEAN(0, "all", &all,
49                     "fetch from all remotes"),
50         OPT_BOOLEAN('a', "append", &append,
51                     "append to .git/FETCH_HEAD instead of overwriting"),
52         OPT_STRING(0, "upload-pack", &upload_pack, "PATH",
53                    "path to upload pack on remote end"),
54         OPT_BOOLEAN('f', "force", &force,
55                     "force overwrite of local branch"),
56         OPT_BOOLEAN('m', "multiple", &multiple,
57                     "fetch from multiple remotes"),
58         OPT_SET_INT('t', "tags", &tags,
59                     "fetch all tags and associated objects", TAGS_SET),
60         OPT_SET_INT('n', NULL, &tags,
61                     "do not fetch all tags (--no-tags)", TAGS_UNSET),
62         OPT_BOOLEAN('p', "prune", &prune,
63                     "prune tracking branches no longer on remote"),
64         OPT_SET_INT(0, "recurse-submodules", &recurse_submodules,
65                     "control recursive fetching of submodules",
66                     RECURSE_SUBMODULES_ON),
67         OPT_BOOLEAN(0, "dry-run", &dry_run,
68                     "dry run"),
69         OPT_BOOLEAN('k', "keep", &keep, "keep downloaded pack"),
70         OPT_BOOLEAN('u', "update-head-ok", &update_head_ok,
71                     "allow updating of HEAD ref"),
72         OPT_BOOLEAN(0, "progress", &progress, "force progress reporting"),
73         OPT_STRING(0, "depth", &depth, "DEPTH",
74                    "deepen history of shallow clone"),
75         { OPTION_STRING, 0, "submodule-prefix", &submodule_prefix, "DIR",
76                    "prepend this to submodule path output", PARSE_OPT_HIDDEN },
77         OPT_END()
78 };
80 static void unlock_pack(void)
81 {
82         if (transport)
83                 transport_unlock_pack(transport);
84 }
86 static void unlock_pack_on_signal(int signo)
87 {
88         unlock_pack();
89         sigchain_pop(signo);
90         raise(signo);
91 }
93 static void add_merge_config(struct ref **head,
94                            const struct ref *remote_refs,
95                            struct branch *branch,
96                            struct ref ***tail)
97 {
98         int i;
100         for (i = 0; i < branch->merge_nr; i++) {
101                 struct ref *rm, **old_tail = *tail;
102                 struct refspec refspec;
104                 for (rm = *head; rm; rm = rm->next) {
105                         if (branch_merge_matches(branch, i, rm->name)) {
106                                 rm->merge = 1;
107                                 break;
108                         }
109                 }
110                 if (rm)
111                         continue;
113                 /*
114                  * Not fetched to a tracking branch?  We need to fetch
115                  * it anyway to allow this branch's "branch.$name.merge"
116                  * to be honored by 'git pull', but we do not have to
117                  * fail if branch.$name.merge is misconfigured to point
118                  * at a nonexisting branch.  If we were indeed called by
119                  * 'git pull', it will notice the misconfiguration because
120                  * there is no entry in the resulting FETCH_HEAD marked
121                  * for merging.
122                  */
123                 memset(&refspec, 0, sizeof(refspec));
124                 refspec.src = branch->merge[i]->src;
125                 get_fetch_map(remote_refs, &refspec, tail, 1);
126                 for (rm = *old_tail; rm; rm = rm->next)
127                         rm->merge = 1;
128         }
131 static void find_non_local_tags(struct transport *transport,
132                         struct ref **head,
133                         struct ref ***tail);
135 static struct ref *get_ref_map(struct transport *transport,
136                                struct refspec *refs, int ref_count, int tags,
137                                int *autotags)
139         int i;
140         struct ref *rm;
141         struct ref *ref_map = NULL;
142         struct ref **tail = &ref_map;
144         const struct ref *remote_refs = transport_get_remote_refs(transport);
146         if (ref_count || tags == TAGS_SET) {
147                 for (i = 0; i < ref_count; i++) {
148                         get_fetch_map(remote_refs, &refs[i], &tail, 0);
149                         if (refs[i].dst && refs[i].dst[0])
150                                 *autotags = 1;
151                 }
152                 /* Merge everything on the command line, but not --tags */
153                 for (rm = ref_map; rm; rm = rm->next)
154                         rm->merge = 1;
155                 if (tags == TAGS_SET)
156                         get_fetch_map(remote_refs, tag_refspec, &tail, 0);
157         } else {
158                 /* Use the defaults */
159                 struct remote *remote = transport->remote;
160                 struct branch *branch = branch_get(NULL);
161                 int has_merge = branch_has_merge_config(branch);
162                 if (remote && (remote->fetch_refspec_nr || has_merge)) {
163                         for (i = 0; i < remote->fetch_refspec_nr; i++) {
164                                 get_fetch_map(remote_refs, &remote->fetch[i], &tail, 0);
165                                 if (remote->fetch[i].dst &&
166                                     remote->fetch[i].dst[0])
167                                         *autotags = 1;
168                                 if (!i && !has_merge && ref_map &&
169                                     !remote->fetch[0].pattern)
170                                         ref_map->merge = 1;
171                         }
172                         /*
173                          * if the remote we're fetching from is the same
174                          * as given in branch.<name>.remote, we add the
175                          * ref given in branch.<name>.merge, too.
176                          */
177                         if (has_merge &&
178                             !strcmp(branch->remote_name, remote->name))
179                                 add_merge_config(&ref_map, remote_refs, branch, &tail);
180                 } else {
181                         ref_map = get_remote_ref(remote_refs, "HEAD");
182                         if (!ref_map)
183                                 die("Couldn't find remote ref HEAD");
184                         ref_map->merge = 1;
185                         tail = &ref_map->next;
186                 }
187         }
188         if (tags == TAGS_DEFAULT && *autotags)
189                 find_non_local_tags(transport, &ref_map, &tail);
190         ref_remove_duplicates(ref_map);
192         return ref_map;
195 #define STORE_REF_ERROR_OTHER 1
196 #define STORE_REF_ERROR_DF_CONFLICT 2
198 static int s_update_ref(const char *action,
199                         struct ref *ref,
200                         int check_old)
202         char msg[1024];
203         char *rla = getenv("GIT_REFLOG_ACTION");
204         static struct ref_lock *lock;
206         if (dry_run)
207                 return 0;
208         if (!rla)
209                 rla = default_rla.buf;
210         snprintf(msg, sizeof(msg), "%s: %s", rla, action);
211         lock = lock_any_ref_for_update(ref->name,
212                                        check_old ? ref->old_sha1 : NULL, 0);
213         if (!lock)
214                 return errno == ENOTDIR ? STORE_REF_ERROR_DF_CONFLICT :
215                                           STORE_REF_ERROR_OTHER;
216         if (write_ref_sha1(lock, ref->new_sha1, msg) < 0)
217                 return errno == ENOTDIR ? STORE_REF_ERROR_DF_CONFLICT :
218                                           STORE_REF_ERROR_OTHER;
219         return 0;
222 #define REFCOL_WIDTH  10
224 static int update_local_ref(struct ref *ref,
225                             const char *remote,
226                             char *display)
228         struct commit *current = NULL, *updated;
229         enum object_type type;
230         struct branch *current_branch = branch_get(NULL);
231         const char *pretty_ref = prettify_refname(ref->name);
233         *display = 0;
234         type = sha1_object_info(ref->new_sha1, NULL);
235         if (type < 0)
236                 die("object %s not found", sha1_to_hex(ref->new_sha1));
238         if (!hashcmp(ref->old_sha1, ref->new_sha1)) {
239                 if (verbosity > 0)
240                         sprintf(display, "= %-*s %-*s -> %s", TRANSPORT_SUMMARY_WIDTH,
241                                 "[up to date]", REFCOL_WIDTH, remote,
242                                 pretty_ref);
243                 return 0;
244         }
246         if (current_branch &&
247             !strcmp(ref->name, current_branch->name) &&
248             !(update_head_ok || is_bare_repository()) &&
249             !is_null_sha1(ref->old_sha1)) {
250                 /*
251                  * If this is the head, and it's not okay to update
252                  * the head, and the old value of the head isn't empty...
253                  */
254                 sprintf(display, "! %-*s %-*s -> %s  (can't fetch in current branch)",
255                         TRANSPORT_SUMMARY_WIDTH, "[rejected]", REFCOL_WIDTH, remote,
256                         pretty_ref);
257                 return 1;
258         }
260         if (!is_null_sha1(ref->old_sha1) &&
261             !prefixcmp(ref->name, "refs/tags/")) {
262                 int r;
263                 r = s_update_ref("updating tag", ref, 0);
264                 sprintf(display, "%c %-*s %-*s -> %s%s", r ? '!' : '-',
265                         TRANSPORT_SUMMARY_WIDTH, "[tag update]", REFCOL_WIDTH, remote,
266                         pretty_ref, r ? "  (unable to update local ref)" : "");
267                 return r;
268         }
270         current = lookup_commit_reference_gently(ref->old_sha1, 1);
271         updated = lookup_commit_reference_gently(ref->new_sha1, 1);
272         if (!current || !updated) {
273                 const char *msg;
274                 const char *what;
275                 int r;
276                 if (!strncmp(ref->name, "refs/tags/", 10)) {
277                         msg = "storing tag";
278                         what = "[new tag]";
279                 }
280                 else {
281                         msg = "storing head";
282                         what = "[new branch]";
283                 }
285                 r = s_update_ref(msg, ref, 0);
286                 sprintf(display, "%c %-*s %-*s -> %s%s", r ? '!' : '*',
287                         TRANSPORT_SUMMARY_WIDTH, what, REFCOL_WIDTH, remote, pretty_ref,
288                         r ? "  (unable to update local ref)" : "");
289                 return r;
290         }
292         if (in_merge_bases(current, &updated, 1)) {
293                 char quickref[83];
294                 int r;
295                 strcpy(quickref, find_unique_abbrev(current->object.sha1, DEFAULT_ABBREV));
296                 strcat(quickref, "..");
297                 strcat(quickref, find_unique_abbrev(ref->new_sha1, DEFAULT_ABBREV));
298                 r = s_update_ref("fast-forward", ref, 1);
299                 sprintf(display, "%c %-*s %-*s -> %s%s", r ? '!' : ' ',
300                         TRANSPORT_SUMMARY_WIDTH, quickref, REFCOL_WIDTH, remote,
301                         pretty_ref, r ? "  (unable to update local ref)" : "");
302                 return r;
303         } else if (force || ref->force) {
304                 char quickref[84];
305                 int r;
306                 strcpy(quickref, find_unique_abbrev(current->object.sha1, DEFAULT_ABBREV));
307                 strcat(quickref, "...");
308                 strcat(quickref, find_unique_abbrev(ref->new_sha1, DEFAULT_ABBREV));
309                 r = s_update_ref("forced-update", ref, 1);
310                 sprintf(display, "%c %-*s %-*s -> %s  (%s)", r ? '!' : '+',
311                         TRANSPORT_SUMMARY_WIDTH, quickref, REFCOL_WIDTH, remote,
312                         pretty_ref,
313                         r ? "unable to update local ref" : "forced update");
314                 return r;
315         } else {
316                 sprintf(display, "! %-*s %-*s -> %s  (non-fast-forward)",
317                         TRANSPORT_SUMMARY_WIDTH, "[rejected]", REFCOL_WIDTH, remote,
318                         pretty_ref);
319                 return 1;
320         }
323 static int store_updated_refs(const char *raw_url, const char *remote_name,
324                 struct ref *ref_map)
326         FILE *fp;
327         struct commit *commit;
328         int url_len, i, note_len, shown_url = 0, rc = 0;
329         char note[1024];
330         const char *what, *kind;
331         struct ref *rm;
332         char *url, *filename = dry_run ? "/dev/null" : git_path("FETCH_HEAD");
334         fp = fopen(filename, "a");
335         if (!fp)
336                 return error("cannot open %s: %s\n", filename, strerror(errno));
338         if (raw_url)
339                 url = transport_anonymize_url(raw_url);
340         else
341                 url = xstrdup("foreign");
342         for (rm = ref_map; rm; rm = rm->next) {
343                 struct ref *ref = NULL;
345                 if (rm->peer_ref) {
346                         ref = xcalloc(1, sizeof(*ref) + strlen(rm->peer_ref->name) + 1);
347                         strcpy(ref->name, rm->peer_ref->name);
348                         hashcpy(ref->old_sha1, rm->peer_ref->old_sha1);
349                         hashcpy(ref->new_sha1, rm->old_sha1);
350                         ref->force = rm->peer_ref->force;
351                 }
353                 commit = lookup_commit_reference_gently(rm->old_sha1, 1);
354                 if (!commit)
355                         rm->merge = 0;
357                 if (!strcmp(rm->name, "HEAD")) {
358                         kind = "";
359                         what = "";
360                 }
361                 else if (!prefixcmp(rm->name, "refs/heads/")) {
362                         kind = "branch";
363                         what = rm->name + 11;
364                 }
365                 else if (!prefixcmp(rm->name, "refs/tags/")) {
366                         kind = "tag";
367                         what = rm->name + 10;
368                 }
369                 else if (!prefixcmp(rm->name, "refs/remotes/")) {
370                         kind = "remote branch";
371                         what = rm->name + 13;
372                 }
373                 else {
374                         kind = "";
375                         what = rm->name;
376                 }
378                 url_len = strlen(url);
379                 for (i = url_len - 1; url[i] == '/' && 0 <= i; i--)
380                         ;
381                 url_len = i + 1;
382                 if (4 < i && !strncmp(".git", url + i - 3, 4))
383                         url_len = i - 3;
385                 note_len = 0;
386                 if (*what) {
387                         if (*kind)
388                                 note_len += sprintf(note + note_len, "%s ",
389                                                     kind);
390                         note_len += sprintf(note + note_len, "'%s' of ", what);
391                 }
392                 note[note_len] = '\0';
393                 fprintf(fp, "%s\t%s\t%s",
394                         sha1_to_hex(commit ? commit->object.sha1 :
395                                     rm->old_sha1),
396                         rm->merge ? "" : "not-for-merge",
397                         note);
398                 for (i = 0; i < url_len; ++i)
399                         if ('\n' == url[i])
400                                 fputs("\\n", fp);
401                         else
402                                 fputc(url[i], fp);
403                 fputc('\n', fp);
405                 if (ref) {
406                         rc |= update_local_ref(ref, what, note);
407                         free(ref);
408                 } else
409                         sprintf(note, "* %-*s %-*s -> FETCH_HEAD",
410                                 TRANSPORT_SUMMARY_WIDTH, *kind ? kind : "branch",
411                                  REFCOL_WIDTH, *what ? what : "HEAD");
412                 if (*note) {
413                         if (verbosity >= 0 && !shown_url) {
414                                 fprintf(stderr, "From %.*s\n",
415                                                 url_len, url);
416                                 shown_url = 1;
417                         }
418                         if (verbosity >= 0)
419                                 fprintf(stderr, " %s\n", note);
420                 }
421         }
422         free(url);
423         fclose(fp);
424         if (rc & STORE_REF_ERROR_DF_CONFLICT)
425                 error("some local refs could not be updated; try running\n"
426                       " 'git remote prune %s' to remove any old, conflicting "
427                       "branches", remote_name);
428         return rc;
431 /*
432  * We would want to bypass the object transfer altogether if
433  * everything we are going to fetch already exists and is connected
434  * locally.
435  *
436  * The refs we are going to fetch are in ref_map.  If running
437  *
438  *  $ git rev-list --objects --stdin --not --all
439  *
440  * (feeding all the refs in ref_map on its standard input)
441  * does not error out, that means everything reachable from the
442  * refs we are going to fetch exists and is connected to some of
443  * our existing refs.
444  */
445 static int quickfetch(struct ref *ref_map)
447         struct child_process revlist;
448         struct ref *ref;
449         int err;
450         const char *argv[] = {"rev-list",
451                 "--quiet", "--objects", "--stdin", "--not", "--all", NULL};
453         /*
454          * If we are deepening a shallow clone we already have these
455          * objects reachable.  Running rev-list here will return with
456          * a good (0) exit status and we'll bypass the fetch that we
457          * really need to perform.  Claiming failure now will ensure
458          * we perform the network exchange to deepen our history.
459          */
460         if (depth)
461                 return -1;
463         if (!ref_map)
464                 return 0;
466         memset(&revlist, 0, sizeof(revlist));
467         revlist.argv = argv;
468         revlist.git_cmd = 1;
469         revlist.no_stdout = 1;
470         revlist.no_stderr = 1;
471         revlist.in = -1;
473         err = start_command(&revlist);
474         if (err) {
475                 error("could not run rev-list");
476                 return err;
477         }
479         /*
480          * If rev-list --stdin encounters an unknown commit, it terminates,
481          * which will cause SIGPIPE in the write loop below.
482          */
483         sigchain_push(SIGPIPE, SIG_IGN);
485         for (ref = ref_map; ref; ref = ref->next) {
486                 if (write_in_full(revlist.in, sha1_to_hex(ref->old_sha1), 40) < 0 ||
487                     write_str_in_full(revlist.in, "\n") < 0) {
488                         if (errno != EPIPE && errno != EINVAL)
489                                 error("failed write to rev-list: %s", strerror(errno));
490                         err = -1;
491                         break;
492                 }
493         }
495         if (close(revlist.in)) {
496                 error("failed to close rev-list's stdin: %s", strerror(errno));
497                 err = -1;
498         }
500         sigchain_pop(SIGPIPE);
502         return finish_command(&revlist) || err;
505 static int fetch_refs(struct transport *transport, struct ref *ref_map)
507         int ret = quickfetch(ref_map);
508         if (ret)
509                 ret = transport_fetch_refs(transport, ref_map);
510         if (!ret)
511                 ret |= store_updated_refs(transport->url,
512                                 transport->remote->name,
513                                 ref_map);
514         transport_unlock_pack(transport);
515         return ret;
518 static int prune_refs(struct transport *transport, struct ref *ref_map)
520         int result = 0;
521         struct ref *ref, *stale_refs = get_stale_heads(transport->remote, ref_map);
522         const char *dangling_msg = dry_run
523                 ? "   (%s will become dangling)\n"
524                 : "   (%s has become dangling)\n";
526         for (ref = stale_refs; ref; ref = ref->next) {
527                 if (!dry_run)
528                         result |= delete_ref(ref->name, NULL, 0);
529                 if (verbosity >= 0) {
530                         fprintf(stderr, " x %-*s %-*s -> %s\n",
531                                 TRANSPORT_SUMMARY_WIDTH, "[deleted]",
532                                 REFCOL_WIDTH, "(none)", prettify_refname(ref->name));
533                         warn_dangling_symref(stderr, dangling_msg, ref->name);
534                 }
535         }
536         free_refs(stale_refs);
537         return result;
540 static int add_existing(const char *refname, const unsigned char *sha1,
541                         int flag, void *cbdata)
543         struct string_list *list = (struct string_list *)cbdata;
544         struct string_list_item *item = string_list_insert(list, refname);
545         item->util = (void *)sha1;
546         return 0;
549 static int will_fetch(struct ref **head, const unsigned char *sha1)
551         struct ref *rm = *head;
552         while (rm) {
553                 if (!hashcmp(rm->old_sha1, sha1))
554                         return 1;
555                 rm = rm->next;
556         }
557         return 0;
560 static void find_non_local_tags(struct transport *transport,
561                         struct ref **head,
562                         struct ref ***tail)
564         struct string_list existing_refs = STRING_LIST_INIT_NODUP;
565         struct string_list remote_refs = STRING_LIST_INIT_NODUP;
566         const struct ref *ref;
567         struct string_list_item *item = NULL;
569         for_each_ref(add_existing, &existing_refs);
570         for (ref = transport_get_remote_refs(transport); ref; ref = ref->next) {
571                 if (prefixcmp(ref->name, "refs/tags"))
572                         continue;
574                 /*
575                  * The peeled ref always follows the matching base
576                  * ref, so if we see a peeled ref that we don't want
577                  * to fetch then we can mark the ref entry in the list
578                  * as one to ignore by setting util to NULL.
579                  */
580                 if (!suffixcmp(ref->name, "^{}")) {
581                         if (item && !has_sha1_file(ref->old_sha1) &&
582                             !will_fetch(head, ref->old_sha1) &&
583                             !has_sha1_file(item->util) &&
584                             !will_fetch(head, item->util))
585                                 item->util = NULL;
586                         item = NULL;
587                         continue;
588                 }
590                 /*
591                  * If item is non-NULL here, then we previously saw a
592                  * ref not followed by a peeled reference, so we need
593                  * to check if it is a lightweight tag that we want to
594                  * fetch.
595                  */
596                 if (item && !has_sha1_file(item->util) &&
597                     !will_fetch(head, item->util))
598                         item->util = NULL;
600                 item = NULL;
602                 /* skip duplicates and refs that we already have */
603                 if (string_list_has_string(&remote_refs, ref->name) ||
604                     string_list_has_string(&existing_refs, ref->name))
605                         continue;
607                 item = string_list_insert(&remote_refs, ref->name);
608                 item->util = (void *)ref->old_sha1;
609         }
610         string_list_clear(&existing_refs, 0);
612         /*
613          * We may have a final lightweight tag that needs to be
614          * checked to see if it needs fetching.
615          */
616         if (item && !has_sha1_file(item->util) &&
617             !will_fetch(head, item->util))
618                 item->util = NULL;
620         /*
621          * For all the tags in the remote_refs string list,
622          * add them to the list of refs to be fetched
623          */
624         for_each_string_list_item(item, &remote_refs) {
625                 /* Unless we have already decided to ignore this item... */
626                 if (item->util)
627                 {
628                         struct ref *rm = alloc_ref(item->string);
629                         rm->peer_ref = alloc_ref(item->string);
630                         hashcpy(rm->old_sha1, item->util);
631                         **tail = rm;
632                         *tail = &rm->next;
633                 }
634         }
636         string_list_clear(&remote_refs, 0);
639 static void check_not_current_branch(struct ref *ref_map)
641         struct branch *current_branch = branch_get(NULL);
643         if (is_bare_repository() || !current_branch)
644                 return;
646         for (; ref_map; ref_map = ref_map->next)
647                 if (ref_map->peer_ref && !strcmp(current_branch->refname,
648                                         ref_map->peer_ref->name))
649                         die("Refusing to fetch into current branch %s "
650                             "of non-bare repository", current_branch->refname);
653 static int truncate_fetch_head(void)
655         char *filename = git_path("FETCH_HEAD");
656         FILE *fp = fopen(filename, "w");
658         if (!fp)
659                 return error("cannot open %s: %s\n", filename, strerror(errno));
660         fclose(fp);
661         return 0;
664 static int do_fetch(struct transport *transport,
665                     struct refspec *refs, int ref_count)
667         struct string_list existing_refs = STRING_LIST_INIT_NODUP;
668         struct string_list_item *peer_item = NULL;
669         struct ref *ref_map;
670         struct ref *rm;
671         int autotags = (transport->remote->fetch_tags == 1);
673         for_each_ref(add_existing, &existing_refs);
675         if (transport->remote->fetch_tags == 2 && tags != TAGS_UNSET)
676                 tags = TAGS_SET;
677         if (transport->remote->fetch_tags == -1)
678                 tags = TAGS_UNSET;
680         if (!transport->get_refs_list || !transport->fetch)
681                 die("Don't know how to fetch from %s", transport->url);
683         /* if not appending, truncate FETCH_HEAD */
684         if (!append && !dry_run) {
685                 int errcode = truncate_fetch_head();
686                 if (errcode)
687                         return errcode;
688         }
690         ref_map = get_ref_map(transport, refs, ref_count, tags, &autotags);
691         if (!update_head_ok)
692                 check_not_current_branch(ref_map);
694         for (rm = ref_map; rm; rm = rm->next) {
695                 if (rm->peer_ref) {
696                         peer_item = string_list_lookup(&existing_refs,
697                                                        rm->peer_ref->name);
698                         if (peer_item)
699                                 hashcpy(rm->peer_ref->old_sha1,
700                                         peer_item->util);
701                 }
702         }
704         if (tags == TAGS_DEFAULT && autotags)
705                 transport_set_option(transport, TRANS_OPT_FOLLOWTAGS, "1");
706         if (fetch_refs(transport, ref_map)) {
707                 free_refs(ref_map);
708                 return 1;
709         }
710         if (prune)
711                 prune_refs(transport, ref_map);
712         free_refs(ref_map);
714         /* if neither --no-tags nor --tags was specified, do automated tag
715          * following ... */
716         if (tags == TAGS_DEFAULT && autotags) {
717                 struct ref **tail = &ref_map;
718                 ref_map = NULL;
719                 find_non_local_tags(transport, &ref_map, &tail);
720                 if (ref_map) {
721                         transport_set_option(transport, TRANS_OPT_FOLLOWTAGS, NULL);
722                         transport_set_option(transport, TRANS_OPT_DEPTH, "0");
723                         fetch_refs(transport, ref_map);
724                 }
725                 free_refs(ref_map);
726         }
728         return 0;
731 static void set_option(const char *name, const char *value)
733         int r = transport_set_option(transport, name, value);
734         if (r < 0)
735                 die("Option \"%s\" value \"%s\" is not valid for %s",
736                         name, value, transport->url);
737         if (r > 0)
738                 warning("Option \"%s\" is ignored for %s\n",
739                         name, transport->url);
742 static int get_one_remote_for_fetch(struct remote *remote, void *priv)
744         struct string_list *list = priv;
745         if (!remote->skip_default_update)
746                 string_list_append(list, remote->name);
747         return 0;
750 struct remote_group_data {
751         const char *name;
752         struct string_list *list;
753 };
755 static int get_remote_group(const char *key, const char *value, void *priv)
757         struct remote_group_data *g = priv;
759         if (!prefixcmp(key, "remotes.") &&
760                         !strcmp(key + 8, g->name)) {
761                 /* split list by white space */
762                 int space = strcspn(value, " \t\n");
763                 while (*value) {
764                         if (space > 1) {
765                                 string_list_append(g->list,
766                                                    xstrndup(value, space));
767                         }
768                         value += space + (value[space] != '\0');
769                         space = strcspn(value, " \t\n");
770                 }
771         }
773         return 0;
776 static int add_remote_or_group(const char *name, struct string_list *list)
778         int prev_nr = list->nr;
779         struct remote_group_data g;
780         g.name = name; g.list = list;
782         git_config(get_remote_group, &g);
783         if (list->nr == prev_nr) {
784                 struct remote *remote;
785                 if (!remote_is_configured(name))
786                         return 0;
787                 remote = remote_get(name);
788                 string_list_append(list, remote->name);
789         }
790         return 1;
793 static void add_options_to_argv(int *argc, const char **argv)
795         if (dry_run)
796                 argv[(*argc)++] = "--dry-run";
797         if (prune)
798                 argv[(*argc)++] = "--prune";
799         if (update_head_ok)
800                 argv[(*argc)++] = "--update-head-ok";
801         if (force)
802                 argv[(*argc)++] = "--force";
803         if (keep)
804                 argv[(*argc)++] = "--keep";
805         if (recurse_submodules == RECURSE_SUBMODULES_ON)
806                 argv[(*argc)++] = "--recurse-submodules";
807         if (verbosity >= 2)
808                 argv[(*argc)++] = "-v";
809         if (verbosity >= 1)
810                 argv[(*argc)++] = "-v";
811         else if (verbosity < 0)
812                 argv[(*argc)++] = "-q";
816 static int fetch_multiple(struct string_list *list)
818         int i, result = 0;
819         const char *argv[12] = { "fetch", "--append" };
820         int argc = 2;
822         add_options_to_argv(&argc, argv);
824         if (!append && !dry_run) {
825                 int errcode = truncate_fetch_head();
826                 if (errcode)
827                         return errcode;
828         }
830         for (i = 0; i < list->nr; i++) {
831                 const char *name = list->items[i].string;
832                 argv[argc] = name;
833                 argv[argc + 1] = NULL;
834                 if (verbosity >= 0)
835                         printf("Fetching %s\n", name);
836                 if (run_command_v_opt(argv, RUN_GIT_CMD)) {
837                         error("Could not fetch %s", name);
838                         result = 1;
839                 }
840         }
842         return result;
845 static int fetch_one(struct remote *remote, int argc, const char **argv)
847         int i;
848         static const char **refs = NULL;
849         int ref_nr = 0;
850         int exit_code;
852         if (!remote)
853                 die("No remote repository specified.  Please, specify either a URL or a\n"
854                     "remote name from which new revisions should be fetched.");
856         transport = transport_get(remote, NULL);
857         transport_set_verbosity(transport, verbosity, progress);
858         if (upload_pack)
859                 set_option(TRANS_OPT_UPLOADPACK, upload_pack);
860         if (keep)
861                 set_option(TRANS_OPT_KEEP, "yes");
862         if (depth)
863                 set_option(TRANS_OPT_DEPTH, depth);
865         if (argc > 0) {
866                 int j = 0;
867                 refs = xcalloc(argc + 1, sizeof(const char *));
868                 for (i = 0; i < argc; i++) {
869                         if (!strcmp(argv[i], "tag")) {
870                                 char *ref;
871                                 i++;
872                                 if (i >= argc)
873                                         die("You need to specify a tag name.");
874                                 ref = xmalloc(strlen(argv[i]) * 2 + 22);
875                                 strcpy(ref, "refs/tags/");
876                                 strcat(ref, argv[i]);
877                                 strcat(ref, ":refs/tags/");
878                                 strcat(ref, argv[i]);
879                                 refs[j++] = ref;
880                         } else
881                                 refs[j++] = argv[i];
882                 }
883                 refs[j] = NULL;
884                 ref_nr = j;
885         }
887         sigchain_push_common(unlock_pack_on_signal);
888         atexit(unlock_pack);
889         exit_code = do_fetch(transport,
890                         parse_fetch_refspec(ref_nr, refs), ref_nr);
891         transport_disconnect(transport);
892         transport = NULL;
893         return exit_code;
896 int cmd_fetch(int argc, const char **argv, const char *prefix)
898         int i;
899         struct string_list list = STRING_LIST_INIT_NODUP;
900         struct remote *remote;
901         int result = 0;
903         /* Record the command line for the reflog */
904         strbuf_addstr(&default_rla, "fetch");
905         for (i = 1; i < argc; i++)
906                 strbuf_addf(&default_rla, " %s", argv[i]);
908         argc = parse_options(argc, argv, prefix,
909                              builtin_fetch_options, builtin_fetch_usage, 0);
911         if (all) {
912                 if (argc == 1)
913                         die("fetch --all does not take a repository argument");
914                 else if (argc > 1)
915                         die("fetch --all does not make sense with refspecs");
916                 (void) for_each_remote(get_one_remote_for_fetch, &list);
917                 result = fetch_multiple(&list);
918         } else if (argc == 0) {
919                 /* No arguments -- use default remote */
920                 remote = remote_get(NULL);
921                 result = fetch_one(remote, argc, argv);
922         } else if (multiple) {
923                 /* All arguments are assumed to be remotes or groups */
924                 for (i = 0; i < argc; i++)
925                         if (!add_remote_or_group(argv[i], &list))
926                                 die("No such remote or remote group: %s", argv[i]);
927                 result = fetch_multiple(&list);
928         } else {
929                 /* Single remote or group */
930                 (void) add_remote_or_group(argv[0], &list);
931                 if (list.nr > 1) {
932                         /* More than one remote */
933                         if (argc > 1)
934                                 die("Fetching a group and specifying refspecs does not make sense");
935                         result = fetch_multiple(&list);
936                 } else {
937                         /* Zero or one remotes */
938                         remote = remote_get(argv[0]);
939                         result = fetch_one(remote, argc-1, argv+1);
940                 }
941         }
943         if (!result && (recurse_submodules != RECURSE_SUBMODULES_OFF)) {
944                 const char *options[10];
945                 int num_options = 0;
946                 /* Set recursion as default when we already are recursing */
947                 if (submodule_prefix[0])
948                         set_config_fetch_recurse_submodules(1);
949                 gitmodules_config();
950                 git_config(submodule_config, NULL);
951                 add_options_to_argv(&num_options, options);
952                 result = fetch_populated_submodules(num_options, options,
953                                                     submodule_prefix,
954                                                     recurse_submodules == RECURSE_SUBMODULES_ON,
955                                                     verbosity < 0);
956         }
958         /* All names were strdup()ed or strndup()ed */
959         list.strdup_strings = 1;
960         string_list_clear(&list, 0);
962         return result;