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