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