Code

Merge branch 'nd/maint-ignore-exclude' into maint-1.7.7
[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 static int all, append, dry_run, force, keep, multiple, prune, update_head_ok, verbosity;
32 static int progress, recurse_submodules = RECURSE_SUBMODULES_DEFAULT;
33 static int tags = TAGS_DEFAULT;
34 static const char *depth;
35 static const char *upload_pack;
36 static struct strbuf default_rla = STRBUF_INIT;
37 static struct transport *transport;
38 static const char *submodule_prefix = "";
39 static const char *recurse_submodules_default;
41 static int option_parse_recurse_submodules(const struct option *opt,
42                                    const char *arg, int unset)
43 {
44         if (unset) {
45                 recurse_submodules = RECURSE_SUBMODULES_OFF;
46         } else {
47                 if (arg)
48                         recurse_submodules = parse_fetch_recurse_submodules_arg(opt->long_name, arg);
49                 else
50                         recurse_submodules = RECURSE_SUBMODULES_ON;
51         }
52         return 0;
53 }
55 static struct option builtin_fetch_options[] = {
56         OPT__VERBOSITY(&verbosity),
57         OPT_BOOLEAN(0, "all", &all,
58                     "fetch from all remotes"),
59         OPT_BOOLEAN('a', "append", &append,
60                     "append to .git/FETCH_HEAD instead of overwriting"),
61         OPT_STRING(0, "upload-pack", &upload_pack, "path",
62                    "path to upload pack on remote end"),
63         OPT__FORCE(&force, "force overwrite of local branch"),
64         OPT_BOOLEAN('m', "multiple", &multiple,
65                     "fetch from multiple remotes"),
66         OPT_SET_INT('t', "tags", &tags,
67                     "fetch all tags and associated objects", TAGS_SET),
68         OPT_SET_INT('n', NULL, &tags,
69                     "do not fetch all tags (--no-tags)", TAGS_UNSET),
70         OPT_BOOLEAN('p', "prune", &prune,
71                     "prune remote-tracking branches no longer on remote"),
72         { OPTION_CALLBACK, 0, "recurse-submodules", NULL, "on-demand",
73                     "control recursive fetching of submodules",
74                     PARSE_OPT_OPTARG, option_parse_recurse_submodules },
75         OPT_BOOLEAN(0, "dry-run", &dry_run,
76                     "dry run"),
77         OPT_BOOLEAN('k', "keep", &keep, "keep downloaded pack"),
78         OPT_BOOLEAN('u', "update-head-ok", &update_head_ok,
79                     "allow updating of HEAD ref"),
80         OPT_BOOLEAN(0, "progress", &progress, "force progress reporting"),
81         OPT_STRING(0, "depth", &depth, "depth",
82                    "deepen history of shallow clone"),
83         { OPTION_STRING, 0, "submodule-prefix", &submodule_prefix, "dir",
84                    "prepend this to submodule path output", PARSE_OPT_HIDDEN },
85         { OPTION_STRING, 0, "recurse-submodules-default",
86                    &recurse_submodules_default, NULL,
87                    "default mode for recursion", PARSE_OPT_HIDDEN },
88         OPT_END()
89 };
91 static void unlock_pack(void)
92 {
93         if (transport)
94                 transport_unlock_pack(transport);
95 }
97 static void unlock_pack_on_signal(int signo)
98 {
99         unlock_pack();
100         sigchain_pop(signo);
101         raise(signo);
104 static void add_merge_config(struct ref **head,
105                            const struct ref *remote_refs,
106                            struct branch *branch,
107                            struct ref ***tail)
109         int i;
111         for (i = 0; i < branch->merge_nr; i++) {
112                 struct ref *rm, **old_tail = *tail;
113                 struct refspec refspec;
115                 for (rm = *head; rm; rm = rm->next) {
116                         if (branch_merge_matches(branch, i, rm->name)) {
117                                 rm->merge = 1;
118                                 break;
119                         }
120                 }
121                 if (rm)
122                         continue;
124                 /*
125                  * Not fetched to a remote-tracking branch?  We need to fetch
126                  * it anyway to allow this branch's "branch.$name.merge"
127                  * to be honored by 'git pull', but we do not have to
128                  * fail if branch.$name.merge is misconfigured to point
129                  * at a nonexisting branch.  If we were indeed called by
130                  * 'git pull', it will notice the misconfiguration because
131                  * there is no entry in the resulting FETCH_HEAD marked
132                  * for merging.
133                  */
134                 memset(&refspec, 0, sizeof(refspec));
135                 refspec.src = branch->merge[i]->src;
136                 get_fetch_map(remote_refs, &refspec, tail, 1);
137                 for (rm = *old_tail; rm; rm = rm->next)
138                         rm->merge = 1;
139         }
142 static void find_non_local_tags(struct transport *transport,
143                         struct ref **head,
144                         struct ref ***tail);
146 static struct ref *get_ref_map(struct transport *transport,
147                                struct refspec *refs, int ref_count, int tags,
148                                int *autotags)
150         int i;
151         struct ref *rm;
152         struct ref *ref_map = NULL;
153         struct ref **tail = &ref_map;
155         const struct ref *remote_refs = transport_get_remote_refs(transport);
157         if (ref_count || tags == TAGS_SET) {
158                 for (i = 0; i < ref_count; i++) {
159                         get_fetch_map(remote_refs, &refs[i], &tail, 0);
160                         if (refs[i].dst && refs[i].dst[0])
161                                 *autotags = 1;
162                 }
163                 /* Merge everything on the command line, but not --tags */
164                 for (rm = ref_map; rm; rm = rm->next)
165                         rm->merge = 1;
166                 if (tags == TAGS_SET)
167                         get_fetch_map(remote_refs, tag_refspec, &tail, 0);
168         } else {
169                 /* Use the defaults */
170                 struct remote *remote = transport->remote;
171                 struct branch *branch = branch_get(NULL);
172                 int has_merge = branch_has_merge_config(branch);
173                 if (remote &&
174                     (remote->fetch_refspec_nr ||
175                      /* Note: has_merge implies non-NULL branch->remote_name */
176                      (has_merge && !strcmp(branch->remote_name, remote->name)))) {
177                         for (i = 0; i < remote->fetch_refspec_nr; i++) {
178                                 get_fetch_map(remote_refs, &remote->fetch[i], &tail, 0);
179                                 if (remote->fetch[i].dst &&
180                                     remote->fetch[i].dst[0])
181                                         *autotags = 1;
182                                 if (!i && !has_merge && ref_map &&
183                                     !remote->fetch[0].pattern)
184                                         ref_map->merge = 1;
185                         }
186                         /*
187                          * if the remote we're fetching from is the same
188                          * as given in branch.<name>.remote, we add the
189                          * ref given in branch.<name>.merge, too.
190                          *
191                          * Note: has_merge implies non-NULL branch->remote_name
192                          */
193                         if (has_merge &&
194                             !strcmp(branch->remote_name, remote->name))
195                                 add_merge_config(&ref_map, remote_refs, branch, &tail);
196                 } else {
197                         ref_map = get_remote_ref(remote_refs, "HEAD");
198                         if (!ref_map)
199                                 die(_("Couldn't find remote ref HEAD"));
200                         ref_map->merge = 1;
201                         tail = &ref_map->next;
202                 }
203         }
204         if (tags == TAGS_DEFAULT && *autotags)
205                 find_non_local_tags(transport, &ref_map, &tail);
206         ref_remove_duplicates(ref_map);
208         return ref_map;
211 #define STORE_REF_ERROR_OTHER 1
212 #define STORE_REF_ERROR_DF_CONFLICT 2
214 static int s_update_ref(const char *action,
215                         struct ref *ref,
216                         int check_old)
218         char msg[1024];
219         char *rla = getenv("GIT_REFLOG_ACTION");
220         static struct ref_lock *lock;
222         if (dry_run)
223                 return 0;
224         if (!rla)
225                 rla = default_rla.buf;
226         snprintf(msg, sizeof(msg), "%s: %s", rla, action);
227         lock = lock_any_ref_for_update(ref->name,
228                                        check_old ? ref->old_sha1 : NULL, 0);
229         if (!lock)
230                 return errno == ENOTDIR ? STORE_REF_ERROR_DF_CONFLICT :
231                                           STORE_REF_ERROR_OTHER;
232         if (write_ref_sha1(lock, ref->new_sha1, msg) < 0)
233                 return errno == ENOTDIR ? STORE_REF_ERROR_DF_CONFLICT :
234                                           STORE_REF_ERROR_OTHER;
235         return 0;
238 #define REFCOL_WIDTH  10
240 static int update_local_ref(struct ref *ref,
241                             const char *remote,
242                             struct strbuf *display)
244         struct commit *current = NULL, *updated;
245         enum object_type type;
246         struct branch *current_branch = branch_get(NULL);
247         const char *pretty_ref = prettify_refname(ref->name);
249         type = sha1_object_info(ref->new_sha1, NULL);
250         if (type < 0)
251                 die(_("object %s not found"), sha1_to_hex(ref->new_sha1));
253         if (!hashcmp(ref->old_sha1, ref->new_sha1)) {
254                 if (verbosity > 0)
255                         strbuf_addf(display, "= %-*s %-*s -> %s",
256                                     TRANSPORT_SUMMARY_WIDTH,
257                                     _("[up to date]"), REFCOL_WIDTH,
258                                     remote, pretty_ref);
259                 return 0;
260         }
262         if (current_branch &&
263             !strcmp(ref->name, current_branch->name) &&
264             !(update_head_ok || is_bare_repository()) &&
265             !is_null_sha1(ref->old_sha1)) {
266                 /*
267                  * If this is the head, and it's not okay to update
268                  * the head, and the old value of the head isn't empty...
269                  */
270                 strbuf_addf(display,
271                             _("! %-*s %-*s -> %s  (can't fetch in current branch)"),
272                             TRANSPORT_SUMMARY_WIDTH, _("[rejected]"),
273                             REFCOL_WIDTH, remote, pretty_ref);
274                 return 1;
275         }
277         if (!is_null_sha1(ref->old_sha1) &&
278             !prefixcmp(ref->name, "refs/tags/")) {
279                 int r;
280                 r = s_update_ref("updating tag", ref, 0);
281                 strbuf_addf(display, "%c %-*s %-*s -> %s%s",
282                             r ? '!' : '-',
283                             TRANSPORT_SUMMARY_WIDTH, _("[tag update]"),
284                             REFCOL_WIDTH, remote, pretty_ref,
285                             r ? _("  (unable to update local ref)") : "");
286                 return r;
287         }
289         current = lookup_commit_reference_gently(ref->old_sha1, 1);
290         updated = lookup_commit_reference_gently(ref->new_sha1, 1);
291         if (!current || !updated) {
292                 const char *msg;
293                 const char *what;
294                 int r;
295                 if (!strncmp(ref->name, "refs/tags/", 10)) {
296                         msg = "storing tag";
297                         what = _("[new tag]");
298                 }
299                 else {
300                         msg = "storing head";
301                         what = _("[new branch]");
302                         if ((recurse_submodules != RECURSE_SUBMODULES_OFF) &&
303                             (recurse_submodules != RECURSE_SUBMODULES_ON))
304                                 check_for_new_submodule_commits(ref->new_sha1);
305                 }
307                 r = s_update_ref(msg, ref, 0);
308                 strbuf_addf(display, "%c %-*s %-*s -> %s%s",
309                             r ? '!' : '*',
310                             TRANSPORT_SUMMARY_WIDTH, what,
311                             REFCOL_WIDTH, remote, pretty_ref,
312                             r ? _("  (unable to update local ref)") : "");
313                 return r;
314         }
316         if (in_merge_bases(current, &updated, 1)) {
317                 char quickref[83];
318                 int r;
319                 strcpy(quickref, find_unique_abbrev(current->object.sha1, DEFAULT_ABBREV));
320                 strcat(quickref, "..");
321                 strcat(quickref, find_unique_abbrev(ref->new_sha1, DEFAULT_ABBREV));
322                 if ((recurse_submodules != RECURSE_SUBMODULES_OFF) &&
323                     (recurse_submodules != RECURSE_SUBMODULES_ON))
324                         check_for_new_submodule_commits(ref->new_sha1);
325                 r = s_update_ref("fast-forward", ref, 1);
326                 strbuf_addf(display, "%c %-*s %-*s -> %s%s",
327                             r ? '!' : ' ',
328                             TRANSPORT_SUMMARY_WIDTH, quickref,
329                             REFCOL_WIDTH, remote, pretty_ref,
330                             r ? _("  (unable to update local ref)") : "");
331                 return r;
332         } else if (force || ref->force) {
333                 char quickref[84];
334                 int r;
335                 strcpy(quickref, find_unique_abbrev(current->object.sha1, DEFAULT_ABBREV));
336                 strcat(quickref, "...");
337                 strcat(quickref, find_unique_abbrev(ref->new_sha1, DEFAULT_ABBREV));
338                 if ((recurse_submodules != RECURSE_SUBMODULES_OFF) &&
339                     (recurse_submodules != RECURSE_SUBMODULES_ON))
340                         check_for_new_submodule_commits(ref->new_sha1);
341                 r = s_update_ref("forced-update", ref, 1);
342                 strbuf_addf(display, "%c %-*s %-*s -> %s  (%s)",
343                             r ? '!' : '+',
344                             TRANSPORT_SUMMARY_WIDTH, quickref,
345                             REFCOL_WIDTH, remote, pretty_ref,
346                             r ? _("unable to update local ref") : _("forced update"));
347                 return r;
348         } else {
349                 strbuf_addf(display, "! %-*s %-*s -> %s  %s",
350                             TRANSPORT_SUMMARY_WIDTH, _("[rejected]"),
351                             REFCOL_WIDTH, remote, pretty_ref,
352                             _("(non-fast-forward)"));
353                 return 1;
354         }
357 static int store_updated_refs(const char *raw_url, const char *remote_name,
358                 struct ref *ref_map)
360         FILE *fp;
361         struct commit *commit;
362         int url_len, i, shown_url = 0, rc = 0;
363         struct strbuf note = STRBUF_INIT;
364         const char *what, *kind;
365         struct ref *rm;
366         char *url, *filename = dry_run ? "/dev/null" : git_path("FETCH_HEAD");
368         fp = fopen(filename, "a");
369         if (!fp)
370                 return error(_("cannot open %s: %s\n"), filename, strerror(errno));
372         if (raw_url)
373                 url = transport_anonymize_url(raw_url);
374         else
375                 url = xstrdup("foreign");
376         for (rm = ref_map; rm; rm = rm->next) {
377                 struct ref *ref = NULL;
379                 if (rm->peer_ref) {
380                         ref = xcalloc(1, sizeof(*ref) + strlen(rm->peer_ref->name) + 1);
381                         strcpy(ref->name, rm->peer_ref->name);
382                         hashcpy(ref->old_sha1, rm->peer_ref->old_sha1);
383                         hashcpy(ref->new_sha1, rm->old_sha1);
384                         ref->force = rm->peer_ref->force;
385                 }
387                 commit = lookup_commit_reference_gently(rm->old_sha1, 1);
388                 if (!commit)
389                         rm->merge = 0;
391                 if (!strcmp(rm->name, "HEAD")) {
392                         kind = "";
393                         what = "";
394                 }
395                 else if (!prefixcmp(rm->name, "refs/heads/")) {
396                         kind = "branch";
397                         what = rm->name + 11;
398                 }
399                 else if (!prefixcmp(rm->name, "refs/tags/")) {
400                         kind = "tag";
401                         what = rm->name + 10;
402                 }
403                 else if (!prefixcmp(rm->name, "refs/remotes/")) {
404                         kind = "remote-tracking branch";
405                         what = rm->name + 13;
406                 }
407                 else {
408                         kind = "";
409                         what = rm->name;
410                 }
412                 url_len = strlen(url);
413                 for (i = url_len - 1; url[i] == '/' && 0 <= i; i--)
414                         ;
415                 url_len = i + 1;
416                 if (4 < i && !strncmp(".git", url + i - 3, 4))
417                         url_len = i - 3;
419                 strbuf_reset(&note);
420                 if (*what) {
421                         if (*kind)
422                                 strbuf_addf(&note, "%s ", kind);
423                         strbuf_addf(&note, "'%s' of ", what);
424                 }
425                 fprintf(fp, "%s\t%s\t%s",
426                         sha1_to_hex(commit ? commit->object.sha1 :
427                                     rm->old_sha1),
428                         rm->merge ? "" : "not-for-merge",
429                         note.buf);
430                 for (i = 0; i < url_len; ++i)
431                         if ('\n' == url[i])
432                                 fputs("\\n", fp);
433                         else
434                                 fputc(url[i], fp);
435                 fputc('\n', fp);
437                 strbuf_reset(&note);
438                 if (ref) {
439                         rc |= update_local_ref(ref, what, &note);
440                         free(ref);
441                 } else
442                         strbuf_addf(&note, "* %-*s %-*s -> FETCH_HEAD",
443                                     TRANSPORT_SUMMARY_WIDTH,
444                                     *kind ? kind : "branch",
445                                     REFCOL_WIDTH,
446                                     *what ? what : "HEAD");
447                 if (note.len) {
448                         if (verbosity >= 0 && !shown_url) {
449                                 fprintf(stderr, _("From %.*s\n"),
450                                                 url_len, url);
451                                 shown_url = 1;
452                         }
453                         if (verbosity >= 0)
454                                 fprintf(stderr, " %s\n", note.buf);
455                 }
456         }
457         free(url);
458         fclose(fp);
459         if (rc & STORE_REF_ERROR_DF_CONFLICT)
460                 error(_("some local refs could not be updated; try running\n"
461                       " 'git remote prune %s' to remove any old, conflicting "
462                       "branches"), remote_name);
463         strbuf_release(&note);
464         return rc;
467 /*
468  * We would want to bypass the object transfer altogether if
469  * everything we are going to fetch already exists and is connected
470  * locally.
471  *
472  * The refs we are going to fetch are in ref_map.  If running
473  *
474  *  $ git rev-list --objects --stdin --not --all
475  *
476  * (feeding all the refs in ref_map on its standard input)
477  * does not error out, that means everything reachable from the
478  * refs we are going to fetch exists and is connected to some of
479  * our existing refs.
480  */
481 static int quickfetch(struct ref *ref_map)
483         struct child_process revlist;
484         struct ref *ref;
485         int err;
486         const char *argv[] = {"rev-list",
487                 "--quiet", "--objects", "--stdin", "--not", "--all", NULL};
489         /*
490          * If we are deepening a shallow clone we already have these
491          * objects reachable.  Running rev-list here will return with
492          * a good (0) exit status and we'll bypass the fetch that we
493          * really need to perform.  Claiming failure now will ensure
494          * we perform the network exchange to deepen our history.
495          */
496         if (depth)
497                 return -1;
499         if (!ref_map)
500                 return 0;
502         memset(&revlist, 0, sizeof(revlist));
503         revlist.argv = argv;
504         revlist.git_cmd = 1;
505         revlist.no_stdout = 1;
506         revlist.no_stderr = 1;
507         revlist.in = -1;
509         err = start_command(&revlist);
510         if (err) {
511                 error(_("could not run rev-list"));
512                 return err;
513         }
515         /*
516          * If rev-list --stdin encounters an unknown commit, it terminates,
517          * which will cause SIGPIPE in the write loop below.
518          */
519         sigchain_push(SIGPIPE, SIG_IGN);
521         for (ref = ref_map; ref; ref = ref->next) {
522                 if (write_in_full(revlist.in, sha1_to_hex(ref->old_sha1), 40) < 0 ||
523                     write_str_in_full(revlist.in, "\n") < 0) {
524                         if (errno != EPIPE && errno != EINVAL)
525                                 error(_("failed write to rev-list: %s"), strerror(errno));
526                         err = -1;
527                         break;
528                 }
529         }
531         if (close(revlist.in)) {
532                 error(_("failed to close rev-list's stdin: %s"), strerror(errno));
533                 err = -1;
534         }
536         sigchain_pop(SIGPIPE);
538         return finish_command(&revlist) || err;
541 static int fetch_refs(struct transport *transport, struct ref *ref_map)
543         int ret = quickfetch(ref_map);
544         if (ret)
545                 ret = transport_fetch_refs(transport, ref_map);
546         if (!ret)
547                 ret |= store_updated_refs(transport->url,
548                                 transport->remote->name,
549                                 ref_map);
550         transport_unlock_pack(transport);
551         return ret;
554 static int prune_refs(struct refspec *refs, int ref_count, struct ref *ref_map)
556         int result = 0;
557         struct ref *ref, *stale_refs = get_stale_heads(refs, ref_count, ref_map);
558         const char *dangling_msg = dry_run
559                 ? _("   (%s will become dangling)\n")
560                 : _("   (%s has become dangling)\n");
562         for (ref = stale_refs; ref; ref = ref->next) {
563                 if (!dry_run)
564                         result |= delete_ref(ref->name, NULL, 0);
565                 if (verbosity >= 0) {
566                         fprintf(stderr, " x %-*s %-*s -> %s\n",
567                                 TRANSPORT_SUMMARY_WIDTH, _("[deleted]"),
568                                 REFCOL_WIDTH, _("(none)"), prettify_refname(ref->name));
569                         warn_dangling_symref(stderr, dangling_msg, ref->name);
570                 }
571         }
572         free_refs(stale_refs);
573         return result;
576 static int add_existing(const char *refname, const unsigned char *sha1,
577                         int flag, void *cbdata)
579         struct string_list *list = (struct string_list *)cbdata;
580         struct string_list_item *item = string_list_insert(list, refname);
581         item->util = (void *)sha1;
582         return 0;
585 static int will_fetch(struct ref **head, const unsigned char *sha1)
587         struct ref *rm = *head;
588         while (rm) {
589                 if (!hashcmp(rm->old_sha1, sha1))
590                         return 1;
591                 rm = rm->next;
592         }
593         return 0;
596 static void find_non_local_tags(struct transport *transport,
597                         struct ref **head,
598                         struct ref ***tail)
600         struct string_list existing_refs = STRING_LIST_INIT_NODUP;
601         struct string_list remote_refs = STRING_LIST_INIT_NODUP;
602         const struct ref *ref;
603         struct string_list_item *item = NULL;
605         for_each_ref(add_existing, &existing_refs);
606         for (ref = transport_get_remote_refs(transport); ref; ref = ref->next) {
607                 if (prefixcmp(ref->name, "refs/tags"))
608                         continue;
610                 /*
611                  * The peeled ref always follows the matching base
612                  * ref, so if we see a peeled ref that we don't want
613                  * to fetch then we can mark the ref entry in the list
614                  * as one to ignore by setting util to NULL.
615                  */
616                 if (!suffixcmp(ref->name, "^{}")) {
617                         if (item && !has_sha1_file(ref->old_sha1) &&
618                             !will_fetch(head, ref->old_sha1) &&
619                             !has_sha1_file(item->util) &&
620                             !will_fetch(head, item->util))
621                                 item->util = NULL;
622                         item = NULL;
623                         continue;
624                 }
626                 /*
627                  * If item is non-NULL here, then we previously saw a
628                  * ref not followed by a peeled reference, so we need
629                  * to check if it is a lightweight tag that we want to
630                  * fetch.
631                  */
632                 if (item && !has_sha1_file(item->util) &&
633                     !will_fetch(head, item->util))
634                         item->util = NULL;
636                 item = NULL;
638                 /* skip duplicates and refs that we already have */
639                 if (string_list_has_string(&remote_refs, ref->name) ||
640                     string_list_has_string(&existing_refs, ref->name))
641                         continue;
643                 item = string_list_insert(&remote_refs, ref->name);
644                 item->util = (void *)ref->old_sha1;
645         }
646         string_list_clear(&existing_refs, 0);
648         /*
649          * We may have a final lightweight tag that needs to be
650          * checked to see if it needs fetching.
651          */
652         if (item && !has_sha1_file(item->util) &&
653             !will_fetch(head, item->util))
654                 item->util = NULL;
656         /*
657          * For all the tags in the remote_refs string list,
658          * add them to the list of refs to be fetched
659          */
660         for_each_string_list_item(item, &remote_refs) {
661                 /* Unless we have already decided to ignore this item... */
662                 if (item->util)
663                 {
664                         struct ref *rm = alloc_ref(item->string);
665                         rm->peer_ref = alloc_ref(item->string);
666                         hashcpy(rm->old_sha1, item->util);
667                         **tail = rm;
668                         *tail = &rm->next;
669                 }
670         }
672         string_list_clear(&remote_refs, 0);
675 static void check_not_current_branch(struct ref *ref_map)
677         struct branch *current_branch = branch_get(NULL);
679         if (is_bare_repository() || !current_branch)
680                 return;
682         for (; ref_map; ref_map = ref_map->next)
683                 if (ref_map->peer_ref && !strcmp(current_branch->refname,
684                                         ref_map->peer_ref->name))
685                         die(_("Refusing to fetch into current branch %s "
686                             "of non-bare repository"), current_branch->refname);
689 static int truncate_fetch_head(void)
691         char *filename = git_path("FETCH_HEAD");
692         FILE *fp = fopen(filename, "w");
694         if (!fp)
695                 return error(_("cannot open %s: %s\n"), filename, strerror(errno));
696         fclose(fp);
697         return 0;
700 static int do_fetch(struct transport *transport,
701                     struct refspec *refs, int ref_count)
703         struct string_list existing_refs = STRING_LIST_INIT_NODUP;
704         struct string_list_item *peer_item = NULL;
705         struct ref *ref_map;
706         struct ref *rm;
707         int autotags = (transport->remote->fetch_tags == 1);
709         for_each_ref(add_existing, &existing_refs);
711         if (tags == TAGS_DEFAULT) {
712                 if (transport->remote->fetch_tags == 2)
713                         tags = TAGS_SET;
714                 if (transport->remote->fetch_tags == -1)
715                         tags = TAGS_UNSET;
716         }
718         if (!transport->get_refs_list || !transport->fetch)
719                 die(_("Don't know how to fetch from %s"), transport->url);
721         /* if not appending, truncate FETCH_HEAD */
722         if (!append && !dry_run) {
723                 int errcode = truncate_fetch_head();
724                 if (errcode)
725                         return errcode;
726         }
728         ref_map = get_ref_map(transport, refs, ref_count, tags, &autotags);
729         if (!update_head_ok)
730                 check_not_current_branch(ref_map);
732         for (rm = ref_map; rm; rm = rm->next) {
733                 if (rm->peer_ref) {
734                         peer_item = string_list_lookup(&existing_refs,
735                                                        rm->peer_ref->name);
736                         if (peer_item)
737                                 hashcpy(rm->peer_ref->old_sha1,
738                                         peer_item->util);
739                 }
740         }
742         if (tags == TAGS_DEFAULT && autotags)
743                 transport_set_option(transport, TRANS_OPT_FOLLOWTAGS, "1");
744         if (fetch_refs(transport, ref_map)) {
745                 free_refs(ref_map);
746                 return 1;
747         }
748         if (prune) {
749                 /* If --tags was specified, pretend the user gave us the canonical tags refspec */
750                 if (tags == TAGS_SET) {
751                         const char *tags_str = "refs/tags/*:refs/tags/*";
752                         struct refspec *tags_refspec, *refspec;
754                         /* Copy the refspec and add the tags to it */
755                         refspec = xcalloc(ref_count + 1, sizeof(struct refspec));
756                         tags_refspec = parse_fetch_refspec(1, &tags_str);
757                         memcpy(refspec, refs, ref_count * sizeof(struct refspec));
758                         memcpy(&refspec[ref_count], tags_refspec, sizeof(struct refspec));
759                         ref_count++;
761                         prune_refs(refspec, ref_count, ref_map);
763                         ref_count--;
764                         /* The rest of the strings belong to fetch_one */
765                         free_refspec(1, tags_refspec);
766                         free(refspec);
767                 } else if (ref_count) {
768                         prune_refs(refs, ref_count, ref_map);
769                 } else {
770                         prune_refs(transport->remote->fetch, transport->remote->fetch_refspec_nr, ref_map);
771                 }
772         }
773         free_refs(ref_map);
775         /* if neither --no-tags nor --tags was specified, do automated tag
776          * following ... */
777         if (tags == TAGS_DEFAULT && autotags) {
778                 struct ref **tail = &ref_map;
779                 ref_map = NULL;
780                 find_non_local_tags(transport, &ref_map, &tail);
781                 if (ref_map) {
782                         transport_set_option(transport, TRANS_OPT_FOLLOWTAGS, NULL);
783                         transport_set_option(transport, TRANS_OPT_DEPTH, "0");
784                         fetch_refs(transport, ref_map);
785                 }
786                 free_refs(ref_map);
787         }
789         return 0;
792 static void set_option(const char *name, const char *value)
794         int r = transport_set_option(transport, name, value);
795         if (r < 0)
796                 die(_("Option \"%s\" value \"%s\" is not valid for %s"),
797                         name, value, transport->url);
798         if (r > 0)
799                 warning(_("Option \"%s\" is ignored for %s\n"),
800                         name, transport->url);
803 static int get_one_remote_for_fetch(struct remote *remote, void *priv)
805         struct string_list *list = priv;
806         if (!remote->skip_default_update)
807                 string_list_append(list, remote->name);
808         return 0;
811 struct remote_group_data {
812         const char *name;
813         struct string_list *list;
814 };
816 static int get_remote_group(const char *key, const char *value, void *priv)
818         struct remote_group_data *g = priv;
820         if (!prefixcmp(key, "remotes.") &&
821                         !strcmp(key + 8, g->name)) {
822                 /* split list by white space */
823                 int space = strcspn(value, " \t\n");
824                 while (*value) {
825                         if (space > 1) {
826                                 string_list_append(g->list,
827                                                    xstrndup(value, space));
828                         }
829                         value += space + (value[space] != '\0');
830                         space = strcspn(value, " \t\n");
831                 }
832         }
834         return 0;
837 static int add_remote_or_group(const char *name, struct string_list *list)
839         int prev_nr = list->nr;
840         struct remote_group_data g;
841         g.name = name; g.list = list;
843         git_config(get_remote_group, &g);
844         if (list->nr == prev_nr) {
845                 struct remote *remote;
846                 if (!remote_is_configured(name))
847                         return 0;
848                 remote = remote_get(name);
849                 string_list_append(list, remote->name);
850         }
851         return 1;
854 static void add_options_to_argv(int *argc, const char **argv)
856         if (dry_run)
857                 argv[(*argc)++] = "--dry-run";
858         if (prune)
859                 argv[(*argc)++] = "--prune";
860         if (update_head_ok)
861                 argv[(*argc)++] = "--update-head-ok";
862         if (force)
863                 argv[(*argc)++] = "--force";
864         if (keep)
865                 argv[(*argc)++] = "--keep";
866         if (recurse_submodules == RECURSE_SUBMODULES_ON)
867                 argv[(*argc)++] = "--recurse-submodules";
868         else if (recurse_submodules == RECURSE_SUBMODULES_ON_DEMAND)
869                 argv[(*argc)++] = "--recurse-submodules=on-demand";
870         if (verbosity >= 2)
871                 argv[(*argc)++] = "-v";
872         if (verbosity >= 1)
873                 argv[(*argc)++] = "-v";
874         else if (verbosity < 0)
875                 argv[(*argc)++] = "-q";
879 static int fetch_multiple(struct string_list *list)
881         int i, result = 0;
882         const char *argv[12] = { "fetch", "--append" };
883         int argc = 2;
885         add_options_to_argv(&argc, argv);
887         if (!append && !dry_run) {
888                 int errcode = truncate_fetch_head();
889                 if (errcode)
890                         return errcode;
891         }
893         for (i = 0; i < list->nr; i++) {
894                 const char *name = list->items[i].string;
895                 argv[argc] = name;
896                 argv[argc + 1] = NULL;
897                 if (verbosity >= 0)
898                         printf(_("Fetching %s\n"), name);
899                 if (run_command_v_opt(argv, RUN_GIT_CMD)) {
900                         error(_("Could not fetch %s"), name);
901                         result = 1;
902                 }
903         }
905         return result;
908 static int fetch_one(struct remote *remote, int argc, const char **argv)
910         int i;
911         static const char **refs = NULL;
912         struct refspec *refspec;
913         int ref_nr = 0;
914         int exit_code;
916         if (!remote)
917                 die(_("No remote repository specified.  Please, specify either a URL or a\n"
918                     "remote name from which new revisions should be fetched."));
920         transport = transport_get(remote, NULL);
921         transport_set_verbosity(transport, verbosity, progress);
922         if (upload_pack)
923                 set_option(TRANS_OPT_UPLOADPACK, upload_pack);
924         if (keep)
925                 set_option(TRANS_OPT_KEEP, "yes");
926         if (depth)
927                 set_option(TRANS_OPT_DEPTH, depth);
929         if (argc > 0) {
930                 int j = 0;
931                 refs = xcalloc(argc + 1, sizeof(const char *));
932                 for (i = 0; i < argc; i++) {
933                         if (!strcmp(argv[i], "tag")) {
934                                 char *ref;
935                                 i++;
936                                 if (i >= argc)
937                                         die(_("You need to specify a tag name."));
938                                 ref = xmalloc(strlen(argv[i]) * 2 + 22);
939                                 strcpy(ref, "refs/tags/");
940                                 strcat(ref, argv[i]);
941                                 strcat(ref, ":refs/tags/");
942                                 strcat(ref, argv[i]);
943                                 refs[j++] = ref;
944                         } else
945                                 refs[j++] = argv[i];
946                 }
947                 refs[j] = NULL;
948                 ref_nr = j;
949         }
951         sigchain_push_common(unlock_pack_on_signal);
952         atexit(unlock_pack);
953         refspec = parse_fetch_refspec(ref_nr, refs);
954         exit_code = do_fetch(transport, refspec, ref_nr);
955         free_refspec(ref_nr, refspec);
956         transport_disconnect(transport);
957         transport = NULL;
958         return exit_code;
961 int cmd_fetch(int argc, const char **argv, const char *prefix)
963         int i;
964         struct string_list list = STRING_LIST_INIT_NODUP;
965         struct remote *remote;
966         int result = 0;
968         packet_trace_identity("fetch");
970         /* Record the command line for the reflog */
971         strbuf_addstr(&default_rla, "fetch");
972         for (i = 1; i < argc; i++)
973                 strbuf_addf(&default_rla, " %s", argv[i]);
975         argc = parse_options(argc, argv, prefix,
976                              builtin_fetch_options, builtin_fetch_usage, 0);
978         if (recurse_submodules != RECURSE_SUBMODULES_OFF) {
979                 if (recurse_submodules_default) {
980                         int arg = parse_fetch_recurse_submodules_arg("--recurse-submodules-default", recurse_submodules_default);
981                         set_config_fetch_recurse_submodules(arg);
982                 }
983                 gitmodules_config();
984                 git_config(submodule_config, NULL);
985         }
987         if (all) {
988                 if (argc == 1)
989                         die(_("fetch --all does not take a repository argument"));
990                 else if (argc > 1)
991                         die(_("fetch --all does not make sense with refspecs"));
992                 (void) for_each_remote(get_one_remote_for_fetch, &list);
993                 result = fetch_multiple(&list);
994         } else if (argc == 0) {
995                 /* No arguments -- use default remote */
996                 remote = remote_get(NULL);
997                 result = fetch_one(remote, argc, argv);
998         } else if (multiple) {
999                 /* All arguments are assumed to be remotes or groups */
1000                 for (i = 0; i < argc; i++)
1001                         if (!add_remote_or_group(argv[i], &list))
1002                                 die(_("No such remote or remote group: %s"), argv[i]);
1003                 result = fetch_multiple(&list);
1004         } else {
1005                 /* Single remote or group */
1006                 (void) add_remote_or_group(argv[0], &list);
1007                 if (list.nr > 1) {
1008                         /* More than one remote */
1009                         if (argc > 1)
1010                                 die(_("Fetching a group and specifying refspecs does not make sense"));
1011                         result = fetch_multiple(&list);
1012                 } else {
1013                         /* Zero or one remotes */
1014                         remote = remote_get(argv[0]);
1015                         result = fetch_one(remote, argc-1, argv+1);
1016                 }
1017         }
1019         if (!result && (recurse_submodules != RECURSE_SUBMODULES_OFF)) {
1020                 const char *options[10];
1021                 int num_options = 0;
1022                 add_options_to_argv(&num_options, options);
1023                 result = fetch_populated_submodules(num_options, options,
1024                                                     submodule_prefix,
1025                                                     recurse_submodules,
1026                                                     verbosity < 0);
1027         }
1029         /* All names were strdup()ed or strndup()ed */
1030         list.strdup_strings = 1;
1031         string_list_clear(&list, 0);
1033         return result;