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