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