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