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