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