builtin / submodule--helper.con commit unpack-trees: don't respect submodule.update (7463e2e)
   1#include "builtin.h"
   2#include "repository.h"
   3#include "cache.h"
   4#include "config.h"
   5#include "parse-options.h"
   6#include "quote.h"
   7#include "pathspec.h"
   8#include "dir.h"
   9#include "submodule.h"
  10#include "submodule-config.h"
  11#include "string-list.h"
  12#include "run-command.h"
  13#include "remote.h"
  14#include "refs.h"
  15#include "connect.h"
  16
  17static char *get_default_remote(void)
  18{
  19        char *dest = NULL, *ret;
  20        unsigned char sha1[20];
  21        struct strbuf sb = STRBUF_INIT;
  22        const char *refname = resolve_ref_unsafe("HEAD", 0, sha1, NULL);
  23
  24        if (!refname)
  25                die(_("No such ref: %s"), "HEAD");
  26
  27        /* detached HEAD */
  28        if (!strcmp(refname, "HEAD"))
  29                return xstrdup("origin");
  30
  31        if (!skip_prefix(refname, "refs/heads/", &refname))
  32                die(_("Expecting a full ref name, got %s"), refname);
  33
  34        strbuf_addf(&sb, "branch.%s.remote", refname);
  35        if (git_config_get_string(sb.buf, &dest))
  36                ret = xstrdup("origin");
  37        else
  38                ret = dest;
  39
  40        strbuf_release(&sb);
  41        return ret;
  42}
  43
  44static int starts_with_dot_slash(const char *str)
  45{
  46        return str[0] == '.' && is_dir_sep(str[1]);
  47}
  48
  49static int starts_with_dot_dot_slash(const char *str)
  50{
  51        return str[0] == '.' && str[1] == '.' && is_dir_sep(str[2]);
  52}
  53
  54/*
  55 * Returns 1 if it was the last chop before ':'.
  56 */
  57static int chop_last_dir(char **remoteurl, int is_relative)
  58{
  59        char *rfind = find_last_dir_sep(*remoteurl);
  60        if (rfind) {
  61                *rfind = '\0';
  62                return 0;
  63        }
  64
  65        rfind = strrchr(*remoteurl, ':');
  66        if (rfind) {
  67                *rfind = '\0';
  68                return 1;
  69        }
  70
  71        if (is_relative || !strcmp(".", *remoteurl))
  72                die(_("cannot strip one component off url '%s'"),
  73                        *remoteurl);
  74
  75        free(*remoteurl);
  76        *remoteurl = xstrdup(".");
  77        return 0;
  78}
  79
  80/*
  81 * The `url` argument is the URL that navigates to the submodule origin
  82 * repo. When relative, this URL is relative to the superproject origin
  83 * URL repo. The `up_path` argument, if specified, is the relative
  84 * path that navigates from the submodule working tree to the superproject
  85 * working tree. Returns the origin URL of the submodule.
  86 *
  87 * Return either an absolute URL or filesystem path (if the superproject
  88 * origin URL is an absolute URL or filesystem path, respectively) or a
  89 * relative file system path (if the superproject origin URL is a relative
  90 * file system path).
  91 *
  92 * When the output is a relative file system path, the path is either
  93 * relative to the submodule working tree, if up_path is specified, or to
  94 * the superproject working tree otherwise.
  95 *
  96 * NEEDSWORK: This works incorrectly on the domain and protocol part.
  97 * remote_url      url              outcome          expectation
  98 * http://a.com/b  ../c             http://a.com/c   as is
  99 * http://a.com/b/ ../c             http://a.com/c   same as previous line, but
 100 *                                                   ignore trailing slash in url
 101 * http://a.com/b  ../../c          http://c         error out
 102 * http://a.com/b  ../../../c       http:/c          error out
 103 * http://a.com/b  ../../../../c    http:c           error out
 104 * http://a.com/b  ../../../../../c    .:c           error out
 105 * NEEDSWORK: Given how chop_last_dir() works, this function is broken
 106 * when a local part has a colon in its path component, too.
 107 */
 108static char *relative_url(const char *remote_url,
 109                                const char *url,
 110                                const char *up_path)
 111{
 112        int is_relative = 0;
 113        int colonsep = 0;
 114        char *out;
 115        char *remoteurl = xstrdup(remote_url);
 116        struct strbuf sb = STRBUF_INIT;
 117        size_t len = strlen(remoteurl);
 118
 119        if (is_dir_sep(remoteurl[len-1]))
 120                remoteurl[len-1] = '\0';
 121
 122        if (!url_is_local_not_ssh(remoteurl) || is_absolute_path(remoteurl))
 123                is_relative = 0;
 124        else {
 125                is_relative = 1;
 126                /*
 127                 * Prepend a './' to ensure all relative
 128                 * remoteurls start with './' or '../'
 129                 */
 130                if (!starts_with_dot_slash(remoteurl) &&
 131                    !starts_with_dot_dot_slash(remoteurl)) {
 132                        strbuf_reset(&sb);
 133                        strbuf_addf(&sb, "./%s", remoteurl);
 134                        free(remoteurl);
 135                        remoteurl = strbuf_detach(&sb, NULL);
 136                }
 137        }
 138        /*
 139         * When the url starts with '../', remove that and the
 140         * last directory in remoteurl.
 141         */
 142        while (url) {
 143                if (starts_with_dot_dot_slash(url)) {
 144                        url += 3;
 145                        colonsep |= chop_last_dir(&remoteurl, is_relative);
 146                } else if (starts_with_dot_slash(url))
 147                        url += 2;
 148                else
 149                        break;
 150        }
 151        strbuf_reset(&sb);
 152        strbuf_addf(&sb, "%s%s%s", remoteurl, colonsep ? ":" : "/", url);
 153        if (ends_with(url, "/"))
 154                strbuf_setlen(&sb, sb.len - 1);
 155        free(remoteurl);
 156
 157        if (starts_with_dot_slash(sb.buf))
 158                out = xstrdup(sb.buf + 2);
 159        else
 160                out = xstrdup(sb.buf);
 161        strbuf_reset(&sb);
 162
 163        if (!up_path || !is_relative)
 164                return out;
 165
 166        strbuf_addf(&sb, "%s%s", up_path, out);
 167        free(out);
 168        return strbuf_detach(&sb, NULL);
 169}
 170
 171static int resolve_relative_url(int argc, const char **argv, const char *prefix)
 172{
 173        char *remoteurl = NULL;
 174        char *remote = get_default_remote();
 175        const char *up_path = NULL;
 176        char *res;
 177        const char *url;
 178        struct strbuf sb = STRBUF_INIT;
 179
 180        if (argc != 2 && argc != 3)
 181                die("resolve-relative-url only accepts one or two arguments");
 182
 183        url = argv[1];
 184        strbuf_addf(&sb, "remote.%s.url", remote);
 185        free(remote);
 186
 187        if (git_config_get_string(sb.buf, &remoteurl))
 188                /* the repository is its own authoritative upstream */
 189                remoteurl = xgetcwd();
 190
 191        if (argc == 3)
 192                up_path = argv[2];
 193
 194        res = relative_url(remoteurl, url, up_path);
 195        puts(res);
 196        free(res);
 197        free(remoteurl);
 198        return 0;
 199}
 200
 201static int resolve_relative_url_test(int argc, const char **argv, const char *prefix)
 202{
 203        char *remoteurl, *res;
 204        const char *up_path, *url;
 205
 206        if (argc != 4)
 207                die("resolve-relative-url-test only accepts three arguments: <up_path> <remoteurl> <url>");
 208
 209        up_path = argv[1];
 210        remoteurl = xstrdup(argv[2]);
 211        url = argv[3];
 212
 213        if (!strcmp(up_path, "(null)"))
 214                up_path = NULL;
 215
 216        res = relative_url(remoteurl, url, up_path);
 217        puts(res);
 218        free(res);
 219        free(remoteurl);
 220        return 0;
 221}
 222
 223struct module_list {
 224        const struct cache_entry **entries;
 225        int alloc, nr;
 226};
 227#define MODULE_LIST_INIT { NULL, 0, 0 }
 228
 229static int module_list_compute(int argc, const char **argv,
 230                               const char *prefix,
 231                               struct pathspec *pathspec,
 232                               struct module_list *list)
 233{
 234        int i, result = 0;
 235        char *ps_matched = NULL;
 236        parse_pathspec(pathspec, 0,
 237                       PATHSPEC_PREFER_FULL,
 238                       prefix, argv);
 239
 240        if (pathspec->nr)
 241                ps_matched = xcalloc(pathspec->nr, 1);
 242
 243        if (read_cache() < 0)
 244                die(_("index file corrupt"));
 245
 246        for (i = 0; i < active_nr; i++) {
 247                const struct cache_entry *ce = active_cache[i];
 248
 249                if (!match_pathspec(pathspec, ce->name, ce_namelen(ce),
 250                                    0, ps_matched, 1) ||
 251                    !S_ISGITLINK(ce->ce_mode))
 252                        continue;
 253
 254                ALLOC_GROW(list->entries, list->nr + 1, list->alloc);
 255                list->entries[list->nr++] = ce;
 256                while (i + 1 < active_nr &&
 257                       !strcmp(ce->name, active_cache[i + 1]->name))
 258                        /*
 259                         * Skip entries with the same name in different stages
 260                         * to make sure an entry is returned only once.
 261                         */
 262                        i++;
 263        }
 264
 265        if (ps_matched && report_path_error(ps_matched, pathspec, prefix))
 266                result = -1;
 267
 268        free(ps_matched);
 269
 270        return result;
 271}
 272
 273static void module_list_active(struct module_list *list)
 274{
 275        int i;
 276        struct module_list active_modules = MODULE_LIST_INIT;
 277
 278        gitmodules_config();
 279
 280        for (i = 0; i < list->nr; i++) {
 281                const struct cache_entry *ce = list->entries[i];
 282
 283                if (!is_submodule_active(the_repository, ce->name))
 284                        continue;
 285
 286                ALLOC_GROW(active_modules.entries,
 287                           active_modules.nr + 1,
 288                           active_modules.alloc);
 289                active_modules.entries[active_modules.nr++] = ce;
 290        }
 291
 292        free(list->entries);
 293        *list = active_modules;
 294}
 295
 296static int module_list(int argc, const char **argv, const char *prefix)
 297{
 298        int i;
 299        struct pathspec pathspec;
 300        struct module_list list = MODULE_LIST_INIT;
 301
 302        struct option module_list_options[] = {
 303                OPT_STRING(0, "prefix", &prefix,
 304                           N_("path"),
 305                           N_("alternative anchor for relative paths")),
 306                OPT_END()
 307        };
 308
 309        const char *const git_submodule_helper_usage[] = {
 310                N_("git submodule--helper list [--prefix=<path>] [<path>...]"),
 311                NULL
 312        };
 313
 314        argc = parse_options(argc, argv, prefix, module_list_options,
 315                             git_submodule_helper_usage, 0);
 316
 317        if (module_list_compute(argc, argv, prefix, &pathspec, &list) < 0)
 318                return 1;
 319
 320        for (i = 0; i < list.nr; i++) {
 321                const struct cache_entry *ce = list.entries[i];
 322
 323                if (ce_stage(ce))
 324                        printf("%06o %s U\t", ce->ce_mode, sha1_to_hex(null_sha1));
 325                else
 326                        printf("%06o %s %d\t", ce->ce_mode,
 327                               oid_to_hex(&ce->oid), ce_stage(ce));
 328
 329                fprintf(stdout, "%s\n", ce->name);
 330        }
 331        return 0;
 332}
 333
 334static void init_submodule(const char *path, const char *prefix, int quiet)
 335{
 336        const struct submodule *sub;
 337        struct strbuf sb = STRBUF_INIT;
 338        char *upd = NULL, *url = NULL, *displaypath;
 339
 340        /* Only loads from .gitmodules, no overlay with .git/config */
 341        gitmodules_config();
 342
 343        if (prefix && get_super_prefix())
 344                die("BUG: cannot have prefix and superprefix");
 345        else if (prefix)
 346                displaypath = xstrdup(relative_path(path, prefix, &sb));
 347        else if (get_super_prefix()) {
 348                strbuf_addf(&sb, "%s%s", get_super_prefix(), path);
 349                displaypath = strbuf_detach(&sb, NULL);
 350        } else
 351                displaypath = xstrdup(path);
 352
 353        sub = submodule_from_path(&null_oid, path);
 354
 355        if (!sub)
 356                die(_("No url found for submodule path '%s' in .gitmodules"),
 357                        displaypath);
 358
 359        /*
 360         * NEEDSWORK: In a multi-working-tree world, this needs to be
 361         * set in the per-worktree config.
 362         *
 363         * Set active flag for the submodule being initialized
 364         */
 365        if (!is_submodule_active(the_repository, path)) {
 366                strbuf_reset(&sb);
 367                strbuf_addf(&sb, "submodule.%s.active", sub->name);
 368                git_config_set_gently(sb.buf, "true");
 369        }
 370
 371        /*
 372         * Copy url setting when it is not set yet.
 373         * To look up the url in .git/config, we must not fall back to
 374         * .gitmodules, so look it up directly.
 375         */
 376        strbuf_reset(&sb);
 377        strbuf_addf(&sb, "submodule.%s.url", sub->name);
 378        if (git_config_get_string(sb.buf, &url)) {
 379                if (!sub->url)
 380                        die(_("No url found for submodule path '%s' in .gitmodules"),
 381                                displaypath);
 382
 383                url = xstrdup(sub->url);
 384
 385                /* Possibly a url relative to parent */
 386                if (starts_with_dot_dot_slash(url) ||
 387                    starts_with_dot_slash(url)) {
 388                        char *remoteurl, *relurl;
 389                        char *remote = get_default_remote();
 390                        struct strbuf remotesb = STRBUF_INIT;
 391                        strbuf_addf(&remotesb, "remote.%s.url", remote);
 392                        free(remote);
 393
 394                        if (git_config_get_string(remotesb.buf, &remoteurl)) {
 395                                warning(_("could not lookup configuration '%s'. Assuming this repository is its own authoritative upstream."), remotesb.buf);
 396                                remoteurl = xgetcwd();
 397                        }
 398                        relurl = relative_url(remoteurl, url, NULL);
 399                        strbuf_release(&remotesb);
 400                        free(remoteurl);
 401                        free(url);
 402                        url = relurl;
 403                }
 404
 405                if (git_config_set_gently(sb.buf, url))
 406                        die(_("Failed to register url for submodule path '%s'"),
 407                            displaypath);
 408                if (!quiet)
 409                        fprintf(stderr,
 410                                _("Submodule '%s' (%s) registered for path '%s'\n"),
 411                                sub->name, url, displaypath);
 412        }
 413
 414        /* Copy "update" setting when it is not set yet */
 415        strbuf_reset(&sb);
 416        strbuf_addf(&sb, "submodule.%s.update", sub->name);
 417        if (git_config_get_string(sb.buf, &upd) &&
 418            sub->update_strategy.type != SM_UPDATE_UNSPECIFIED) {
 419                if (sub->update_strategy.type == SM_UPDATE_COMMAND) {
 420                        fprintf(stderr, _("warning: command update mode suggested for submodule '%s'\n"),
 421                                sub->name);
 422                        upd = xstrdup("none");
 423                } else
 424                        upd = xstrdup(submodule_strategy_to_string(&sub->update_strategy));
 425
 426                if (git_config_set_gently(sb.buf, upd))
 427                        die(_("Failed to register update mode for submodule path '%s'"), displaypath);
 428        }
 429        strbuf_release(&sb);
 430        free(displaypath);
 431        free(url);
 432        free(upd);
 433}
 434
 435static int module_init(int argc, const char **argv, const char *prefix)
 436{
 437        struct pathspec pathspec;
 438        struct module_list list = MODULE_LIST_INIT;
 439        int quiet = 0;
 440        int i;
 441
 442        struct option module_init_options[] = {
 443                OPT__QUIET(&quiet, N_("Suppress output for initializing a submodule")),
 444                OPT_END()
 445        };
 446
 447        const char *const git_submodule_helper_usage[] = {
 448                N_("git submodule--helper init [<path>]"),
 449                NULL
 450        };
 451
 452        argc = parse_options(argc, argv, prefix, module_init_options,
 453                             git_submodule_helper_usage, 0);
 454
 455        if (module_list_compute(argc, argv, prefix, &pathspec, &list) < 0)
 456                return 1;
 457
 458        /*
 459         * If there are no path args and submodule.active is set then,
 460         * by default, only initialize 'active' modules.
 461         */
 462        if (!argc && git_config_get_value_multi("submodule.active"))
 463                module_list_active(&list);
 464
 465        for (i = 0; i < list.nr; i++)
 466                init_submodule(list.entries[i]->name, prefix, quiet);
 467
 468        return 0;
 469}
 470
 471static int module_name(int argc, const char **argv, const char *prefix)
 472{
 473        const struct submodule *sub;
 474
 475        if (argc != 2)
 476                usage(_("git submodule--helper name <path>"));
 477
 478        gitmodules_config();
 479        sub = submodule_from_path(&null_oid, argv[1]);
 480
 481        if (!sub)
 482                die(_("no submodule mapping found in .gitmodules for path '%s'"),
 483                    argv[1]);
 484
 485        printf("%s\n", sub->name);
 486
 487        return 0;
 488}
 489
 490static int clone_submodule(const char *path, const char *gitdir, const char *url,
 491                           const char *depth, struct string_list *reference,
 492                           int quiet, int progress)
 493{
 494        struct child_process cp = CHILD_PROCESS_INIT;
 495
 496        argv_array_push(&cp.args, "clone");
 497        argv_array_push(&cp.args, "--no-checkout");
 498        if (quiet)
 499                argv_array_push(&cp.args, "--quiet");
 500        if (progress)
 501                argv_array_push(&cp.args, "--progress");
 502        if (depth && *depth)
 503                argv_array_pushl(&cp.args, "--depth", depth, NULL);
 504        if (reference->nr) {
 505                struct string_list_item *item;
 506                for_each_string_list_item(item, reference)
 507                        argv_array_pushl(&cp.args, "--reference",
 508                                         item->string, NULL);
 509        }
 510        if (gitdir && *gitdir)
 511                argv_array_pushl(&cp.args, "--separate-git-dir", gitdir, NULL);
 512
 513        argv_array_push(&cp.args, url);
 514        argv_array_push(&cp.args, path);
 515
 516        cp.git_cmd = 1;
 517        prepare_submodule_repo_env(&cp.env_array);
 518        cp.no_stdin = 1;
 519
 520        return run_command(&cp);
 521}
 522
 523struct submodule_alternate_setup {
 524        const char *submodule_name;
 525        enum SUBMODULE_ALTERNATE_ERROR_MODE {
 526                SUBMODULE_ALTERNATE_ERROR_DIE,
 527                SUBMODULE_ALTERNATE_ERROR_INFO,
 528                SUBMODULE_ALTERNATE_ERROR_IGNORE
 529        } error_mode;
 530        struct string_list *reference;
 531};
 532#define SUBMODULE_ALTERNATE_SETUP_INIT { NULL, \
 533        SUBMODULE_ALTERNATE_ERROR_IGNORE, NULL }
 534
 535static int add_possible_reference_from_superproject(
 536                struct alternate_object_database *alt, void *sas_cb)
 537{
 538        struct submodule_alternate_setup *sas = sas_cb;
 539
 540        /*
 541         * If the alternate object store is another repository, try the
 542         * standard layout with .git/(modules/<name>)+/objects
 543         */
 544        if (ends_with(alt->path, "/objects")) {
 545                char *sm_alternate;
 546                struct strbuf sb = STRBUF_INIT;
 547                struct strbuf err = STRBUF_INIT;
 548                strbuf_add(&sb, alt->path, strlen(alt->path) - strlen("objects"));
 549
 550                /*
 551                 * We need to end the new path with '/' to mark it as a dir,
 552                 * otherwise a submodule name containing '/' will be broken
 553                 * as the last part of a missing submodule reference would
 554                 * be taken as a file name.
 555                 */
 556                strbuf_addf(&sb, "modules/%s/", sas->submodule_name);
 557
 558                sm_alternate = compute_alternate_path(sb.buf, &err);
 559                if (sm_alternate) {
 560                        string_list_append(sas->reference, xstrdup(sb.buf));
 561                        free(sm_alternate);
 562                } else {
 563                        switch (sas->error_mode) {
 564                        case SUBMODULE_ALTERNATE_ERROR_DIE:
 565                                die(_("submodule '%s' cannot add alternate: %s"),
 566                                    sas->submodule_name, err.buf);
 567                        case SUBMODULE_ALTERNATE_ERROR_INFO:
 568                                fprintf(stderr, _("submodule '%s' cannot add alternate: %s"),
 569                                        sas->submodule_name, err.buf);
 570                        case SUBMODULE_ALTERNATE_ERROR_IGNORE:
 571                                ; /* nothing */
 572                        }
 573                }
 574                strbuf_release(&sb);
 575        }
 576
 577        return 0;
 578}
 579
 580static void prepare_possible_alternates(const char *sm_name,
 581                struct string_list *reference)
 582{
 583        char *sm_alternate = NULL, *error_strategy = NULL;
 584        struct submodule_alternate_setup sas = SUBMODULE_ALTERNATE_SETUP_INIT;
 585
 586        git_config_get_string("submodule.alternateLocation", &sm_alternate);
 587        if (!sm_alternate)
 588                return;
 589
 590        git_config_get_string("submodule.alternateErrorStrategy", &error_strategy);
 591
 592        if (!error_strategy)
 593                error_strategy = xstrdup("die");
 594
 595        sas.submodule_name = sm_name;
 596        sas.reference = reference;
 597        if (!strcmp(error_strategy, "die"))
 598                sas.error_mode = SUBMODULE_ALTERNATE_ERROR_DIE;
 599        else if (!strcmp(error_strategy, "info"))
 600                sas.error_mode = SUBMODULE_ALTERNATE_ERROR_INFO;
 601        else if (!strcmp(error_strategy, "ignore"))
 602                sas.error_mode = SUBMODULE_ALTERNATE_ERROR_IGNORE;
 603        else
 604                die(_("Value '%s' for submodule.alternateErrorStrategy is not recognized"), error_strategy);
 605
 606        if (!strcmp(sm_alternate, "superproject"))
 607                foreach_alt_odb(add_possible_reference_from_superproject, &sas);
 608        else if (!strcmp(sm_alternate, "no"))
 609                ; /* do nothing */
 610        else
 611                die(_("Value '%s' for submodule.alternateLocation is not recognized"), sm_alternate);
 612
 613        free(sm_alternate);
 614        free(error_strategy);
 615}
 616
 617static int module_clone(int argc, const char **argv, const char *prefix)
 618{
 619        const char *name = NULL, *url = NULL, *depth = NULL;
 620        int quiet = 0;
 621        int progress = 0;
 622        char *p, *path = NULL, *sm_gitdir;
 623        struct strbuf sb = STRBUF_INIT;
 624        struct string_list reference = STRING_LIST_INIT_NODUP;
 625        char *sm_alternate = NULL, *error_strategy = NULL;
 626
 627        struct option module_clone_options[] = {
 628                OPT_STRING(0, "prefix", &prefix,
 629                           N_("path"),
 630                           N_("alternative anchor for relative paths")),
 631                OPT_STRING(0, "path", &path,
 632                           N_("path"),
 633                           N_("where the new submodule will be cloned to")),
 634                OPT_STRING(0, "name", &name,
 635                           N_("string"),
 636                           N_("name of the new submodule")),
 637                OPT_STRING(0, "url", &url,
 638                           N_("string"),
 639                           N_("url where to clone the submodule from")),
 640                OPT_STRING_LIST(0, "reference", &reference,
 641                           N_("repo"),
 642                           N_("reference repository")),
 643                OPT_STRING(0, "depth", &depth,
 644                           N_("string"),
 645                           N_("depth for shallow clones")),
 646                OPT__QUIET(&quiet, "Suppress output for cloning a submodule"),
 647                OPT_BOOL(0, "progress", &progress,
 648                           N_("force cloning progress")),
 649                OPT_END()
 650        };
 651
 652        const char *const git_submodule_helper_usage[] = {
 653                N_("git submodule--helper clone [--prefix=<path>] [--quiet] "
 654                   "[--reference <repository>] [--name <name>] [--depth <depth>] "
 655                   "--url <url> --path <path>"),
 656                NULL
 657        };
 658
 659        argc = parse_options(argc, argv, prefix, module_clone_options,
 660                             git_submodule_helper_usage, 0);
 661
 662        if (argc || !url || !path || !*path)
 663                usage_with_options(git_submodule_helper_usage,
 664                                   module_clone_options);
 665
 666        strbuf_addf(&sb, "%s/modules/%s", get_git_dir(), name);
 667        sm_gitdir = absolute_pathdup(sb.buf);
 668        strbuf_reset(&sb);
 669
 670        if (!is_absolute_path(path)) {
 671                strbuf_addf(&sb, "%s/%s", get_git_work_tree(), path);
 672                path = strbuf_detach(&sb, NULL);
 673        } else
 674                path = xstrdup(path);
 675
 676        if (!file_exists(sm_gitdir)) {
 677                if (safe_create_leading_directories_const(sm_gitdir) < 0)
 678                        die(_("could not create directory '%s'"), sm_gitdir);
 679
 680                prepare_possible_alternates(name, &reference);
 681
 682                if (clone_submodule(path, sm_gitdir, url, depth, &reference,
 683                                    quiet, progress))
 684                        die(_("clone of '%s' into submodule path '%s' failed"),
 685                            url, path);
 686        } else {
 687                if (safe_create_leading_directories_const(path) < 0)
 688                        die(_("could not create directory '%s'"), path);
 689                strbuf_addf(&sb, "%s/index", sm_gitdir);
 690                unlink_or_warn(sb.buf);
 691                strbuf_reset(&sb);
 692        }
 693
 694        /* Connect module worktree and git dir */
 695        connect_work_tree_and_git_dir(path, sm_gitdir);
 696
 697        p = git_pathdup_submodule(path, "config");
 698        if (!p)
 699                die(_("could not get submodule directory for '%s'"), path);
 700
 701        /* setup alternateLocation and alternateErrorStrategy in the cloned submodule if needed */
 702        git_config_get_string("submodule.alternateLocation", &sm_alternate);
 703        if (sm_alternate)
 704                git_config_set_in_file(p, "submodule.alternateLocation",
 705                                           sm_alternate);
 706        git_config_get_string("submodule.alternateErrorStrategy", &error_strategy);
 707        if (error_strategy)
 708                git_config_set_in_file(p, "submodule.alternateErrorStrategy",
 709                                           error_strategy);
 710
 711        free(sm_alternate);
 712        free(error_strategy);
 713
 714        strbuf_release(&sb);
 715        free(sm_gitdir);
 716        free(path);
 717        free(p);
 718        return 0;
 719}
 720
 721struct submodule_update_clone {
 722        /* index into 'list', the list of submodules to look into for cloning */
 723        int current;
 724        struct module_list list;
 725        unsigned warn_if_uninitialized : 1;
 726
 727        /* update parameter passed via commandline */
 728        struct submodule_update_strategy update;
 729
 730        /* configuration parameters which are passed on to the children */
 731        int progress;
 732        int quiet;
 733        int recommend_shallow;
 734        struct string_list references;
 735        const char *depth;
 736        const char *recursive_prefix;
 737        const char *prefix;
 738
 739        /* Machine-readable status lines to be consumed by git-submodule.sh */
 740        struct string_list projectlines;
 741
 742        /* If we want to stop as fast as possible and return an error */
 743        unsigned quickstop : 1;
 744
 745        /* failed clones to be retried again */
 746        const struct cache_entry **failed_clones;
 747        int failed_clones_nr, failed_clones_alloc;
 748};
 749#define SUBMODULE_UPDATE_CLONE_INIT {0, MODULE_LIST_INIT, 0, \
 750        SUBMODULE_UPDATE_STRATEGY_INIT, 0, 0, -1, STRING_LIST_INIT_DUP, \
 751        NULL, NULL, NULL, \
 752        STRING_LIST_INIT_DUP, 0, NULL, 0, 0}
 753
 754
 755static void next_submodule_warn_missing(struct submodule_update_clone *suc,
 756                struct strbuf *out, const char *displaypath)
 757{
 758        /*
 759         * Only mention uninitialized submodules when their
 760         * paths have been specified.
 761         */
 762        if (suc->warn_if_uninitialized) {
 763                strbuf_addf(out,
 764                        _("Submodule path '%s' not initialized"),
 765                        displaypath);
 766                strbuf_addch(out, '\n');
 767                strbuf_addstr(out,
 768                        _("Maybe you want to use 'update --init'?"));
 769                strbuf_addch(out, '\n');
 770        }
 771}
 772
 773/**
 774 * Determine whether 'ce' needs to be cloned. If so, prepare the 'child' to
 775 * run the clone. Returns 1 if 'ce' needs to be cloned, 0 otherwise.
 776 */
 777static int prepare_to_clone_next_submodule(const struct cache_entry *ce,
 778                                           struct child_process *child,
 779                                           struct submodule_update_clone *suc,
 780                                           struct strbuf *out)
 781{
 782        const struct submodule *sub = NULL;
 783        const char *url = NULL;
 784        const char *update_string;
 785        enum submodule_update_type update_type;
 786        char *key;
 787        struct strbuf displaypath_sb = STRBUF_INIT;
 788        struct strbuf sb = STRBUF_INIT;
 789        const char *displaypath = NULL;
 790        int needs_cloning = 0;
 791
 792        if (ce_stage(ce)) {
 793                if (suc->recursive_prefix)
 794                        strbuf_addf(&sb, "%s/%s", suc->recursive_prefix, ce->name);
 795                else
 796                        strbuf_addstr(&sb, ce->name);
 797                strbuf_addf(out, _("Skipping unmerged submodule %s"), sb.buf);
 798                strbuf_addch(out, '\n');
 799                goto cleanup;
 800        }
 801
 802        sub = submodule_from_path(&null_oid, ce->name);
 803
 804        if (suc->recursive_prefix)
 805                displaypath = relative_path(suc->recursive_prefix,
 806                                            ce->name, &displaypath_sb);
 807        else
 808                displaypath = ce->name;
 809
 810        if (!sub) {
 811                next_submodule_warn_missing(suc, out, displaypath);
 812                goto cleanup;
 813        }
 814
 815        key = xstrfmt("submodule.%s.update", sub->name);
 816        if (!repo_config_get_string_const(the_repository, key, &update_string)) {
 817                update_type = parse_submodule_update_type(update_string);
 818        } else {
 819                update_type = sub->update_strategy.type;
 820        }
 821        free(key);
 822
 823        if (suc->update.type == SM_UPDATE_NONE
 824            || (suc->update.type == SM_UPDATE_UNSPECIFIED
 825                && update_type == SM_UPDATE_NONE)) {
 826                strbuf_addf(out, _("Skipping submodule '%s'"), displaypath);
 827                strbuf_addch(out, '\n');
 828                goto cleanup;
 829        }
 830
 831        /* Check if the submodule has been initialized. */
 832        if (!is_submodule_active(the_repository, ce->name)) {
 833                next_submodule_warn_missing(suc, out, displaypath);
 834                goto cleanup;
 835        }
 836
 837        strbuf_reset(&sb);
 838        strbuf_addf(&sb, "submodule.%s.url", sub->name);
 839        if (repo_config_get_string_const(the_repository, sb.buf, &url))
 840                url = sub->url;
 841
 842        strbuf_reset(&sb);
 843        strbuf_addf(&sb, "%s/.git", ce->name);
 844        needs_cloning = !file_exists(sb.buf);
 845
 846        strbuf_reset(&sb);
 847        strbuf_addf(&sb, "%06o %s %d %d\t%s\n", ce->ce_mode,
 848                        oid_to_hex(&ce->oid), ce_stage(ce),
 849                        needs_cloning, ce->name);
 850        string_list_append(&suc->projectlines, sb.buf);
 851
 852        if (!needs_cloning)
 853                goto cleanup;
 854
 855        child->git_cmd = 1;
 856        child->no_stdin = 1;
 857        child->stdout_to_stderr = 1;
 858        child->err = -1;
 859        argv_array_push(&child->args, "submodule--helper");
 860        argv_array_push(&child->args, "clone");
 861        if (suc->progress)
 862                argv_array_push(&child->args, "--progress");
 863        if (suc->quiet)
 864                argv_array_push(&child->args, "--quiet");
 865        if (suc->prefix)
 866                argv_array_pushl(&child->args, "--prefix", suc->prefix, NULL);
 867        if (suc->recommend_shallow && sub->recommend_shallow == 1)
 868                argv_array_push(&child->args, "--depth=1");
 869        argv_array_pushl(&child->args, "--path", sub->path, NULL);
 870        argv_array_pushl(&child->args, "--name", sub->name, NULL);
 871        argv_array_pushl(&child->args, "--url", url, NULL);
 872        if (suc->references.nr) {
 873                struct string_list_item *item;
 874                for_each_string_list_item(item, &suc->references)
 875                        argv_array_pushl(&child->args, "--reference", item->string, NULL);
 876        }
 877        if (suc->depth)
 878                argv_array_push(&child->args, suc->depth);
 879
 880cleanup:
 881        strbuf_reset(&displaypath_sb);
 882        strbuf_reset(&sb);
 883
 884        return needs_cloning;
 885}
 886
 887static int update_clone_get_next_task(struct child_process *child,
 888                                      struct strbuf *err,
 889                                      void *suc_cb,
 890                                      void **idx_task_cb)
 891{
 892        struct submodule_update_clone *suc = suc_cb;
 893        const struct cache_entry *ce;
 894        int index;
 895
 896        for (; suc->current < suc->list.nr; suc->current++) {
 897                ce = suc->list.entries[suc->current];
 898                if (prepare_to_clone_next_submodule(ce, child, suc, err)) {
 899                        int *p = xmalloc(sizeof(*p));
 900                        *p = suc->current;
 901                        *idx_task_cb = p;
 902                        suc->current++;
 903                        return 1;
 904                }
 905        }
 906
 907        /*
 908         * The loop above tried cloning each submodule once, now try the
 909         * stragglers again, which we can imagine as an extension of the
 910         * entry list.
 911         */
 912        index = suc->current - suc->list.nr;
 913        if (index < suc->failed_clones_nr) {
 914                int *p;
 915                ce = suc->failed_clones[index];
 916                if (!prepare_to_clone_next_submodule(ce, child, suc, err)) {
 917                        suc->current ++;
 918                        strbuf_addstr(err, "BUG: submodule considered for "
 919                                           "cloning, doesn't need cloning "
 920                                           "any more?\n");
 921                        return 0;
 922                }
 923                p = xmalloc(sizeof(*p));
 924                *p = suc->current;
 925                *idx_task_cb = p;
 926                suc->current ++;
 927                return 1;
 928        }
 929
 930        return 0;
 931}
 932
 933static int update_clone_start_failure(struct strbuf *err,
 934                                      void *suc_cb,
 935                                      void *idx_task_cb)
 936{
 937        struct submodule_update_clone *suc = suc_cb;
 938        suc->quickstop = 1;
 939        return 1;
 940}
 941
 942static int update_clone_task_finished(int result,
 943                                      struct strbuf *err,
 944                                      void *suc_cb,
 945                                      void *idx_task_cb)
 946{
 947        const struct cache_entry *ce;
 948        struct submodule_update_clone *suc = suc_cb;
 949
 950        int *idxP = *(int**)idx_task_cb;
 951        int idx = *idxP;
 952        free(idxP);
 953
 954        if (!result)
 955                return 0;
 956
 957        if (idx < suc->list.nr) {
 958                ce  = suc->list.entries[idx];
 959                strbuf_addf(err, _("Failed to clone '%s'. Retry scheduled"),
 960                            ce->name);
 961                strbuf_addch(err, '\n');
 962                ALLOC_GROW(suc->failed_clones,
 963                           suc->failed_clones_nr + 1,
 964                           suc->failed_clones_alloc);
 965                suc->failed_clones[suc->failed_clones_nr++] = ce;
 966                return 0;
 967        } else {
 968                idx -= suc->list.nr;
 969                ce  = suc->failed_clones[idx];
 970                strbuf_addf(err, _("Failed to clone '%s' a second time, aborting"),
 971                            ce->name);
 972                strbuf_addch(err, '\n');
 973                suc->quickstop = 1;
 974                return 1;
 975        }
 976
 977        return 0;
 978}
 979
 980static int gitmodules_update_clone_config(const char *var, const char *value,
 981                                          void *cb)
 982{
 983        int *max_jobs = cb;
 984        if (!strcmp(var, "submodule.fetchjobs"))
 985                *max_jobs = parse_submodule_fetchjobs(var, value);
 986        return 0;
 987}
 988
 989static int update_clone(int argc, const char **argv, const char *prefix)
 990{
 991        const char *update = NULL;
 992        int max_jobs = 1;
 993        struct string_list_item *item;
 994        struct pathspec pathspec;
 995        struct submodule_update_clone suc = SUBMODULE_UPDATE_CLONE_INIT;
 996
 997        struct option module_update_clone_options[] = {
 998                OPT_STRING(0, "prefix", &prefix,
 999                           N_("path"),
1000                           N_("path into the working tree")),
1001                OPT_STRING(0, "recursive-prefix", &suc.recursive_prefix,
1002                           N_("path"),
1003                           N_("path into the working tree, across nested "
1004                              "submodule boundaries")),
1005                OPT_STRING(0, "update", &update,
1006                           N_("string"),
1007                           N_("rebase, merge, checkout or none")),
1008                OPT_STRING_LIST(0, "reference", &suc.references, N_("repo"),
1009                           N_("reference repository")),
1010                OPT_STRING(0, "depth", &suc.depth, "<depth>",
1011                           N_("Create a shallow clone truncated to the "
1012                              "specified number of revisions")),
1013                OPT_INTEGER('j', "jobs", &max_jobs,
1014                            N_("parallel jobs")),
1015                OPT_BOOL(0, "recommend-shallow", &suc.recommend_shallow,
1016                            N_("whether the initial clone should follow the shallow recommendation")),
1017                OPT__QUIET(&suc.quiet, N_("don't print cloning progress")),
1018                OPT_BOOL(0, "progress", &suc.progress,
1019                            N_("force cloning progress")),
1020                OPT_END()
1021        };
1022
1023        const char *const git_submodule_helper_usage[] = {
1024                N_("git submodule--helper update_clone [--prefix=<path>] [<path>...]"),
1025                NULL
1026        };
1027        suc.prefix = prefix;
1028
1029        config_from_gitmodules(gitmodules_update_clone_config, &max_jobs);
1030        git_config(gitmodules_update_clone_config, &max_jobs);
1031
1032        argc = parse_options(argc, argv, prefix, module_update_clone_options,
1033                             git_submodule_helper_usage, 0);
1034
1035        if (update)
1036                if (parse_submodule_update_strategy(update, &suc.update) < 0)
1037                        die(_("bad value for update parameter"));
1038
1039        if (module_list_compute(argc, argv, prefix, &pathspec, &suc.list) < 0)
1040                return 1;
1041
1042        if (pathspec.nr)
1043                suc.warn_if_uninitialized = 1;
1044
1045        gitmodules_config();
1046
1047        run_processes_parallel(max_jobs,
1048                               update_clone_get_next_task,
1049                               update_clone_start_failure,
1050                               update_clone_task_finished,
1051                               &suc);
1052
1053        /*
1054         * We saved the output and put it out all at once now.
1055         * That means:
1056         * - the listener does not have to interleave their (checkout)
1057         *   work with our fetching.  The writes involved in a
1058         *   checkout involve more straightforward sequential I/O.
1059         * - the listener can avoid doing any work if fetching failed.
1060         */
1061        if (suc.quickstop)
1062                return 1;
1063
1064        for_each_string_list_item(item, &suc.projectlines)
1065                fprintf(stdout, "%s", item->string);
1066
1067        return 0;
1068}
1069
1070static int resolve_relative_path(int argc, const char **argv, const char *prefix)
1071{
1072        struct strbuf sb = STRBUF_INIT;
1073        if (argc != 3)
1074                die("submodule--helper relative-path takes exactly 2 arguments, got %d", argc);
1075
1076        printf("%s", relative_path(argv[1], argv[2], &sb));
1077        strbuf_release(&sb);
1078        return 0;
1079}
1080
1081static const char *remote_submodule_branch(const char *path)
1082{
1083        const struct submodule *sub;
1084        const char *branch = NULL;
1085        char *key;
1086
1087        gitmodules_config();
1088
1089        sub = submodule_from_path(&null_oid, path);
1090        if (!sub)
1091                return NULL;
1092
1093        key = xstrfmt("submodule.%s.branch", sub->name);
1094        if (repo_config_get_string_const(the_repository, key, &branch))
1095                branch = sub->branch;
1096        free(key);
1097
1098        if (!branch)
1099                return "master";
1100
1101        if (!strcmp(branch, ".")) {
1102                unsigned char sha1[20];
1103                const char *refname = resolve_ref_unsafe("HEAD", 0, sha1, NULL);
1104
1105                if (!refname)
1106                        die(_("No such ref: %s"), "HEAD");
1107
1108                /* detached HEAD */
1109                if (!strcmp(refname, "HEAD"))
1110                        die(_("Submodule (%s) branch configured to inherit "
1111                              "branch from superproject, but the superproject "
1112                              "is not on any branch"), sub->name);
1113
1114                if (!skip_prefix(refname, "refs/heads/", &refname))
1115                        die(_("Expecting a full ref name, got %s"), refname);
1116                return refname;
1117        }
1118
1119        return branch;
1120}
1121
1122static int resolve_remote_submodule_branch(int argc, const char **argv,
1123                const char *prefix)
1124{
1125        const char *ret;
1126        struct strbuf sb = STRBUF_INIT;
1127        if (argc != 2)
1128                die("submodule--helper remote-branch takes exactly one arguments, got %d", argc);
1129
1130        ret = remote_submodule_branch(argv[1]);
1131        if (!ret)
1132                die("submodule %s doesn't exist", argv[1]);
1133
1134        printf("%s", ret);
1135        strbuf_release(&sb);
1136        return 0;
1137}
1138
1139static int push_check(int argc, const char **argv, const char *prefix)
1140{
1141        struct remote *remote;
1142
1143        if (argc < 2)
1144                die("submodule--helper push-check requires at least 1 argument");
1145
1146        /*
1147         * The remote must be configured.
1148         * This is to avoid pushing to the exact same URL as the parent.
1149         */
1150        remote = pushremote_get(argv[1]);
1151        if (!remote || remote->origin == REMOTE_UNCONFIGURED)
1152                die("remote '%s' not configured", argv[1]);
1153
1154        /* Check the refspec */
1155        if (argc > 2) {
1156                int i, refspec_nr = argc - 2;
1157                struct ref *local_refs = get_local_heads();
1158                struct refspec *refspec = parse_push_refspec(refspec_nr,
1159                                                             argv + 2);
1160
1161                for (i = 0; i < refspec_nr; i++) {
1162                        struct refspec *rs = refspec + i;
1163
1164                        if (rs->pattern || rs->matching)
1165                                continue;
1166
1167                        /*
1168                         * LHS must match a single ref
1169                         * NEEDSWORK: add logic to special case 'HEAD' once
1170                         * working with submodules in a detached head state
1171                         * ceases to be the norm.
1172                         */
1173                        if (count_refspec_match(rs->src, local_refs, NULL) != 1)
1174                                die("src refspec '%s' must name a ref",
1175                                    rs->src);
1176                }
1177                free_refspec(refspec_nr, refspec);
1178        }
1179
1180        return 0;
1181}
1182
1183static int absorb_git_dirs(int argc, const char **argv, const char *prefix)
1184{
1185        int i;
1186        struct pathspec pathspec;
1187        struct module_list list = MODULE_LIST_INIT;
1188        unsigned flags = ABSORB_GITDIR_RECURSE_SUBMODULES;
1189
1190        struct option embed_gitdir_options[] = {
1191                OPT_STRING(0, "prefix", &prefix,
1192                           N_("path"),
1193                           N_("path into the working tree")),
1194                OPT_BIT(0, "--recursive", &flags, N_("recurse into submodules"),
1195                        ABSORB_GITDIR_RECURSE_SUBMODULES),
1196                OPT_END()
1197        };
1198
1199        const char *const git_submodule_helper_usage[] = {
1200                N_("git submodule--helper embed-git-dir [<path>...]"),
1201                NULL
1202        };
1203
1204        argc = parse_options(argc, argv, prefix, embed_gitdir_options,
1205                             git_submodule_helper_usage, 0);
1206
1207        gitmodules_config();
1208        git_config(submodule_config, NULL);
1209
1210        if (module_list_compute(argc, argv, prefix, &pathspec, &list) < 0)
1211                return 1;
1212
1213        for (i = 0; i < list.nr; i++)
1214                absorb_git_dir_into_superproject(prefix,
1215                                list.entries[i]->name, flags);
1216
1217        return 0;
1218}
1219
1220static int is_active(int argc, const char **argv, const char *prefix)
1221{
1222        if (argc != 2)
1223                die("submodule--helper is-active takes exactly 1 argument");
1224
1225        gitmodules_config();
1226
1227        return !is_submodule_active(the_repository, argv[1]);
1228}
1229
1230#define SUPPORT_SUPER_PREFIX (1<<0)
1231
1232struct cmd_struct {
1233        const char *cmd;
1234        int (*fn)(int, const char **, const char *);
1235        unsigned option;
1236};
1237
1238static struct cmd_struct commands[] = {
1239        {"list", module_list, 0},
1240        {"name", module_name, 0},
1241        {"clone", module_clone, 0},
1242        {"update-clone", update_clone, 0},
1243        {"relative-path", resolve_relative_path, 0},
1244        {"resolve-relative-url", resolve_relative_url, 0},
1245        {"resolve-relative-url-test", resolve_relative_url_test, 0},
1246        {"init", module_init, SUPPORT_SUPER_PREFIX},
1247        {"remote-branch", resolve_remote_submodule_branch, 0},
1248        {"push-check", push_check, 0},
1249        {"absorb-git-dirs", absorb_git_dirs, SUPPORT_SUPER_PREFIX},
1250        {"is-active", is_active, 0},
1251};
1252
1253int cmd_submodule__helper(int argc, const char **argv, const char *prefix)
1254{
1255        int i;
1256        if (argc < 2 || !strcmp(argv[1], "-h"))
1257                usage("git submodule--helper <command>");
1258
1259        for (i = 0; i < ARRAY_SIZE(commands); i++) {
1260                if (!strcmp(argv[1], commands[i].cmd)) {
1261                        if (get_super_prefix() &&
1262                            !(commands[i].option & SUPPORT_SUPER_PREFIX))
1263                                die(_("%s doesn't support --super-prefix"),
1264                                    commands[i].cmd);
1265                        return commands[i].fn(argc - 1, argv + 1, prefix);
1266                }
1267        }
1268
1269        die(_("'%s' is not a valid submodule--helper "
1270              "subcommand"), argv[1]);
1271}