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