287cf4ce8b1a794d08e8e5aff0afede2fc000de9
   1/*
   2 * "git fetch"
   3 */
   4#include "cache.h"
   5#include "refs.h"
   6#include "commit.h"
   7#include "builtin.h"
   8#include "string-list.h"
   9#include "remote.h"
  10#include "transport.h"
  11#include "run-command.h"
  12#include "parse-options.h"
  13#include "sigchain.h"
  14#include "transport.h"
  15#include "submodule.h"
  16#include "connected.h"
  17#include "argv-array.h"
  18
  19static const char * const builtin_fetch_usage[] = {
  20        N_("git fetch [<options>] [<repository> [<refspec>...]]"),
  21        N_("git fetch [<options>] <group>"),
  22        N_("git fetch --multiple [<options>] [(<repository> | <group>)...]"),
  23        N_("git fetch --all [<options>]"),
  24        NULL
  25};
  26
  27enum {
  28        TAGS_UNSET = 0,
  29        TAGS_DEFAULT = 1,
  30        TAGS_SET = 2
  31};
  32
  33static int all, append, dry_run, force, keep, multiple, prune, update_head_ok, verbosity;
  34static int progress = -1, recurse_submodules = RECURSE_SUBMODULES_DEFAULT;
  35static int tags = TAGS_DEFAULT, unshallow;
  36static const char *depth;
  37static const char *upload_pack;
  38static struct strbuf default_rla = STRBUF_INIT;
  39static struct transport *transport;
  40static const char *submodule_prefix = "";
  41static const char *recurse_submodules_default;
  42
  43static int option_parse_recurse_submodules(const struct option *opt,
  44                                   const char *arg, int unset)
  45{
  46        if (unset) {
  47                recurse_submodules = RECURSE_SUBMODULES_OFF;
  48        } else {
  49                if (arg)
  50                        recurse_submodules = parse_fetch_recurse_submodules_arg(opt->long_name, arg);
  51                else
  52                        recurse_submodules = RECURSE_SUBMODULES_ON;
  53        }
  54        return 0;
  55}
  56
  57static struct option builtin_fetch_options[] = {
  58        OPT__VERBOSITY(&verbosity),
  59        OPT_BOOLEAN(0, "all", &all,
  60                    N_("fetch from all remotes")),
  61        OPT_BOOLEAN('a', "append", &append,
  62                    N_("append to .git/FETCH_HEAD instead of overwriting")),
  63        OPT_STRING(0, "upload-pack", &upload_pack, N_("path"),
  64                   N_("path to upload pack on remote end")),
  65        OPT__FORCE(&force, N_("force overwrite of local branch")),
  66        OPT_BOOLEAN('m', "multiple", &multiple,
  67                    N_("fetch from multiple remotes")),
  68        OPT_SET_INT('t', "tags", &tags,
  69                    N_("fetch all tags and associated objects"), TAGS_SET),
  70        OPT_SET_INT('n', NULL, &tags,
  71                    N_("do not fetch all tags (--no-tags)"), TAGS_UNSET),
  72        OPT_BOOLEAN('p', "prune", &prune,
  73                    N_("prune remote-tracking branches no longer on remote")),
  74        { OPTION_CALLBACK, 0, "recurse-submodules", NULL, N_("on-demand"),
  75                    N_("control recursive fetching of submodules"),
  76                    PARSE_OPT_OPTARG, option_parse_recurse_submodules },
  77        OPT_BOOLEAN(0, "dry-run", &dry_run,
  78                    N_("dry run")),
  79        OPT_BOOLEAN('k', "keep", &keep, N_("keep downloaded pack")),
  80        OPT_BOOLEAN('u', "update-head-ok", &update_head_ok,
  81                    N_("allow updating of HEAD ref")),
  82        OPT_BOOL(0, "progress", &progress, N_("force progress reporting")),
  83        OPT_STRING(0, "depth", &depth, N_("depth"),
  84                   N_("deepen history of shallow clone")),
  85        { OPTION_SET_INT, 0, "unshallow", &unshallow, NULL,
  86                   N_("convert to a complete repository"),
  87                   PARSE_OPT_NONEG | PARSE_OPT_NOARG, NULL, 1 },
  88        { OPTION_STRING, 0, "submodule-prefix", &submodule_prefix, N_("dir"),
  89                   N_("prepend this to submodule path output"), PARSE_OPT_HIDDEN },
  90        { OPTION_STRING, 0, "recurse-submodules-default",
  91                   &recurse_submodules_default, NULL,
  92                   N_("default mode for recursion"), PARSE_OPT_HIDDEN },
  93        OPT_END()
  94};
  95
  96static void unlock_pack(void)
  97{
  98        if (transport)
  99                transport_unlock_pack(transport);
 100}
 101
 102static void unlock_pack_on_signal(int signo)
 103{
 104        unlock_pack();
 105        sigchain_pop(signo);
 106        raise(signo);
 107}
 108
 109static void add_merge_config(struct ref **head,
 110                           const struct ref *remote_refs,
 111                           struct branch *branch,
 112                           struct ref ***tail)
 113{
 114        int i;
 115
 116        for (i = 0; i < branch->merge_nr; i++) {
 117                struct ref *rm, **old_tail = *tail;
 118                struct refspec refspec;
 119
 120                for (rm = *head; rm; rm = rm->next) {
 121                        if (branch_merge_matches(branch, i, rm->name)) {
 122                                rm->fetch_head_status = FETCH_HEAD_MERGE;
 123                                break;
 124                        }
 125                }
 126                if (rm)
 127                        continue;
 128
 129                /*
 130                 * Not fetched to a remote-tracking branch?  We need to fetch
 131                 * it anyway to allow this branch's "branch.$name.merge"
 132                 * to be honored by 'git pull', but we do not have to
 133                 * fail if branch.$name.merge is misconfigured to point
 134                 * at a nonexisting branch.  If we were indeed called by
 135                 * 'git pull', it will notice the misconfiguration because
 136                 * there is no entry in the resulting FETCH_HEAD marked
 137                 * for merging.
 138                 */
 139                memset(&refspec, 0, sizeof(refspec));
 140                refspec.src = branch->merge[i]->src;
 141                get_fetch_map(remote_refs, &refspec, tail, 1);
 142                for (rm = *old_tail; rm; rm = rm->next)
 143                        rm->fetch_head_status = FETCH_HEAD_MERGE;
 144        }
 145}
 146
 147static void find_non_local_tags(struct transport *transport,
 148                        struct ref **head,
 149                        struct ref ***tail);
 150
 151static struct ref *get_ref_map(struct transport *transport,
 152                               struct refspec *refs, int ref_count, int tags,
 153                               int *autotags)
 154{
 155        int i;
 156        struct ref *rm;
 157        struct ref *ref_map = NULL;
 158        struct ref **tail = &ref_map;
 159
 160        const struct ref *remote_refs = transport_get_remote_refs(transport);
 161
 162        if (ref_count || tags == TAGS_SET) {
 163                for (i = 0; i < ref_count; i++) {
 164                        get_fetch_map(remote_refs, &refs[i], &tail, 0);
 165                        if (refs[i].dst && refs[i].dst[0])
 166                                *autotags = 1;
 167                }
 168                /* Merge everything on the command line, but not --tags */
 169                for (rm = ref_map; rm; rm = rm->next)
 170                        rm->fetch_head_status = FETCH_HEAD_MERGE;
 171                if (tags == TAGS_SET)
 172                        get_fetch_map(remote_refs, tag_refspec, &tail, 0);
 173        } else {
 174                /* Use the defaults */
 175                struct remote *remote = transport->remote;
 176                struct branch *branch = branch_get(NULL);
 177                int has_merge = branch_has_merge_config(branch);
 178                if (remote &&
 179                    (remote->fetch_refspec_nr ||
 180                     /* Note: has_merge implies non-NULL branch->remote_name */
 181                     (has_merge && !strcmp(branch->remote_name, remote->name)))) {
 182                        for (i = 0; i < remote->fetch_refspec_nr; i++) {
 183                                get_fetch_map(remote_refs, &remote->fetch[i], &tail, 0);
 184                                if (remote->fetch[i].dst &&
 185                                    remote->fetch[i].dst[0])
 186                                        *autotags = 1;
 187                                if (!i && !has_merge && ref_map &&
 188                                    !remote->fetch[0].pattern)
 189                                        ref_map->fetch_head_status = FETCH_HEAD_MERGE;
 190                        }
 191                        /*
 192                         * if the remote we're fetching from is the same
 193                         * as given in branch.<name>.remote, we add the
 194                         * ref given in branch.<name>.merge, too.
 195                         *
 196                         * Note: has_merge implies non-NULL branch->remote_name
 197                         */
 198                        if (has_merge &&
 199                            !strcmp(branch->remote_name, remote->name))
 200                                add_merge_config(&ref_map, remote_refs, branch, &tail);
 201                } else {
 202                        ref_map = get_remote_ref(remote_refs, "HEAD");
 203                        if (!ref_map)
 204                                die(_("Couldn't find remote ref HEAD"));
 205                        ref_map->fetch_head_status = FETCH_HEAD_MERGE;
 206                        tail = &ref_map->next;
 207                }
 208        }
 209        if (tags == TAGS_DEFAULT && *autotags)
 210                find_non_local_tags(transport, &ref_map, &tail);
 211        ref_remove_duplicates(ref_map);
 212
 213        return ref_map;
 214}
 215
 216#define STORE_REF_ERROR_OTHER 1
 217#define STORE_REF_ERROR_DF_CONFLICT 2
 218
 219static int s_update_ref(const char *action,
 220                        struct ref *ref,
 221                        int check_old)
 222{
 223        char msg[1024];
 224        char *rla = getenv("GIT_REFLOG_ACTION");
 225        static struct ref_lock *lock;
 226
 227        if (dry_run)
 228                return 0;
 229        if (!rla)
 230                rla = default_rla.buf;
 231        snprintf(msg, sizeof(msg), "%s: %s", rla, action);
 232        lock = lock_any_ref_for_update(ref->name,
 233                                       check_old ? ref->old_sha1 : NULL, 0);
 234        if (!lock)
 235                return errno == ENOTDIR ? STORE_REF_ERROR_DF_CONFLICT :
 236                                          STORE_REF_ERROR_OTHER;
 237        if (write_ref_sha1(lock, ref->new_sha1, msg) < 0)
 238                return errno == ENOTDIR ? STORE_REF_ERROR_DF_CONFLICT :
 239                                          STORE_REF_ERROR_OTHER;
 240        return 0;
 241}
 242
 243#define REFCOL_WIDTH  10
 244
 245static int update_local_ref(struct ref *ref,
 246                            const char *remote,
 247                            const struct ref *remote_ref,
 248                            struct strbuf *display)
 249{
 250        struct commit *current = NULL, *updated;
 251        enum object_type type;
 252        struct branch *current_branch = branch_get(NULL);
 253        const char *pretty_ref = prettify_refname(ref->name);
 254
 255        type = sha1_object_info(ref->new_sha1, NULL);
 256        if (type < 0)
 257                die(_("object %s not found"), sha1_to_hex(ref->new_sha1));
 258
 259        if (!hashcmp(ref->old_sha1, ref->new_sha1)) {
 260                if (verbosity > 0)
 261                        strbuf_addf(display, "= %-*s %-*s -> %s",
 262                                    TRANSPORT_SUMMARY(_("[up to date]")),
 263                                    REFCOL_WIDTH, remote, pretty_ref);
 264                return 0;
 265        }
 266
 267        if (current_branch &&
 268            !strcmp(ref->name, current_branch->name) &&
 269            !(update_head_ok || is_bare_repository()) &&
 270            !is_null_sha1(ref->old_sha1)) {
 271                /*
 272                 * If this is the head, and it's not okay to update
 273                 * the head, and the old value of the head isn't empty...
 274                 */
 275                strbuf_addf(display,
 276                            _("! %-*s %-*s -> %s  (can't fetch in current branch)"),
 277                            TRANSPORT_SUMMARY(_("[rejected]")),
 278                            REFCOL_WIDTH, remote, pretty_ref);
 279                return 1;
 280        }
 281
 282        if (!is_null_sha1(ref->old_sha1) &&
 283            !prefixcmp(ref->name, "refs/tags/")) {
 284                int r;
 285                r = s_update_ref("updating tag", ref, 0);
 286                strbuf_addf(display, "%c %-*s %-*s -> %s%s",
 287                            r ? '!' : '-',
 288                            TRANSPORT_SUMMARY(_("[tag update]")),
 289                            REFCOL_WIDTH, remote, pretty_ref,
 290                            r ? _("  (unable to update local ref)") : "");
 291                return r;
 292        }
 293
 294        current = lookup_commit_reference_gently(ref->old_sha1, 1);
 295        updated = lookup_commit_reference_gently(ref->new_sha1, 1);
 296        if (!current || !updated) {
 297                const char *msg;
 298                const char *what;
 299                int r;
 300                /*
 301                 * Nicely describe the new ref we're fetching.
 302                 * Base this on the remote's ref name, as it's
 303                 * more likely to follow a standard layout.
 304                 */
 305                const char *name = remote_ref ? remote_ref->name : "";
 306                if (!prefixcmp(name, "refs/tags/")) {
 307                        msg = "storing tag";
 308                        what = _("[new tag]");
 309                } else if (!prefixcmp(name, "refs/heads/")) {
 310                        msg = "storing head";
 311                        what = _("[new branch]");
 312                } else {
 313                        msg = "storing ref";
 314                        what = _("[new ref]");
 315                }
 316
 317                if ((recurse_submodules != RECURSE_SUBMODULES_OFF) &&
 318                    (recurse_submodules != RECURSE_SUBMODULES_ON))
 319                        check_for_new_submodule_commits(ref->new_sha1);
 320                r = s_update_ref(msg, ref, 0);
 321                strbuf_addf(display, "%c %-*s %-*s -> %s%s",
 322                            r ? '!' : '*',
 323                            TRANSPORT_SUMMARY(what),
 324                            REFCOL_WIDTH, remote, pretty_ref,
 325                            r ? _("  (unable to update local ref)") : "");
 326                return r;
 327        }
 328
 329        if (in_merge_bases(current, updated)) {
 330                char quickref[83];
 331                int r;
 332                strcpy(quickref, find_unique_abbrev(current->object.sha1, DEFAULT_ABBREV));
 333                strcat(quickref, "..");
 334                strcat(quickref, find_unique_abbrev(ref->new_sha1, DEFAULT_ABBREV));
 335                if ((recurse_submodules != RECURSE_SUBMODULES_OFF) &&
 336                    (recurse_submodules != RECURSE_SUBMODULES_ON))
 337                        check_for_new_submodule_commits(ref->new_sha1);
 338                r = s_update_ref("fast-forward", ref, 1);
 339                strbuf_addf(display, "%c %-*s %-*s -> %s%s",
 340                            r ? '!' : ' ',
 341                            TRANSPORT_SUMMARY_WIDTH, quickref,
 342                            REFCOL_WIDTH, remote, pretty_ref,
 343                            r ? _("  (unable to update local ref)") : "");
 344                return r;
 345        } else if (force || ref->force) {
 346                char quickref[84];
 347                int r;
 348                strcpy(quickref, find_unique_abbrev(current->object.sha1, DEFAULT_ABBREV));
 349                strcat(quickref, "...");
 350                strcat(quickref, find_unique_abbrev(ref->new_sha1, DEFAULT_ABBREV));
 351                if ((recurse_submodules != RECURSE_SUBMODULES_OFF) &&
 352                    (recurse_submodules != RECURSE_SUBMODULES_ON))
 353                        check_for_new_submodule_commits(ref->new_sha1);
 354                r = s_update_ref("forced-update", ref, 1);
 355                strbuf_addf(display, "%c %-*s %-*s -> %s  (%s)",
 356                            r ? '!' : '+',
 357                            TRANSPORT_SUMMARY_WIDTH, quickref,
 358                            REFCOL_WIDTH, remote, pretty_ref,
 359                            r ? _("unable to update local ref") : _("forced update"));
 360                return r;
 361        } else {
 362                strbuf_addf(display, "! %-*s %-*s -> %s  %s",
 363                            TRANSPORT_SUMMARY(_("[rejected]")),
 364                            REFCOL_WIDTH, remote, pretty_ref,
 365                            _("(non-fast-forward)"));
 366                return 1;
 367        }
 368}
 369
 370static int iterate_ref_map(void *cb_data, unsigned char sha1[20])
 371{
 372        struct ref **rm = cb_data;
 373        struct ref *ref = *rm;
 374
 375        if (!ref)
 376                return -1; /* end of the list */
 377        *rm = ref->next;
 378        hashcpy(sha1, ref->old_sha1);
 379        return 0;
 380}
 381
 382static int store_updated_refs(const char *raw_url, const char *remote_name,
 383                struct ref *ref_map)
 384{
 385        FILE *fp;
 386        struct commit *commit;
 387        int url_len, i, shown_url = 0, rc = 0;
 388        struct strbuf note = STRBUF_INIT;
 389        const char *what, *kind;
 390        struct ref *rm;
 391        char *url, *filename = dry_run ? "/dev/null" : git_path("FETCH_HEAD");
 392        int want_status;
 393
 394        fp = fopen(filename, "a");
 395        if (!fp)
 396                return error(_("cannot open %s: %s\n"), filename, strerror(errno));
 397
 398        if (raw_url)
 399                url = transport_anonymize_url(raw_url);
 400        else
 401                url = xstrdup("foreign");
 402
 403        rm = ref_map;
 404        if (check_everything_connected(iterate_ref_map, 0, &rm)) {
 405                rc = error(_("%s did not send all necessary objects\n"), url);
 406                goto abort;
 407        }
 408
 409        /*
 410         * We do a pass for each fetch_head_status type in their enum order, so
 411         * merged entries are written before not-for-merge. That lets readers
 412         * use FETCH_HEAD as a refname to refer to the ref to be merged.
 413         */
 414        for (want_status = FETCH_HEAD_MERGE;
 415             want_status <= FETCH_HEAD_IGNORE;
 416             want_status++) {
 417                for (rm = ref_map; rm; rm = rm->next) {
 418                        struct ref *ref = NULL;
 419                        const char *merge_status_marker = "";
 420
 421                        commit = lookup_commit_reference_gently(rm->old_sha1, 1);
 422                        if (!commit)
 423                                rm->fetch_head_status = FETCH_HEAD_NOT_FOR_MERGE;
 424
 425                        if (rm->fetch_head_status != want_status)
 426                                continue;
 427
 428                        if (rm->peer_ref) {
 429                                ref = xcalloc(1, sizeof(*ref) + strlen(rm->peer_ref->name) + 1);
 430                                strcpy(ref->name, rm->peer_ref->name);
 431                                hashcpy(ref->old_sha1, rm->peer_ref->old_sha1);
 432                                hashcpy(ref->new_sha1, rm->old_sha1);
 433                                ref->force = rm->peer_ref->force;
 434                        }
 435
 436
 437                        if (!strcmp(rm->name, "HEAD")) {
 438                                kind = "";
 439                                what = "";
 440                        }
 441                        else if (!prefixcmp(rm->name, "refs/heads/")) {
 442                                kind = "branch";
 443                                what = rm->name + 11;
 444                        }
 445                        else if (!prefixcmp(rm->name, "refs/tags/")) {
 446                                kind = "tag";
 447                                what = rm->name + 10;
 448                        }
 449                        else if (!prefixcmp(rm->name, "refs/remotes/")) {
 450                                kind = "remote-tracking branch";
 451                                what = rm->name + 13;
 452                        }
 453                        else {
 454                                kind = "";
 455                                what = rm->name;
 456                        }
 457
 458                        url_len = strlen(url);
 459                        for (i = url_len - 1; url[i] == '/' && 0 <= i; i--)
 460                                ;
 461                        url_len = i + 1;
 462                        if (4 < i && !strncmp(".git", url + i - 3, 4))
 463                                url_len = i - 3;
 464
 465                        strbuf_reset(&note);
 466                        if (*what) {
 467                                if (*kind)
 468                                        strbuf_addf(&note, "%s ", kind);
 469                                strbuf_addf(&note, "'%s' of ", what);
 470                        }
 471                        switch (rm->fetch_head_status) {
 472                        case FETCH_HEAD_NOT_FOR_MERGE:
 473                                merge_status_marker = "not-for-merge";
 474                                /* fall-through */
 475                        case FETCH_HEAD_MERGE:
 476                                fprintf(fp, "%s\t%s\t%s",
 477                                        sha1_to_hex(rm->old_sha1),
 478                                        merge_status_marker,
 479                                        note.buf);
 480                                for (i = 0; i < url_len; ++i)
 481                                        if ('\n' == url[i])
 482                                                fputs("\\n", fp);
 483                                        else
 484                                                fputc(url[i], fp);
 485                                fputc('\n', fp);
 486                                break;
 487                        default:
 488                                /* do not write anything to FETCH_HEAD */
 489                                break;
 490                        }
 491
 492                        strbuf_reset(&note);
 493                        if (ref) {
 494                                rc |= update_local_ref(ref, what, rm, &note);
 495                                free(ref);
 496                        } else
 497                                strbuf_addf(&note, "* %-*s %-*s -> FETCH_HEAD",
 498                                            TRANSPORT_SUMMARY_WIDTH,
 499                                            *kind ? kind : "branch",
 500                                            REFCOL_WIDTH,
 501                                            *what ? what : "HEAD");
 502                        if (note.len) {
 503                                if (verbosity >= 0 && !shown_url) {
 504                                        fprintf(stderr, _("From %.*s\n"),
 505                                                        url_len, url);
 506                                        shown_url = 1;
 507                                }
 508                                if (verbosity >= 0)
 509                                        fprintf(stderr, " %s\n", note.buf);
 510                        }
 511                }
 512        }
 513
 514        if (rc & STORE_REF_ERROR_DF_CONFLICT)
 515                error(_("some local refs could not be updated; try running\n"
 516                      " 'git remote prune %s' to remove any old, conflicting "
 517                      "branches"), remote_name);
 518
 519 abort:
 520        strbuf_release(&note);
 521        free(url);
 522        fclose(fp);
 523        return rc;
 524}
 525
 526/*
 527 * We would want to bypass the object transfer altogether if
 528 * everything we are going to fetch already exists and is connected
 529 * locally.
 530 */
 531static int quickfetch(struct ref *ref_map)
 532{
 533        struct ref *rm = ref_map;
 534
 535        /*
 536         * If we are deepening a shallow clone we already have these
 537         * objects reachable.  Running rev-list here will return with
 538         * a good (0) exit status and we'll bypass the fetch that we
 539         * really need to perform.  Claiming failure now will ensure
 540         * we perform the network exchange to deepen our history.
 541         */
 542        if (depth)
 543                return -1;
 544        return check_everything_connected(iterate_ref_map, 1, &rm);
 545}
 546
 547static int fetch_refs(struct transport *transport, struct ref *ref_map)
 548{
 549        int ret = quickfetch(ref_map);
 550        if (ret)
 551                ret = transport_fetch_refs(transport, ref_map);
 552        if (!ret)
 553                ret |= store_updated_refs(transport->url,
 554                                transport->remote->name,
 555                                ref_map);
 556        transport_unlock_pack(transport);
 557        return ret;
 558}
 559
 560static int prune_refs(struct refspec *refs, int ref_count, struct ref *ref_map)
 561{
 562        int result = 0;
 563        struct ref *ref, *stale_refs = get_stale_heads(refs, ref_count, ref_map);
 564        const char *dangling_msg = dry_run
 565                ? _("   (%s will become dangling)")
 566                : _("   (%s has become dangling)");
 567
 568        for (ref = stale_refs; ref; ref = ref->next) {
 569                if (!dry_run)
 570                        result |= delete_ref(ref->name, NULL, 0);
 571                if (verbosity >= 0) {
 572                        fprintf(stderr, " x %-*s %-*s -> %s\n",
 573                                TRANSPORT_SUMMARY(_("[deleted]")),
 574                                REFCOL_WIDTH, _("(none)"), prettify_refname(ref->name));
 575                        warn_dangling_symref(stderr, dangling_msg, ref->name);
 576                }
 577        }
 578        free_refs(stale_refs);
 579        return result;
 580}
 581
 582static int add_existing(const char *refname, const unsigned char *sha1,
 583                        int flag, void *cbdata)
 584{
 585        struct string_list *list = (struct string_list *)cbdata;
 586        struct string_list_item *item = string_list_insert(list, refname);
 587        item->util = (void *)sha1;
 588        return 0;
 589}
 590
 591static int will_fetch(struct ref **head, const unsigned char *sha1)
 592{
 593        struct ref *rm = *head;
 594        while (rm) {
 595                if (!hashcmp(rm->old_sha1, sha1))
 596                        return 1;
 597                rm = rm->next;
 598        }
 599        return 0;
 600}
 601
 602static void find_non_local_tags(struct transport *transport,
 603                        struct ref **head,
 604                        struct ref ***tail)
 605{
 606        struct string_list existing_refs = STRING_LIST_INIT_NODUP;
 607        struct string_list remote_refs = STRING_LIST_INIT_NODUP;
 608        const struct ref *ref;
 609        struct string_list_item *item = NULL;
 610
 611        for_each_ref(add_existing, &existing_refs);
 612        for (ref = transport_get_remote_refs(transport); ref; ref = ref->next) {
 613                if (prefixcmp(ref->name, "refs/tags/"))
 614                        continue;
 615
 616                /*
 617                 * The peeled ref always follows the matching base
 618                 * ref, so if we see a peeled ref that we don't want
 619                 * to fetch then we can mark the ref entry in the list
 620                 * as one to ignore by setting util to NULL.
 621                 */
 622                if (!suffixcmp(ref->name, "^{}")) {
 623                        if (item && !has_sha1_file(ref->old_sha1) &&
 624                            !will_fetch(head, ref->old_sha1) &&
 625                            !has_sha1_file(item->util) &&
 626                            !will_fetch(head, item->util))
 627                                item->util = NULL;
 628                        item = NULL;
 629                        continue;
 630                }
 631
 632                /*
 633                 * If item is non-NULL here, then we previously saw a
 634                 * ref not followed by a peeled reference, so we need
 635                 * to check if it is a lightweight tag that we want to
 636                 * fetch.
 637                 */
 638                if (item && !has_sha1_file(item->util) &&
 639                    !will_fetch(head, item->util))
 640                        item->util = NULL;
 641
 642                item = NULL;
 643
 644                /* skip duplicates and refs that we already have */
 645                if (string_list_has_string(&remote_refs, ref->name) ||
 646                    string_list_has_string(&existing_refs, ref->name))
 647                        continue;
 648
 649                item = string_list_insert(&remote_refs, ref->name);
 650                item->util = (void *)ref->old_sha1;
 651        }
 652        string_list_clear(&existing_refs, 0);
 653
 654        /*
 655         * We may have a final lightweight tag that needs to be
 656         * checked to see if it needs fetching.
 657         */
 658        if (item && !has_sha1_file(item->util) &&
 659            !will_fetch(head, item->util))
 660                item->util = NULL;
 661
 662        /*
 663         * For all the tags in the remote_refs string list,
 664         * add them to the list of refs to be fetched
 665         */
 666        for_each_string_list_item(item, &remote_refs) {
 667                /* Unless we have already decided to ignore this item... */
 668                if (item->util)
 669                {
 670                        struct ref *rm = alloc_ref(item->string);
 671                        rm->peer_ref = alloc_ref(item->string);
 672                        hashcpy(rm->old_sha1, item->util);
 673                        **tail = rm;
 674                        *tail = &rm->next;
 675                }
 676        }
 677
 678        string_list_clear(&remote_refs, 0);
 679}
 680
 681static void check_not_current_branch(struct ref *ref_map)
 682{
 683        struct branch *current_branch = branch_get(NULL);
 684
 685        if (is_bare_repository() || !current_branch)
 686                return;
 687
 688        for (; ref_map; ref_map = ref_map->next)
 689                if (ref_map->peer_ref && !strcmp(current_branch->refname,
 690                                        ref_map->peer_ref->name))
 691                        die(_("Refusing to fetch into current branch %s "
 692                            "of non-bare repository"), current_branch->refname);
 693}
 694
 695static int truncate_fetch_head(void)
 696{
 697        char *filename = git_path("FETCH_HEAD");
 698        FILE *fp = fopen(filename, "w");
 699
 700        if (!fp)
 701                return error(_("cannot open %s: %s\n"), filename, strerror(errno));
 702        fclose(fp);
 703        return 0;
 704}
 705
 706static int do_fetch(struct transport *transport,
 707                    struct refspec *refs, int ref_count)
 708{
 709        struct string_list existing_refs = STRING_LIST_INIT_NODUP;
 710        struct string_list_item *peer_item = NULL;
 711        struct ref *ref_map;
 712        struct ref *rm;
 713        int autotags = (transport->remote->fetch_tags == 1);
 714
 715        for_each_ref(add_existing, &existing_refs);
 716
 717        if (tags == TAGS_DEFAULT) {
 718                if (transport->remote->fetch_tags == 2)
 719                        tags = TAGS_SET;
 720                if (transport->remote->fetch_tags == -1)
 721                        tags = TAGS_UNSET;
 722        }
 723
 724        if (!transport->get_refs_list || !transport->fetch)
 725                die(_("Don't know how to fetch from %s"), transport->url);
 726
 727        /* if not appending, truncate FETCH_HEAD */
 728        if (!append && !dry_run) {
 729                int errcode = truncate_fetch_head();
 730                if (errcode)
 731                        return errcode;
 732        }
 733
 734        ref_map = get_ref_map(transport, refs, ref_count, tags, &autotags);
 735        if (!update_head_ok)
 736                check_not_current_branch(ref_map);
 737
 738        for (rm = ref_map; rm; rm = rm->next) {
 739                if (rm->peer_ref) {
 740                        peer_item = string_list_lookup(&existing_refs,
 741                                                       rm->peer_ref->name);
 742                        if (peer_item)
 743                                hashcpy(rm->peer_ref->old_sha1,
 744                                        peer_item->util);
 745                }
 746        }
 747
 748        if (tags == TAGS_DEFAULT && autotags)
 749                transport_set_option(transport, TRANS_OPT_FOLLOWTAGS, "1");
 750        if (fetch_refs(transport, ref_map)) {
 751                free_refs(ref_map);
 752                return 1;
 753        }
 754        if (prune) {
 755                /* If --tags was specified, pretend the user gave us the canonical tags refspec */
 756                if (tags == TAGS_SET) {
 757                        const char *tags_str = "refs/tags/*:refs/tags/*";
 758                        struct refspec *tags_refspec, *refspec;
 759
 760                        /* Copy the refspec and add the tags to it */
 761                        refspec = xcalloc(ref_count + 1, sizeof(struct refspec));
 762                        tags_refspec = parse_fetch_refspec(1, &tags_str);
 763                        memcpy(refspec, refs, ref_count * sizeof(struct refspec));
 764                        memcpy(&refspec[ref_count], tags_refspec, sizeof(struct refspec));
 765                        ref_count++;
 766
 767                        prune_refs(refspec, ref_count, ref_map);
 768
 769                        ref_count--;
 770                        /* The rest of the strings belong to fetch_one */
 771                        free_refspec(1, tags_refspec);
 772                        free(refspec);
 773                } else if (ref_count) {
 774                        prune_refs(refs, ref_count, ref_map);
 775                } else {
 776                        prune_refs(transport->remote->fetch, transport->remote->fetch_refspec_nr, ref_map);
 777                }
 778        }
 779        free_refs(ref_map);
 780
 781        /* if neither --no-tags nor --tags was specified, do automated tag
 782         * following ... */
 783        if (tags == TAGS_DEFAULT && autotags) {
 784                struct ref **tail = &ref_map;
 785                ref_map = NULL;
 786                find_non_local_tags(transport, &ref_map, &tail);
 787                if (ref_map) {
 788                        transport_set_option(transport, TRANS_OPT_FOLLOWTAGS, NULL);
 789                        transport_set_option(transport, TRANS_OPT_DEPTH, "0");
 790                        fetch_refs(transport, ref_map);
 791                }
 792                free_refs(ref_map);
 793        }
 794
 795        return 0;
 796}
 797
 798static void set_option(const char *name, const char *value)
 799{
 800        int r = transport_set_option(transport, name, value);
 801        if (r < 0)
 802                die(_("Option \"%s\" value \"%s\" is not valid for %s"),
 803                        name, value, transport->url);
 804        if (r > 0)
 805                warning(_("Option \"%s\" is ignored for %s\n"),
 806                        name, transport->url);
 807}
 808
 809static int get_one_remote_for_fetch(struct remote *remote, void *priv)
 810{
 811        struct string_list *list = priv;
 812        if (!remote->skip_default_update)
 813                string_list_append(list, remote->name);
 814        return 0;
 815}
 816
 817struct remote_group_data {
 818        const char *name;
 819        struct string_list *list;
 820};
 821
 822static int get_remote_group(const char *key, const char *value, void *priv)
 823{
 824        struct remote_group_data *g = priv;
 825
 826        if (!prefixcmp(key, "remotes.") &&
 827                        !strcmp(key + 8, g->name)) {
 828                /* split list by white space */
 829                int space = strcspn(value, " \t\n");
 830                while (*value) {
 831                        if (space > 1) {
 832                                string_list_append(g->list,
 833                                                   xstrndup(value, space));
 834                        }
 835                        value += space + (value[space] != '\0');
 836                        space = strcspn(value, " \t\n");
 837                }
 838        }
 839
 840        return 0;
 841}
 842
 843static int add_remote_or_group(const char *name, struct string_list *list)
 844{
 845        int prev_nr = list->nr;
 846        struct remote_group_data g;
 847        g.name = name; g.list = list;
 848
 849        git_config(get_remote_group, &g);
 850        if (list->nr == prev_nr) {
 851                struct remote *remote;
 852                if (!remote_is_configured(name))
 853                        return 0;
 854                remote = remote_get(name);
 855                string_list_append(list, remote->name);
 856        }
 857        return 1;
 858}
 859
 860static void add_options_to_argv(struct argv_array *argv)
 861{
 862        if (dry_run)
 863                argv_array_push(argv, "--dry-run");
 864        if (prune)
 865                argv_array_push(argv, "--prune");
 866        if (update_head_ok)
 867                argv_array_push(argv, "--update-head-ok");
 868        if (force)
 869                argv_array_push(argv, "--force");
 870        if (keep)
 871                argv_array_push(argv, "--keep");
 872        if (recurse_submodules == RECURSE_SUBMODULES_ON)
 873                argv_array_push(argv, "--recurse-submodules");
 874        else if (recurse_submodules == RECURSE_SUBMODULES_ON_DEMAND)
 875                argv_array_push(argv, "--recurse-submodules=on-demand");
 876        if (tags == TAGS_SET)
 877                argv_array_push(argv, "--tags");
 878        else if (tags == TAGS_UNSET)
 879                argv_array_push(argv, "--no-tags");
 880        if (verbosity >= 2)
 881                argv_array_push(argv, "-v");
 882        if (verbosity >= 1)
 883                argv_array_push(argv, "-v");
 884        else if (verbosity < 0)
 885                argv_array_push(argv, "-q");
 886
 887}
 888
 889static int fetch_multiple(struct string_list *list)
 890{
 891        int i, result = 0;
 892        struct argv_array argv = ARGV_ARRAY_INIT;
 893
 894        if (!append && !dry_run) {
 895                int errcode = truncate_fetch_head();
 896                if (errcode)
 897                        return errcode;
 898        }
 899
 900        argv_array_pushl(&argv, "fetch", "--append", NULL);
 901        add_options_to_argv(&argv);
 902
 903        for (i = 0; i < list->nr; i++) {
 904                const char *name = list->items[i].string;
 905                argv_array_push(&argv, name);
 906                if (verbosity >= 0)
 907                        printf(_("Fetching %s\n"), name);
 908                if (run_command_v_opt(argv.argv, RUN_GIT_CMD)) {
 909                        error(_("Could not fetch %s"), name);
 910                        result = 1;
 911                }
 912                argv_array_pop(&argv);
 913        }
 914
 915        argv_array_clear(&argv);
 916        return result;
 917}
 918
 919static int fetch_one(struct remote *remote, int argc, const char **argv)
 920{
 921        int i;
 922        static const char **refs = NULL;
 923        struct refspec *refspec;
 924        int ref_nr = 0;
 925        int exit_code;
 926
 927        if (!remote)
 928                die(_("No remote repository specified.  Please, specify either a URL or a\n"
 929                    "remote name from which new revisions should be fetched."));
 930
 931        transport = transport_get(remote, NULL);
 932        transport_set_verbosity(transport, verbosity, progress);
 933        if (upload_pack)
 934                set_option(TRANS_OPT_UPLOADPACK, upload_pack);
 935        if (keep)
 936                set_option(TRANS_OPT_KEEP, "yes");
 937        if (depth)
 938                set_option(TRANS_OPT_DEPTH, depth);
 939
 940        if (argc > 0) {
 941                int j = 0;
 942                refs = xcalloc(argc + 1, sizeof(const char *));
 943                for (i = 0; i < argc; i++) {
 944                        if (!strcmp(argv[i], "tag")) {
 945                                char *ref;
 946                                i++;
 947                                if (i >= argc)
 948                                        die(_("You need to specify a tag name."));
 949                                ref = xmalloc(strlen(argv[i]) * 2 + 22);
 950                                strcpy(ref, "refs/tags/");
 951                                strcat(ref, argv[i]);
 952                                strcat(ref, ":refs/tags/");
 953                                strcat(ref, argv[i]);
 954                                refs[j++] = ref;
 955                        } else
 956                                refs[j++] = argv[i];
 957                }
 958                refs[j] = NULL;
 959                ref_nr = j;
 960        }
 961
 962        sigchain_push_common(unlock_pack_on_signal);
 963        atexit(unlock_pack);
 964        refspec = parse_fetch_refspec(ref_nr, refs);
 965        exit_code = do_fetch(transport, refspec, ref_nr);
 966        free_refspec(ref_nr, refspec);
 967        transport_disconnect(transport);
 968        transport = NULL;
 969        return exit_code;
 970}
 971
 972int cmd_fetch(int argc, const char **argv, const char *prefix)
 973{
 974        int i;
 975        struct string_list list = STRING_LIST_INIT_NODUP;
 976        struct remote *remote;
 977        int result = 0;
 978        static const char *argv_gc_auto[] = {
 979                "gc", "--auto", NULL,
 980        };
 981
 982        packet_trace_identity("fetch");
 983
 984        /* Record the command line for the reflog */
 985        strbuf_addstr(&default_rla, "fetch");
 986        for (i = 1; i < argc; i++)
 987                strbuf_addf(&default_rla, " %s", argv[i]);
 988
 989        argc = parse_options(argc, argv, prefix,
 990                             builtin_fetch_options, builtin_fetch_usage, 0);
 991
 992        if (unshallow) {
 993                if (depth)
 994                        die(_("--depth and --unshallow cannot be used together"));
 995                else if (!is_repository_shallow())
 996                        die(_("--unshallow on a complete repository does not make sense"));
 997                else {
 998                        static char inf_depth[12];
 999                        sprintf(inf_depth, "%d", INFINITE_DEPTH);
1000                        depth = inf_depth;
1001                }
1002        }
1003
1004        if (recurse_submodules != RECURSE_SUBMODULES_OFF) {
1005                if (recurse_submodules_default) {
1006                        int arg = parse_fetch_recurse_submodules_arg("--recurse-submodules-default", recurse_submodules_default);
1007                        set_config_fetch_recurse_submodules(arg);
1008                }
1009                gitmodules_config();
1010                git_config(submodule_config, NULL);
1011        }
1012
1013        if (all) {
1014                if (argc == 1)
1015                        die(_("fetch --all does not take a repository argument"));
1016                else if (argc > 1)
1017                        die(_("fetch --all does not make sense with refspecs"));
1018                (void) for_each_remote(get_one_remote_for_fetch, &list);
1019                result = fetch_multiple(&list);
1020        } else if (argc == 0) {
1021                /* No arguments -- use default remote */
1022                remote = remote_get(NULL);
1023                result = fetch_one(remote, argc, argv);
1024        } else if (multiple) {
1025                /* All arguments are assumed to be remotes or groups */
1026                for (i = 0; i < argc; i++)
1027                        if (!add_remote_or_group(argv[i], &list))
1028                                die(_("No such remote or remote group: %s"), argv[i]);
1029                result = fetch_multiple(&list);
1030        } else {
1031                /* Single remote or group */
1032                (void) add_remote_or_group(argv[0], &list);
1033                if (list.nr > 1) {
1034                        /* More than one remote */
1035                        if (argc > 1)
1036                                die(_("Fetching a group and specifying refspecs does not make sense"));
1037                        result = fetch_multiple(&list);
1038                } else {
1039                        /* Zero or one remotes */
1040                        remote = remote_get(argv[0]);
1041                        result = fetch_one(remote, argc-1, argv+1);
1042                }
1043        }
1044
1045        if (!result && (recurse_submodules != RECURSE_SUBMODULES_OFF)) {
1046                struct argv_array options = ARGV_ARRAY_INIT;
1047
1048                add_options_to_argv(&options);
1049                result = fetch_populated_submodules(&options,
1050                                                    submodule_prefix,
1051                                                    recurse_submodules,
1052                                                    verbosity < 0);
1053                argv_array_clear(&options);
1054        }
1055
1056        /* All names were strdup()ed or strndup()ed */
1057        list.strdup_strings = 1;
1058        string_list_clear(&list, 0);
1059
1060        run_command_v_opt(argv_gc_auto, RUN_GIT_CMD);
1061
1062        return result;
1063}