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