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