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