builtin / fetch.con commit fetch: align per-ref summary report in UTF-8 locales (754395d)
   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(_("[up to date]")),
 259                                    REFCOL_WIDTH, remote, pretty_ref);
 260                return 0;
 261        }
 262
 263        if (current_branch &&
 264            !strcmp(ref->name, current_branch->name) &&
 265            !(update_head_ok || is_bare_repository()) &&
 266            !is_null_sha1(ref->old_sha1)) {
 267                /*
 268                 * If this is the head, and it's not okay to update
 269                 * the head, and the old value of the head isn't empty...
 270                 */
 271                strbuf_addf(display,
 272                            _("! %-*s %-*s -> %s  (can't fetch in current branch)"),
 273                            TRANSPORT_SUMMARY(_("[rejected]")),
 274                            REFCOL_WIDTH, remote, pretty_ref);
 275                return 1;
 276        }
 277
 278        if (!is_null_sha1(ref->old_sha1) &&
 279            !prefixcmp(ref->name, "refs/tags/")) {
 280                int r;
 281                r = s_update_ref("updating tag", ref, 0);
 282                strbuf_addf(display, "%c %-*s %-*s -> %s%s",
 283                            r ? '!' : '-',
 284                            TRANSPORT_SUMMARY(_("[tag update]")),
 285                            REFCOL_WIDTH, remote, pretty_ref,
 286                            r ? _("  (unable to update local ref)") : "");
 287                return r;
 288        }
 289
 290        current = lookup_commit_reference_gently(ref->old_sha1, 1);
 291        updated = lookup_commit_reference_gently(ref->new_sha1, 1);
 292        if (!current || !updated) {
 293                const char *msg;
 294                const char *what;
 295                int r;
 296                /*
 297                 * Nicely describe the new ref we're fetching.
 298                 * Base this on the remote's ref name, as it's
 299                 * more likely to follow a standard layout.
 300                 */
 301                const char *name = remote_ref ? remote_ref->name : "";
 302                if (!prefixcmp(name, "refs/tags/")) {
 303                        msg = "storing tag";
 304                        what = _("[new tag]");
 305                } else if (!prefixcmp(name, "refs/heads/")) {
 306                        msg = "storing head";
 307                        what = _("[new branch]");
 308                } else {
 309                        msg = "storing ref";
 310                        what = _("[new ref]");
 311                }
 312
 313                if ((recurse_submodules != RECURSE_SUBMODULES_OFF) &&
 314                    (recurse_submodules != RECURSE_SUBMODULES_ON))
 315                        check_for_new_submodule_commits(ref->new_sha1);
 316                r = s_update_ref(msg, ref, 0);
 317                strbuf_addf(display, "%c %-*s %-*s -> %s%s",
 318                            r ? '!' : '*',
 319                            TRANSPORT_SUMMARY(what),
 320                            REFCOL_WIDTH, remote, pretty_ref,
 321                            r ? _("  (unable to update local ref)") : "");
 322                return r;
 323        }
 324
 325        if (in_merge_bases(current, &updated, 1)) {
 326                char quickref[83];
 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("fast-forward", ref, 1);
 335                strbuf_addf(display, "%c %-*s %-*s -> %s%s",
 336                            r ? '!' : ' ',
 337                            TRANSPORT_SUMMARY_WIDTH, quickref,
 338                            REFCOL_WIDTH, remote, pretty_ref,
 339                            r ? _("  (unable to update local ref)") : "");
 340                return r;
 341        } else if (force || ref->force) {
 342                char quickref[84];
 343                int r;
 344                strcpy(quickref, find_unique_abbrev(current->object.sha1, DEFAULT_ABBREV));
 345                strcat(quickref, "...");
 346                strcat(quickref, find_unique_abbrev(ref->new_sha1, DEFAULT_ABBREV));
 347                if ((recurse_submodules != RECURSE_SUBMODULES_OFF) &&
 348                    (recurse_submodules != RECURSE_SUBMODULES_ON))
 349                        check_for_new_submodule_commits(ref->new_sha1);
 350                r = s_update_ref("forced-update", ref, 1);
 351                strbuf_addf(display, "%c %-*s %-*s -> %s  (%s)",
 352                            r ? '!' : '+',
 353                            TRANSPORT_SUMMARY_WIDTH, quickref,
 354                            REFCOL_WIDTH, remote, pretty_ref,
 355                            r ? _("unable to update local ref") : _("forced update"));
 356                return r;
 357        } else {
 358                strbuf_addf(display, "! %-*s %-*s -> %s  %s",
 359                            TRANSPORT_SUMMARY(_("[rejected]")),
 360                            REFCOL_WIDTH, remote, pretty_ref,
 361                            _("(non-fast-forward)"));
 362                return 1;
 363        }
 364}
 365
 366static int iterate_ref_map(void *cb_data, unsigned char sha1[20])
 367{
 368        struct ref **rm = cb_data;
 369        struct ref *ref = *rm;
 370
 371        if (!ref)
 372                return -1; /* end of the list */
 373        *rm = ref->next;
 374        hashcpy(sha1, ref->old_sha1);
 375        return 0;
 376}
 377
 378static int store_updated_refs(const char *raw_url, const char *remote_name,
 379                struct ref *ref_map)
 380{
 381        FILE *fp;
 382        struct commit *commit;
 383        int url_len, i, shown_url = 0, rc = 0;
 384        struct strbuf note = STRBUF_INIT;
 385        const char *what, *kind;
 386        struct ref *rm;
 387        char *url, *filename = dry_run ? "/dev/null" : git_path("FETCH_HEAD");
 388        int want_merge;
 389
 390        fp = fopen(filename, "a");
 391        if (!fp)
 392                return error(_("cannot open %s: %s\n"), filename, strerror(errno));
 393
 394        if (raw_url)
 395                url = transport_anonymize_url(raw_url);
 396        else
 397                url = xstrdup("foreign");
 398
 399        rm = ref_map;
 400        if (check_everything_connected(iterate_ref_map, 0, &rm)) {
 401                rc = error(_("%s did not send all necessary objects\n"), url);
 402                goto abort;
 403        }
 404
 405        /*
 406         * The first pass writes objects to be merged and then the
 407         * second pass writes the rest, in order to allow using
 408         * FETCH_HEAD as a refname to refer to the ref to be merged.
 409         */
 410        for (want_merge = 1; 0 <= want_merge; want_merge--) {
 411                for (rm = ref_map; rm; rm = rm->next) {
 412                        struct ref *ref = NULL;
 413
 414                        commit = lookup_commit_reference_gently(rm->old_sha1, 1);
 415                        if (!commit)
 416                                rm->merge = 0;
 417
 418                        if (rm->merge != want_merge)
 419                                continue;
 420
 421                        if (rm->peer_ref) {
 422                                ref = xcalloc(1, sizeof(*ref) + strlen(rm->peer_ref->name) + 1);
 423                                strcpy(ref->name, rm->peer_ref->name);
 424                                hashcpy(ref->old_sha1, rm->peer_ref->old_sha1);
 425                                hashcpy(ref->new_sha1, rm->old_sha1);
 426                                ref->force = rm->peer_ref->force;
 427                        }
 428
 429
 430                        if (!strcmp(rm->name, "HEAD")) {
 431                                kind = "";
 432                                what = "";
 433                        }
 434                        else if (!prefixcmp(rm->name, "refs/heads/")) {
 435                                kind = "branch";
 436                                what = rm->name + 11;
 437                        }
 438                        else if (!prefixcmp(rm->name, "refs/tags/")) {
 439                                kind = "tag";
 440                                what = rm->name + 10;
 441                        }
 442                        else if (!prefixcmp(rm->name, "refs/remotes/")) {
 443                                kind = "remote-tracking branch";
 444                                what = rm->name + 13;
 445                        }
 446                        else {
 447                                kind = "";
 448                                what = rm->name;
 449                        }
 450
 451                        url_len = strlen(url);
 452                        for (i = url_len - 1; url[i] == '/' && 0 <= i; i--)
 453                                ;
 454                        url_len = i + 1;
 455                        if (4 < i && !strncmp(".git", url + i - 3, 4))
 456                                url_len = i - 3;
 457
 458                        strbuf_reset(&note);
 459                        if (*what) {
 460                                if (*kind)
 461                                        strbuf_addf(&note, "%s ", kind);
 462                                strbuf_addf(&note, "'%s' of ", what);
 463                        }
 464                        fprintf(fp, "%s\t%s\t%s",
 465                                sha1_to_hex(rm->old_sha1),
 466                                rm->merge ? "" : "not-for-merge",
 467                                note.buf);
 468                        for (i = 0; i < url_len; ++i)
 469                                if ('\n' == url[i])
 470                                        fputs("\\n", fp);
 471                                else
 472                                        fputc(url[i], fp);
 473                        fputc('\n', fp);
 474
 475                        strbuf_reset(&note);
 476                        if (ref) {
 477                                rc |= update_local_ref(ref, what, rm, &note);
 478                                free(ref);
 479                        } else
 480                                strbuf_addf(&note, "* %-*s %-*s -> FETCH_HEAD",
 481                                            TRANSPORT_SUMMARY_WIDTH,
 482                                            *kind ? kind : "branch",
 483                                            REFCOL_WIDTH,
 484                                            *what ? what : "HEAD");
 485                        if (note.len) {
 486                                if (verbosity >= 0 && !shown_url) {
 487                                        fprintf(stderr, _("From %.*s\n"),
 488                                                        url_len, url);
 489                                        shown_url = 1;
 490                                }
 491                                if (verbosity >= 0)
 492                                        fprintf(stderr, " %s\n", note.buf);
 493                        }
 494                }
 495        }
 496
 497        if (rc & STORE_REF_ERROR_DF_CONFLICT)
 498                error(_("some local refs could not be updated; try running\n"
 499                      " 'git remote prune %s' to remove any old, conflicting "
 500                      "branches"), remote_name);
 501
 502 abort:
 503        strbuf_release(&note);
 504        free(url);
 505        fclose(fp);
 506        return rc;
 507}
 508
 509/*
 510 * We would want to bypass the object transfer altogether if
 511 * everything we are going to fetch already exists and is connected
 512 * locally.
 513 */
 514static int quickfetch(struct ref *ref_map)
 515{
 516        struct ref *rm = ref_map;
 517
 518        /*
 519         * If we are deepening a shallow clone we already have these
 520         * objects reachable.  Running rev-list here will return with
 521         * a good (0) exit status and we'll bypass the fetch that we
 522         * really need to perform.  Claiming failure now will ensure
 523         * we perform the network exchange to deepen our history.
 524         */
 525        if (depth)
 526                return -1;
 527        return check_everything_connected(iterate_ref_map, 1, &rm);
 528}
 529
 530static int fetch_refs(struct transport *transport, struct ref *ref_map)
 531{
 532        int ret = quickfetch(ref_map);
 533        if (ret)
 534                ret = transport_fetch_refs(transport, ref_map);
 535        if (!ret)
 536                ret |= store_updated_refs(transport->url,
 537                                transport->remote->name,
 538                                ref_map);
 539        transport_unlock_pack(transport);
 540        return ret;
 541}
 542
 543static int prune_refs(struct refspec *refs, int ref_count, struct ref *ref_map)
 544{
 545        int result = 0;
 546        struct ref *ref, *stale_refs = get_stale_heads(refs, ref_count, ref_map);
 547        const char *dangling_msg = dry_run
 548                ? _("   (%s will become dangling)")
 549                : _("   (%s has become dangling)");
 550
 551        for (ref = stale_refs; ref; ref = ref->next) {
 552                if (!dry_run)
 553                        result |= delete_ref(ref->name, NULL, 0);
 554                if (verbosity >= 0) {
 555                        fprintf(stderr, " x %-*s %-*s -> %s\n",
 556                                TRANSPORT_SUMMARY(_("[deleted]")),
 557                                REFCOL_WIDTH, _("(none)"), prettify_refname(ref->name));
 558                        warn_dangling_symref(stderr, dangling_msg, ref->name);
 559                }
 560        }
 561        free_refs(stale_refs);
 562        return result;
 563}
 564
 565static int add_existing(const char *refname, const unsigned char *sha1,
 566                        int flag, void *cbdata)
 567{
 568        struct string_list *list = (struct string_list *)cbdata;
 569        struct string_list_item *item = string_list_insert(list, refname);
 570        item->util = (void *)sha1;
 571        return 0;
 572}
 573
 574static int will_fetch(struct ref **head, const unsigned char *sha1)
 575{
 576        struct ref *rm = *head;
 577        while (rm) {
 578                if (!hashcmp(rm->old_sha1, sha1))
 579                        return 1;
 580                rm = rm->next;
 581        }
 582        return 0;
 583}
 584
 585static void find_non_local_tags(struct transport *transport,
 586                        struct ref **head,
 587                        struct ref ***tail)
 588{
 589        struct string_list existing_refs = STRING_LIST_INIT_NODUP;
 590        struct string_list remote_refs = STRING_LIST_INIT_NODUP;
 591        const struct ref *ref;
 592        struct string_list_item *item = NULL;
 593
 594        for_each_ref(add_existing, &existing_refs);
 595        for (ref = transport_get_remote_refs(transport); ref; ref = ref->next) {
 596                if (prefixcmp(ref->name, "refs/tags/"))
 597                        continue;
 598
 599                /*
 600                 * The peeled ref always follows the matching base
 601                 * ref, so if we see a peeled ref that we don't want
 602                 * to fetch then we can mark the ref entry in the list
 603                 * as one to ignore by setting util to NULL.
 604                 */
 605                if (!suffixcmp(ref->name, "^{}")) {
 606                        if (item && !has_sha1_file(ref->old_sha1) &&
 607                            !will_fetch(head, ref->old_sha1) &&
 608                            !has_sha1_file(item->util) &&
 609                            !will_fetch(head, item->util))
 610                                item->util = NULL;
 611                        item = NULL;
 612                        continue;
 613                }
 614
 615                /*
 616                 * If item is non-NULL here, then we previously saw a
 617                 * ref not followed by a peeled reference, so we need
 618                 * to check if it is a lightweight tag that we want to
 619                 * fetch.
 620                 */
 621                if (item && !has_sha1_file(item->util) &&
 622                    !will_fetch(head, item->util))
 623                        item->util = NULL;
 624
 625                item = NULL;
 626
 627                /* skip duplicates and refs that we already have */
 628                if (string_list_has_string(&remote_refs, ref->name) ||
 629                    string_list_has_string(&existing_refs, ref->name))
 630                        continue;
 631
 632                item = string_list_insert(&remote_refs, ref->name);
 633                item->util = (void *)ref->old_sha1;
 634        }
 635        string_list_clear(&existing_refs, 0);
 636
 637        /*
 638         * We may have a final lightweight tag that needs to be
 639         * checked to see if it needs fetching.
 640         */
 641        if (item && !has_sha1_file(item->util) &&
 642            !will_fetch(head, item->util))
 643                item->util = NULL;
 644
 645        /*
 646         * For all the tags in the remote_refs string list,
 647         * add them to the list of refs to be fetched
 648         */
 649        for_each_string_list_item(item, &remote_refs) {
 650                /* Unless we have already decided to ignore this item... */
 651                if (item->util)
 652                {
 653                        struct ref *rm = alloc_ref(item->string);
 654                        rm->peer_ref = alloc_ref(item->string);
 655                        hashcpy(rm->old_sha1, item->util);
 656                        **tail = rm;
 657                        *tail = &rm->next;
 658                }
 659        }
 660
 661        string_list_clear(&remote_refs, 0);
 662}
 663
 664static void check_not_current_branch(struct ref *ref_map)
 665{
 666        struct branch *current_branch = branch_get(NULL);
 667
 668        if (is_bare_repository() || !current_branch)
 669                return;
 670
 671        for (; ref_map; ref_map = ref_map->next)
 672                if (ref_map->peer_ref && !strcmp(current_branch->refname,
 673                                        ref_map->peer_ref->name))
 674                        die(_("Refusing to fetch into current branch %s "
 675                            "of non-bare repository"), current_branch->refname);
 676}
 677
 678static int truncate_fetch_head(void)
 679{
 680        char *filename = git_path("FETCH_HEAD");
 681        FILE *fp = fopen(filename, "w");
 682
 683        if (!fp)
 684                return error(_("cannot open %s: %s\n"), filename, strerror(errno));
 685        fclose(fp);
 686        return 0;
 687}
 688
 689static int do_fetch(struct transport *transport,
 690                    struct refspec *refs, int ref_count)
 691{
 692        struct string_list existing_refs = STRING_LIST_INIT_NODUP;
 693        struct string_list_item *peer_item = NULL;
 694        struct ref *ref_map;
 695        struct ref *rm;
 696        int autotags = (transport->remote->fetch_tags == 1);
 697
 698        for_each_ref(add_existing, &existing_refs);
 699
 700        if (tags == TAGS_DEFAULT) {
 701                if (transport->remote->fetch_tags == 2)
 702                        tags = TAGS_SET;
 703                if (transport->remote->fetch_tags == -1)
 704                        tags = TAGS_UNSET;
 705        }
 706
 707        if (!transport->get_refs_list || !transport->fetch)
 708                die(_("Don't know how to fetch from %s"), transport->url);
 709
 710        /* if not appending, truncate FETCH_HEAD */
 711        if (!append && !dry_run) {
 712                int errcode = truncate_fetch_head();
 713                if (errcode)
 714                        return errcode;
 715        }
 716
 717        ref_map = get_ref_map(transport, refs, ref_count, tags, &autotags);
 718        if (!update_head_ok)
 719                check_not_current_branch(ref_map);
 720
 721        for (rm = ref_map; rm; rm = rm->next) {
 722                if (rm->peer_ref) {
 723                        peer_item = string_list_lookup(&existing_refs,
 724                                                       rm->peer_ref->name);
 725                        if (peer_item)
 726                                hashcpy(rm->peer_ref->old_sha1,
 727                                        peer_item->util);
 728                }
 729        }
 730
 731        if (tags == TAGS_DEFAULT && autotags)
 732                transport_set_option(transport, TRANS_OPT_FOLLOWTAGS, "1");
 733        if (fetch_refs(transport, ref_map)) {
 734                free_refs(ref_map);
 735                return 1;
 736        }
 737        if (prune) {
 738                /* If --tags was specified, pretend the user gave us the canonical tags refspec */
 739                if (tags == TAGS_SET) {
 740                        const char *tags_str = "refs/tags/*:refs/tags/*";
 741                        struct refspec *tags_refspec, *refspec;
 742
 743                        /* Copy the refspec and add the tags to it */
 744                        refspec = xcalloc(ref_count + 1, sizeof(struct refspec));
 745                        tags_refspec = parse_fetch_refspec(1, &tags_str);
 746                        memcpy(refspec, refs, ref_count * sizeof(struct refspec));
 747                        memcpy(&refspec[ref_count], tags_refspec, sizeof(struct refspec));
 748                        ref_count++;
 749
 750                        prune_refs(refspec, ref_count, ref_map);
 751
 752                        ref_count--;
 753                        /* The rest of the strings belong to fetch_one */
 754                        free_refspec(1, tags_refspec);
 755                        free(refspec);
 756                } else if (ref_count) {
 757                        prune_refs(refs, ref_count, ref_map);
 758                } else {
 759                        prune_refs(transport->remote->fetch, transport->remote->fetch_refspec_nr, ref_map);
 760                }
 761        }
 762        free_refs(ref_map);
 763
 764        /* if neither --no-tags nor --tags was specified, do automated tag
 765         * following ... */
 766        if (tags == TAGS_DEFAULT && autotags) {
 767                struct ref **tail = &ref_map;
 768                ref_map = NULL;
 769                find_non_local_tags(transport, &ref_map, &tail);
 770                if (ref_map) {
 771                        transport_set_option(transport, TRANS_OPT_FOLLOWTAGS, NULL);
 772                        transport_set_option(transport, TRANS_OPT_DEPTH, "0");
 773                        fetch_refs(transport, ref_map);
 774                }
 775                free_refs(ref_map);
 776        }
 777
 778        return 0;
 779}
 780
 781static void set_option(const char *name, const char *value)
 782{
 783        int r = transport_set_option(transport, name, value);
 784        if (r < 0)
 785                die(_("Option \"%s\" value \"%s\" is not valid for %s"),
 786                        name, value, transport->url);
 787        if (r > 0)
 788                warning(_("Option \"%s\" is ignored for %s\n"),
 789                        name, transport->url);
 790}
 791
 792static int get_one_remote_for_fetch(struct remote *remote, void *priv)
 793{
 794        struct string_list *list = priv;
 795        if (!remote->skip_default_update)
 796                string_list_append(list, remote->name);
 797        return 0;
 798}
 799
 800struct remote_group_data {
 801        const char *name;
 802        struct string_list *list;
 803};
 804
 805static int get_remote_group(const char *key, const char *value, void *priv)
 806{
 807        struct remote_group_data *g = priv;
 808
 809        if (!prefixcmp(key, "remotes.") &&
 810                        !strcmp(key + 8, g->name)) {
 811                /* split list by white space */
 812                int space = strcspn(value, " \t\n");
 813                while (*value) {
 814                        if (space > 1) {
 815                                string_list_append(g->list,
 816                                                   xstrndup(value, space));
 817                        }
 818                        value += space + (value[space] != '\0');
 819                        space = strcspn(value, " \t\n");
 820                }
 821        }
 822
 823        return 0;
 824}
 825
 826static int add_remote_or_group(const char *name, struct string_list *list)
 827{
 828        int prev_nr = list->nr;
 829        struct remote_group_data g;
 830        g.name = name; g.list = list;
 831
 832        git_config(get_remote_group, &g);
 833        if (list->nr == prev_nr) {
 834                struct remote *remote;
 835                if (!remote_is_configured(name))
 836                        return 0;
 837                remote = remote_get(name);
 838                string_list_append(list, remote->name);
 839        }
 840        return 1;
 841}
 842
 843static void add_options_to_argv(int *argc, const char **argv)
 844{
 845        if (dry_run)
 846                argv[(*argc)++] = "--dry-run";
 847        if (prune)
 848                argv[(*argc)++] = "--prune";
 849        if (update_head_ok)
 850                argv[(*argc)++] = "--update-head-ok";
 851        if (force)
 852                argv[(*argc)++] = "--force";
 853        if (keep)
 854                argv[(*argc)++] = "--keep";
 855        if (recurse_submodules == RECURSE_SUBMODULES_ON)
 856                argv[(*argc)++] = "--recurse-submodules";
 857        else if (recurse_submodules == RECURSE_SUBMODULES_ON_DEMAND)
 858                argv[(*argc)++] = "--recurse-submodules=on-demand";
 859        if (verbosity >= 2)
 860                argv[(*argc)++] = "-v";
 861        if (verbosity >= 1)
 862                argv[(*argc)++] = "-v";
 863        else if (verbosity < 0)
 864                argv[(*argc)++] = "-q";
 865
 866}
 867
 868static int fetch_multiple(struct string_list *list)
 869{
 870        int i, result = 0;
 871        const char *argv[12] = { "fetch", "--append" };
 872        int argc = 2;
 873
 874        add_options_to_argv(&argc, argv);
 875
 876        if (!append && !dry_run) {
 877                int errcode = truncate_fetch_head();
 878                if (errcode)
 879                        return errcode;
 880        }
 881
 882        for (i = 0; i < list->nr; i++) {
 883                const char *name = list->items[i].string;
 884                argv[argc] = name;
 885                argv[argc + 1] = NULL;
 886                if (verbosity >= 0)
 887                        printf(_("Fetching %s\n"), name);
 888                if (run_command_v_opt(argv, RUN_GIT_CMD)) {
 889                        error(_("Could not fetch %s"), name);
 890                        result = 1;
 891                }
 892        }
 893
 894        return result;
 895}
 896
 897static int fetch_one(struct remote *remote, int argc, const char **argv)
 898{
 899        int i;
 900        static const char **refs = NULL;
 901        struct refspec *refspec;
 902        int ref_nr = 0;
 903        int exit_code;
 904
 905        if (!remote)
 906                die(_("No remote repository specified.  Please, specify either a URL or a\n"
 907                    "remote name from which new revisions should be fetched."));
 908
 909        transport = transport_get(remote, NULL);
 910        transport_set_verbosity(transport, verbosity, progress);
 911        if (upload_pack)
 912                set_option(TRANS_OPT_UPLOADPACK, upload_pack);
 913        if (keep)
 914                set_option(TRANS_OPT_KEEP, "yes");
 915        if (depth)
 916                set_option(TRANS_OPT_DEPTH, depth);
 917
 918        if (argc > 0) {
 919                int j = 0;
 920                refs = xcalloc(argc + 1, sizeof(const char *));
 921                for (i = 0; i < argc; i++) {
 922                        if (!strcmp(argv[i], "tag")) {
 923                                char *ref;
 924                                i++;
 925                                if (i >= argc)
 926                                        die(_("You need to specify a tag name."));
 927                                ref = xmalloc(strlen(argv[i]) * 2 + 22);
 928                                strcpy(ref, "refs/tags/");
 929                                strcat(ref, argv[i]);
 930                                strcat(ref, ":refs/tags/");
 931                                strcat(ref, argv[i]);
 932                                refs[j++] = ref;
 933                        } else
 934                                refs[j++] = argv[i];
 935                }
 936                refs[j] = NULL;
 937                ref_nr = j;
 938        }
 939
 940        sigchain_push_common(unlock_pack_on_signal);
 941        atexit(unlock_pack);
 942        refspec = parse_fetch_refspec(ref_nr, refs);
 943        exit_code = do_fetch(transport, refspec, ref_nr);
 944        free_refspec(ref_nr, refspec);
 945        transport_disconnect(transport);
 946        transport = NULL;
 947        return exit_code;
 948}
 949
 950int cmd_fetch(int argc, const char **argv, const char *prefix)
 951{
 952        int i;
 953        struct string_list list = STRING_LIST_INIT_NODUP;
 954        struct remote *remote;
 955        int result = 0;
 956
 957        packet_trace_identity("fetch");
 958
 959        /* Record the command line for the reflog */
 960        strbuf_addstr(&default_rla, "fetch");
 961        for (i = 1; i < argc; i++)
 962                strbuf_addf(&default_rla, " %s", argv[i]);
 963
 964        argc = parse_options(argc, argv, prefix,
 965                             builtin_fetch_options, builtin_fetch_usage, 0);
 966
 967        if (recurse_submodules != RECURSE_SUBMODULES_OFF) {
 968                if (recurse_submodules_default) {
 969                        int arg = parse_fetch_recurse_submodules_arg("--recurse-submodules-default", recurse_submodules_default);
 970                        set_config_fetch_recurse_submodules(arg);
 971                }
 972                gitmodules_config();
 973                git_config(submodule_config, NULL);
 974        }
 975
 976        if (all) {
 977                if (argc == 1)
 978                        die(_("fetch --all does not take a repository argument"));
 979                else if (argc > 1)
 980                        die(_("fetch --all does not make sense with refspecs"));
 981                (void) for_each_remote(get_one_remote_for_fetch, &list);
 982                result = fetch_multiple(&list);
 983        } else if (argc == 0) {
 984                /* No arguments -- use default remote */
 985                remote = remote_get(NULL);
 986                result = fetch_one(remote, argc, argv);
 987        } else if (multiple) {
 988                /* All arguments are assumed to be remotes or groups */
 989                for (i = 0; i < argc; i++)
 990                        if (!add_remote_or_group(argv[i], &list))
 991                                die(_("No such remote or remote group: %s"), argv[i]);
 992                result = fetch_multiple(&list);
 993        } else {
 994                /* Single remote or group */
 995                (void) add_remote_or_group(argv[0], &list);
 996                if (list.nr > 1) {
 997                        /* More than one remote */
 998                        if (argc > 1)
 999                                die(_("Fetching a group and specifying refspecs does not make sense"));
1000                        result = fetch_multiple(&list);
1001                } else {
1002                        /* Zero or one remotes */
1003                        remote = remote_get(argv[0]);
1004                        result = fetch_one(remote, argc-1, argv+1);
1005                }
1006        }
1007
1008        if (!result && (recurse_submodules != RECURSE_SUBMODULES_OFF)) {
1009                const char *options[10];
1010                int num_options = 0;
1011                add_options_to_argv(&num_options, options);
1012                result = fetch_populated_submodules(num_options, options,
1013                                                    submodule_prefix,
1014                                                    recurse_submodules,
1015                                                    verbosity < 0);
1016        }
1017
1018        /* All names were strdup()ed or strndup()ed */
1019        list.strdup_strings = 1;
1020        string_list_clear(&list, 0);
1021
1022        return result;
1023}