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