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