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