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