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