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