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