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