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