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