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