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