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