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