7700d89488ed971a4e7cdfcafcbc4c0880836ee3
   1#include "builtin.h"
   2#include "cache.h"
   3#include "parse-options.h"
   4#include "quote.h"
   5#include "pathspec.h"
   6#include "dir.h"
   7#include "utf8.h"
   8#include "submodule.h"
   9#include "submodule-config.h"
  10#include "string-list.h"
  11#include "run-command.h"
  12#include "remote.h"
  13#include "refs.h"
  14#include "connect.h"
  15
  16static char *get_default_remote(void)
  17{
  18        char *dest = NULL, *ret;
  19        unsigned char sha1[20];
  20        struct strbuf sb = STRBUF_INIT;
  21        const char *refname = resolve_ref_unsafe("HEAD", 0, sha1, NULL);
  22
  23        if (!refname)
  24                die(_("No such ref: %s"), "HEAD");
  25
  26        /* detached HEAD */
  27        if (!strcmp(refname, "HEAD"))
  28                return xstrdup("origin");
  29
  30        if (!skip_prefix(refname, "refs/heads/", &refname))
  31                die(_("Expecting a full ref name, got %s"), refname);
  32
  33        strbuf_addf(&sb, "branch.%s.remote", refname);
  34        if (git_config_get_string(sb.buf, &dest))
  35                ret = xstrdup("origin");
  36        else
  37                ret = dest;
  38
  39        strbuf_release(&sb);
  40        return ret;
  41}
  42
  43static int starts_with_dot_slash(const char *str)
  44{
  45        return str[0] == '.' && is_dir_sep(str[1]);
  46}
  47
  48static int starts_with_dot_dot_slash(const char *str)
  49{
  50        return str[0] == '.' && str[1] == '.' && is_dir_sep(str[2]);
  51}
  52
  53/*
  54 * Returns 1 if it was the last chop before ':'.
  55 */
  56static int chop_last_dir(char **remoteurl, int is_relative)
  57{
  58        char *rfind = find_last_dir_sep(*remoteurl);
  59        if (rfind) {
  60                *rfind = '\0';
  61                return 0;
  62        }
  63
  64        rfind = strrchr(*remoteurl, ':');
  65        if (rfind) {
  66                *rfind = '\0';
  67                return 1;
  68        }
  69
  70        if (is_relative || !strcmp(".", *remoteurl))
  71                die(_("cannot strip one component off url '%s'"),
  72                        *remoteurl);
  73
  74        free(*remoteurl);
  75        *remoteurl = xstrdup(".");
  76        return 0;
  77}
  78
  79/*
  80 * The `url` argument is the URL that navigates to the submodule origin
  81 * repo. When relative, this URL is relative to the superproject origin
  82 * URL repo. The `up_path` argument, if specified, is the relative
  83 * path that navigates from the submodule working tree to the superproject
  84 * working tree. Returns the origin URL of the submodule.
  85 *
  86 * Return either an absolute URL or filesystem path (if the superproject
  87 * origin URL is an absolute URL or filesystem path, respectively) or a
  88 * relative file system path (if the superproject origin URL is a relative
  89 * file system path).
  90 *
  91 * When the output is a relative file system path, the path is either
  92 * relative to the submodule working tree, if up_path is specified, or to
  93 * the superproject working tree otherwise.
  94 *
  95 * NEEDSWORK: This works incorrectly on the domain and protocol part.
  96 * remote_url      url              outcome          expectation
  97 * http://a.com/b  ../c             http://a.com/c   as is
  98 * http://a.com/b/ ../c             http://a.com/c   same as previous line, but
  99 *                                                   ignore trailing slash in url
 100 * http://a.com/b  ../../c          http://c         error out
 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    .:c           error out
 104 * NEEDSWORK: Given how chop_last_dir() works, this function is broken
 105 * when a local part has a colon in its path component, too.
 106 */
 107static char *relative_url(const char *remote_url,
 108                                const char *url,
 109                                const char *up_path)
 110{
 111        int is_relative = 0;
 112        int colonsep = 0;
 113        char *out;
 114        char *remoteurl = xstrdup(remote_url);
 115        struct strbuf sb = STRBUF_INIT;
 116        size_t len = strlen(remoteurl);
 117
 118        if (is_dir_sep(remoteurl[len-1]))
 119                remoteurl[len-1] = '\0';
 120
 121        if (!url_is_local_not_ssh(remoteurl) || is_absolute_path(remoteurl))
 122                is_relative = 0;
 123        else {
 124                is_relative = 1;
 125                /*
 126                 * Prepend a './' to ensure all relative
 127                 * remoteurls start with './' or '../'
 128                 */
 129                if (!starts_with_dot_slash(remoteurl) &&
 130                    !starts_with_dot_dot_slash(remoteurl)) {
 131                        strbuf_reset(&sb);
 132                        strbuf_addf(&sb, "./%s", remoteurl);
 133                        free(remoteurl);
 134                        remoteurl = strbuf_detach(&sb, NULL);
 135                }
 136        }
 137        /*
 138         * When the url starts with '../', remove that and the
 139         * last directory in remoteurl.
 140         */
 141        while (url) {
 142                if (starts_with_dot_dot_slash(url)) {
 143                        url += 3;
 144                        colonsep |= chop_last_dir(&remoteurl, is_relative);
 145                } else if (starts_with_dot_slash(url))
 146                        url += 2;
 147                else
 148                        break;
 149        }
 150        strbuf_reset(&sb);
 151        strbuf_addf(&sb, "%s%s%s", remoteurl, colonsep ? ":" : "/", url);
 152        if (ends_with(url, "/"))
 153                strbuf_setlen(&sb, sb.len - 1);
 154        free(remoteurl);
 155
 156        if (starts_with_dot_slash(sb.buf))
 157                out = xstrdup(sb.buf + 2);
 158        else
 159                out = xstrdup(sb.buf);
 160        strbuf_reset(&sb);
 161
 162        if (!up_path || !is_relative)
 163                return out;
 164
 165        strbuf_addf(&sb, "%s%s", up_path, out);
 166        free(out);
 167        return strbuf_detach(&sb, NULL);
 168}
 169
 170static int resolve_relative_url(int argc, const char **argv, const char *prefix)
 171{
 172        char *remoteurl = NULL;
 173        char *remote = get_default_remote();
 174        const char *up_path = NULL;
 175        char *res;
 176        const char *url;
 177        struct strbuf sb = STRBUF_INIT;
 178
 179        if (argc != 2 && argc != 3)
 180                die("resolve-relative-url only accepts one or two arguments");
 181
 182        url = argv[1];
 183        strbuf_addf(&sb, "remote.%s.url", remote);
 184        free(remote);
 185
 186        if (git_config_get_string(sb.buf, &remoteurl))
 187                /* the repository is its own authoritative upstream */
 188                remoteurl = xgetcwd();
 189
 190        if (argc == 3)
 191                up_path = argv[2];
 192
 193        res = relative_url(remoteurl, url, up_path);
 194        puts(res);
 195        free(res);
 196        free(remoteurl);
 197        return 0;
 198}
 199
 200static int resolve_relative_url_test(int argc, const char **argv, const char *prefix)
 201{
 202        char *remoteurl, *res;
 203        const char *up_path, *url;
 204
 205        if (argc != 4)
 206                die("resolve-relative-url-test only accepts three arguments: <up_path> <remoteurl> <url>");
 207
 208        up_path = argv[1];
 209        remoteurl = xstrdup(argv[2]);
 210        url = argv[3];
 211
 212        if (!strcmp(up_path, "(null)"))
 213                up_path = NULL;
 214
 215        res = relative_url(remoteurl, url, up_path);
 216        puts(res);
 217        free(res);
 218        free(remoteurl);
 219        return 0;
 220}
 221
 222struct module_list {
 223        const struct cache_entry **entries;
 224        int alloc, nr;
 225};
 226#define MODULE_LIST_INIT { NULL, 0, 0 }
 227
 228static int module_list_compute(int argc, const char **argv,
 229                               const char *prefix,
 230                               struct pathspec *pathspec,
 231                               struct module_list *list)
 232{
 233        int i, result = 0;
 234        char *ps_matched = NULL;
 235        parse_pathspec(pathspec, 0,
 236                       PATHSPEC_PREFER_FULL |
 237                       PATHSPEC_STRIP_SUBMODULE_SLASH_CHEAP,
 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_initialized(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                utf8_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_sha1, 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_initialized(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                url = xstrdup(sub->url);
 380
 381                if (!url)
 382                        die(_("No url found for submodule path '%s' in .gitmodules"),
 383                                displaypath);
 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_sha1, 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        FILE *submodule_dot_git;
 623        char *p, *path = NULL, *sm_gitdir;
 624        struct strbuf rel_path = STRBUF_INIT;
 625        struct strbuf sb = STRBUF_INIT;
 626        struct string_list reference = STRING_LIST_INIT_NODUP;
 627        char *sm_alternate = NULL, *error_strategy = NULL;
 628
 629        struct option module_clone_options[] = {
 630                OPT_STRING(0, "prefix", &prefix,
 631                           N_("path"),
 632                           N_("alternative anchor for relative paths")),
 633                OPT_STRING(0, "path", &path,
 634                           N_("path"),
 635                           N_("where the new submodule will be cloned to")),
 636                OPT_STRING(0, "name", &name,
 637                           N_("string"),
 638                           N_("name of the new submodule")),
 639                OPT_STRING(0, "url", &url,
 640                           N_("string"),
 641                           N_("url where to clone the submodule from")),
 642                OPT_STRING_LIST(0, "reference", &reference,
 643                           N_("repo"),
 644                           N_("reference repository")),
 645                OPT_STRING(0, "depth", &depth,
 646                           N_("string"),
 647                           N_("depth for shallow clones")),
 648                OPT__QUIET(&quiet, "Suppress output for cloning a submodule"),
 649                OPT_BOOL(0, "progress", &progress,
 650                           N_("force cloning progress")),
 651                OPT_END()
 652        };
 653
 654        const char *const git_submodule_helper_usage[] = {
 655                N_("git submodule--helper clone [--prefix=<path>] [--quiet] "
 656                   "[--reference <repository>] [--name <name>] [--depth <depth>] "
 657                   "--url <url> --path <path>"),
 658                NULL
 659        };
 660
 661        argc = parse_options(argc, argv, prefix, module_clone_options,
 662                             git_submodule_helper_usage, 0);
 663
 664        if (argc || !url || !path || !*path)
 665                usage_with_options(git_submodule_helper_usage,
 666                                   module_clone_options);
 667
 668        strbuf_addf(&sb, "%s/modules/%s", get_git_dir(), name);
 669        sm_gitdir = absolute_pathdup(sb.buf);
 670        strbuf_reset(&sb);
 671
 672        if (!is_absolute_path(path)) {
 673                strbuf_addf(&sb, "%s/%s", get_git_work_tree(), path);
 674                path = strbuf_detach(&sb, NULL);
 675        } else
 676                path = xstrdup(path);
 677
 678        if (!file_exists(sm_gitdir)) {
 679                if (safe_create_leading_directories_const(sm_gitdir) < 0)
 680                        die(_("could not create directory '%s'"), sm_gitdir);
 681
 682                prepare_possible_alternates(name, &reference);
 683
 684                if (clone_submodule(path, sm_gitdir, url, depth, &reference,
 685                                    quiet, progress))
 686                        die(_("clone of '%s' into submodule path '%s' failed"),
 687                            url, path);
 688        } else {
 689                if (safe_create_leading_directories_const(path) < 0)
 690                        die(_("could not create directory '%s'"), path);
 691                strbuf_addf(&sb, "%s/index", sm_gitdir);
 692                unlink_or_warn(sb.buf);
 693                strbuf_reset(&sb);
 694        }
 695
 696        /* Write a .git file in the submodule to redirect to the superproject. */
 697        strbuf_addf(&sb, "%s/.git", path);
 698        if (safe_create_leading_directories_const(sb.buf) < 0)
 699                die(_("could not create leading directories of '%s'"), sb.buf);
 700        submodule_dot_git = fopen(sb.buf, "w");
 701        if (!submodule_dot_git)
 702                die_errno(_("cannot open file '%s'"), sb.buf);
 703
 704        fprintf_or_die(submodule_dot_git, "gitdir: %s\n",
 705                       relative_path(sm_gitdir, path, &rel_path));
 706        if (fclose(submodule_dot_git))
 707                die(_("could not close file %s"), sb.buf);
 708        strbuf_reset(&sb);
 709        strbuf_reset(&rel_path);
 710
 711        /* Redirect the worktree of the submodule in the superproject's config */
 712        p = git_pathdup_submodule(path, "config");
 713        if (!p)
 714                die(_("could not get submodule directory for '%s'"), path);
 715        git_config_set_in_file(p, "core.worktree",
 716                               relative_path(path, sm_gitdir, &rel_path));
 717
 718        /* setup alternateLocation and alternateErrorStrategy in the cloned submodule if needed */
 719        git_config_get_string("submodule.alternateLocation", &sm_alternate);
 720        if (sm_alternate)
 721                git_config_set_in_file(p, "submodule.alternateLocation",
 722                                           sm_alternate);
 723        git_config_get_string("submodule.alternateErrorStrategy", &error_strategy);
 724        if (error_strategy)
 725                git_config_set_in_file(p, "submodule.alternateErrorStrategy",
 726                                           error_strategy);
 727
 728        free(sm_alternate);
 729        free(error_strategy);
 730
 731        strbuf_release(&sb);
 732        strbuf_release(&rel_path);
 733        free(sm_gitdir);
 734        free(path);
 735        free(p);
 736        return 0;
 737}
 738
 739struct submodule_update_clone {
 740        /* index into 'list', the list of submodules to look into for cloning */
 741        int current;
 742        struct module_list list;
 743        unsigned warn_if_uninitialized : 1;
 744
 745        /* update parameter passed via commandline */
 746        struct submodule_update_strategy update;
 747
 748        /* configuration parameters which are passed on to the children */
 749        int progress;
 750        int quiet;
 751        int recommend_shallow;
 752        struct string_list references;
 753        const char *depth;
 754        const char *recursive_prefix;
 755        const char *prefix;
 756
 757        /* Machine-readable status lines to be consumed by git-submodule.sh */
 758        struct string_list projectlines;
 759
 760        /* If we want to stop as fast as possible and return an error */
 761        unsigned quickstop : 1;
 762
 763        /* failed clones to be retried again */
 764        const struct cache_entry **failed_clones;
 765        int failed_clones_nr, failed_clones_alloc;
 766};
 767#define SUBMODULE_UPDATE_CLONE_INIT {0, MODULE_LIST_INIT, 0, \
 768        SUBMODULE_UPDATE_STRATEGY_INIT, 0, 0, -1, STRING_LIST_INIT_DUP, \
 769        NULL, NULL, NULL, \
 770        STRING_LIST_INIT_DUP, 0, NULL, 0, 0}
 771
 772
 773static void next_submodule_warn_missing(struct submodule_update_clone *suc,
 774                struct strbuf *out, const char *displaypath)
 775{
 776        /*
 777         * Only mention uninitialized submodules when their
 778         * paths have been specified.
 779         */
 780        if (suc->warn_if_uninitialized) {
 781                strbuf_addf(out,
 782                        _("Submodule path '%s' not initialized"),
 783                        displaypath);
 784                strbuf_addch(out, '\n');
 785                strbuf_addstr(out,
 786                        _("Maybe you want to use 'update --init'?"));
 787                strbuf_addch(out, '\n');
 788        }
 789}
 790
 791/**
 792 * Determine whether 'ce' needs to be cloned. If so, prepare the 'child' to
 793 * run the clone. Returns 1 if 'ce' needs to be cloned, 0 otherwise.
 794 */
 795static int prepare_to_clone_next_submodule(const struct cache_entry *ce,
 796                                           struct child_process *child,
 797                                           struct submodule_update_clone *suc,
 798                                           struct strbuf *out)
 799{
 800        const struct submodule *sub = NULL;
 801        struct strbuf displaypath_sb = STRBUF_INIT;
 802        struct strbuf sb = STRBUF_INIT;
 803        const char *displaypath = NULL;
 804        int needs_cloning = 0;
 805
 806        if (ce_stage(ce)) {
 807                if (suc->recursive_prefix)
 808                        strbuf_addf(&sb, "%s/%s", suc->recursive_prefix, ce->name);
 809                else
 810                        strbuf_addstr(&sb, ce->name);
 811                strbuf_addf(out, _("Skipping unmerged submodule %s"), sb.buf);
 812                strbuf_addch(out, '\n');
 813                goto cleanup;
 814        }
 815
 816        sub = submodule_from_path(null_sha1, ce->name);
 817
 818        if (suc->recursive_prefix)
 819                displaypath = relative_path(suc->recursive_prefix,
 820                                            ce->name, &displaypath_sb);
 821        else
 822                displaypath = ce->name;
 823
 824        if (!sub) {
 825                next_submodule_warn_missing(suc, out, displaypath);
 826                goto cleanup;
 827        }
 828
 829        if (suc->update.type == SM_UPDATE_NONE
 830            || (suc->update.type == SM_UPDATE_UNSPECIFIED
 831                && sub->update_strategy.type == SM_UPDATE_NONE)) {
 832                strbuf_addf(out, _("Skipping submodule '%s'"), displaypath);
 833                strbuf_addch(out, '\n');
 834                goto cleanup;
 835        }
 836
 837        /* Check if the submodule has been initialized. */
 838        if (!is_submodule_initialized(ce->name)) {
 839                next_submodule_warn_missing(suc, out, displaypath);
 840                goto cleanup;
 841        }
 842
 843        strbuf_reset(&sb);
 844        strbuf_addf(&sb, "%s/.git", ce->name);
 845        needs_cloning = !file_exists(sb.buf);
 846
 847        strbuf_reset(&sb);
 848        strbuf_addf(&sb, "%06o %s %d %d\t%s\n", ce->ce_mode,
 849                        oid_to_hex(&ce->oid), ce_stage(ce),
 850                        needs_cloning, ce->name);
 851        string_list_append(&suc->projectlines, sb.buf);
 852
 853        if (!needs_cloning)
 854                goto cleanup;
 855
 856        child->git_cmd = 1;
 857        child->no_stdin = 1;
 858        child->stdout_to_stderr = 1;
 859        child->err = -1;
 860        argv_array_push(&child->args, "submodule--helper");
 861        argv_array_push(&child->args, "clone");
 862        if (suc->progress)
 863                argv_array_push(&child->args, "--progress");
 864        if (suc->quiet)
 865                argv_array_push(&child->args, "--quiet");
 866        if (suc->prefix)
 867                argv_array_pushl(&child->args, "--prefix", suc->prefix, NULL);
 868        if (suc->recommend_shallow && sub->recommend_shallow == 1)
 869                argv_array_push(&child->args, "--depth=1");
 870        argv_array_pushl(&child->args, "--path", sub->path, NULL);
 871        argv_array_pushl(&child->args, "--name", sub->name, NULL);
 872        argv_array_pushl(&child->args, "--url", sub->url, NULL);
 873        if (suc->references.nr) {
 874                struct string_list_item *item;
 875                for_each_string_list_item(item, &suc->references)
 876                        argv_array_pushl(&child->args, "--reference", item->string, NULL);
 877        }
 878        if (suc->depth)
 879                argv_array_push(&child->args, suc->depth);
 880
 881cleanup:
 882        strbuf_reset(&displaypath_sb);
 883        strbuf_reset(&sb);
 884
 885        return needs_cloning;
 886}
 887
 888static int update_clone_get_next_task(struct child_process *child,
 889                                      struct strbuf *err,
 890                                      void *suc_cb,
 891                                      void **idx_task_cb)
 892{
 893        struct submodule_update_clone *suc = suc_cb;
 894        const struct cache_entry *ce;
 895        int index;
 896
 897        for (; suc->current < suc->list.nr; suc->current++) {
 898                ce = suc->list.entries[suc->current];
 899                if (prepare_to_clone_next_submodule(ce, child, suc, err)) {
 900                        int *p = xmalloc(sizeof(*p));
 901                        *p = suc->current;
 902                        *idx_task_cb = p;
 903                        suc->current++;
 904                        return 1;
 905                }
 906        }
 907
 908        /*
 909         * The loop above tried cloning each submodule once, now try the
 910         * stragglers again, which we can imagine as an extension of the
 911         * entry list.
 912         */
 913        index = suc->current - suc->list.nr;
 914        if (index < suc->failed_clones_nr) {
 915                int *p;
 916                ce = suc->failed_clones[index];
 917                if (!prepare_to_clone_next_submodule(ce, child, suc, err)) {
 918                        suc->current ++;
 919                        strbuf_addstr(err, "BUG: submodule considered for "
 920                                           "cloning, doesn't need cloning "
 921                                           "any more?\n");
 922                        return 0;
 923                }
 924                p = xmalloc(sizeof(*p));
 925                *p = suc->current;
 926                *idx_task_cb = p;
 927                suc->current ++;
 928                return 1;
 929        }
 930
 931        return 0;
 932}
 933
 934static int update_clone_start_failure(struct strbuf *err,
 935                                      void *suc_cb,
 936                                      void *idx_task_cb)
 937{
 938        struct submodule_update_clone *suc = suc_cb;
 939        suc->quickstop = 1;
 940        return 1;
 941}
 942
 943static int update_clone_task_finished(int result,
 944                                      struct strbuf *err,
 945                                      void *suc_cb,
 946                                      void *idx_task_cb)
 947{
 948        const struct cache_entry *ce;
 949        struct submodule_update_clone *suc = suc_cb;
 950
 951        int *idxP = *(int**)idx_task_cb;
 952        int idx = *idxP;
 953        free(idxP);
 954
 955        if (!result)
 956                return 0;
 957
 958        if (idx < suc->list.nr) {
 959                ce  = suc->list.entries[idx];
 960                strbuf_addf(err, _("Failed to clone '%s'. Retry scheduled"),
 961                            ce->name);
 962                strbuf_addch(err, '\n');
 963                ALLOC_GROW(suc->failed_clones,
 964                           suc->failed_clones_nr + 1,
 965                           suc->failed_clones_alloc);
 966                suc->failed_clones[suc->failed_clones_nr++] = ce;
 967                return 0;
 968        } else {
 969                idx -= suc->list.nr;
 970                ce  = suc->failed_clones[idx];
 971                strbuf_addf(err, _("Failed to clone '%s' a second time, aborting"),
 972                            ce->name);
 973                strbuf_addch(err, '\n');
 974                suc->quickstop = 1;
 975                return 1;
 976        }
 977
 978        return 0;
 979}
 980
 981static int update_clone(int argc, const char **argv, const char *prefix)
 982{
 983        const char *update = NULL;
 984        int max_jobs = -1;
 985        struct string_list_item *item;
 986        struct pathspec pathspec;
 987        struct submodule_update_clone suc = SUBMODULE_UPDATE_CLONE_INIT;
 988
 989        struct option module_update_clone_options[] = {
 990                OPT_STRING(0, "prefix", &prefix,
 991                           N_("path"),
 992                           N_("path into the working tree")),
 993                OPT_STRING(0, "recursive-prefix", &suc.recursive_prefix,
 994                           N_("path"),
 995                           N_("path into the working tree, across nested "
 996                              "submodule boundaries")),
 997                OPT_STRING(0, "update", &update,
 998                           N_("string"),
 999                           N_("rebase, merge, checkout or none")),
1000                OPT_STRING_LIST(0, "reference", &suc.references, N_("repo"),
1001                           N_("reference repository")),
1002                OPT_STRING(0, "depth", &suc.depth, "<depth>",
1003                           N_("Create a shallow clone truncated to the "
1004                              "specified number of revisions")),
1005                OPT_INTEGER('j', "jobs", &max_jobs,
1006                            N_("parallel jobs")),
1007                OPT_BOOL(0, "recommend-shallow", &suc.recommend_shallow,
1008                            N_("whether the initial clone should follow the shallow recommendation")),
1009                OPT__QUIET(&suc.quiet, N_("don't print cloning progress")),
1010                OPT_BOOL(0, "progress", &suc.progress,
1011                            N_("force cloning progress")),
1012                OPT_END()
1013        };
1014
1015        const char *const git_submodule_helper_usage[] = {
1016                N_("git submodule--helper update_clone [--prefix=<path>] [<path>...]"),
1017                NULL
1018        };
1019        suc.prefix = prefix;
1020
1021        argc = parse_options(argc, argv, prefix, module_update_clone_options,
1022                             git_submodule_helper_usage, 0);
1023
1024        if (update)
1025                if (parse_submodule_update_strategy(update, &suc.update) < 0)
1026                        die(_("bad value for update parameter"));
1027
1028        if (module_list_compute(argc, argv, prefix, &pathspec, &suc.list) < 0)
1029                return 1;
1030
1031        if (pathspec.nr)
1032                suc.warn_if_uninitialized = 1;
1033
1034        /* Overlay the parsed .gitmodules file with .git/config */
1035        gitmodules_config();
1036        git_config(submodule_config, NULL);
1037
1038        if (max_jobs < 0)
1039                max_jobs = parallel_submodules();
1040
1041        run_processes_parallel(max_jobs,
1042                               update_clone_get_next_task,
1043                               update_clone_start_failure,
1044                               update_clone_task_finished,
1045                               &suc);
1046
1047        /*
1048         * We saved the output and put it out all at once now.
1049         * That means:
1050         * - the listener does not have to interleave their (checkout)
1051         *   work with our fetching.  The writes involved in a
1052         *   checkout involve more straightforward sequential I/O.
1053         * - the listener can avoid doing any work if fetching failed.
1054         */
1055        if (suc.quickstop)
1056                return 1;
1057
1058        for_each_string_list_item(item, &suc.projectlines)
1059                utf8_fprintf(stdout, "%s", item->string);
1060
1061        return 0;
1062}
1063
1064static int resolve_relative_path(int argc, const char **argv, const char *prefix)
1065{
1066        struct strbuf sb = STRBUF_INIT;
1067        if (argc != 3)
1068                die("submodule--helper relative-path takes exactly 2 arguments, got %d", argc);
1069
1070        printf("%s", relative_path(argv[1], argv[2], &sb));
1071        strbuf_release(&sb);
1072        return 0;
1073}
1074
1075static const char *remote_submodule_branch(const char *path)
1076{
1077        const struct submodule *sub;
1078        gitmodules_config();
1079        git_config(submodule_config, NULL);
1080
1081        sub = submodule_from_path(null_sha1, path);
1082        if (!sub)
1083                return NULL;
1084
1085        if (!sub->branch)
1086                return "master";
1087
1088        if (!strcmp(sub->branch, ".")) {
1089                unsigned char sha1[20];
1090                const char *refname = resolve_ref_unsafe("HEAD", 0, sha1, NULL);
1091
1092                if (!refname)
1093                        die(_("No such ref: %s"), "HEAD");
1094
1095                /* detached HEAD */
1096                if (!strcmp(refname, "HEAD"))
1097                        die(_("Submodule (%s) branch configured to inherit "
1098                              "branch from superproject, but the superproject "
1099                              "is not on any branch"), sub->name);
1100
1101                if (!skip_prefix(refname, "refs/heads/", &refname))
1102                        die(_("Expecting a full ref name, got %s"), refname);
1103                return refname;
1104        }
1105
1106        return sub->branch;
1107}
1108
1109static int resolve_remote_submodule_branch(int argc, const char **argv,
1110                const char *prefix)
1111{
1112        const char *ret;
1113        struct strbuf sb = STRBUF_INIT;
1114        if (argc != 2)
1115                die("submodule--helper remote-branch takes exactly one arguments, got %d", argc);
1116
1117        ret = remote_submodule_branch(argv[1]);
1118        if (!ret)
1119                die("submodule %s doesn't exist", argv[1]);
1120
1121        printf("%s", ret);
1122        strbuf_release(&sb);
1123        return 0;
1124}
1125
1126static int absorb_git_dirs(int argc, const char **argv, const char *prefix)
1127{
1128        int i;
1129        struct pathspec pathspec;
1130        struct module_list list = MODULE_LIST_INIT;
1131        unsigned flags = ABSORB_GITDIR_RECURSE_SUBMODULES;
1132
1133        struct option embed_gitdir_options[] = {
1134                OPT_STRING(0, "prefix", &prefix,
1135                           N_("path"),
1136                           N_("path into the working tree")),
1137                OPT_BIT(0, "--recursive", &flags, N_("recurse into submodules"),
1138                        ABSORB_GITDIR_RECURSE_SUBMODULES),
1139                OPT_END()
1140        };
1141
1142        const char *const git_submodule_helper_usage[] = {
1143                N_("git submodule--helper embed-git-dir [<path>...]"),
1144                NULL
1145        };
1146
1147        argc = parse_options(argc, argv, prefix, embed_gitdir_options,
1148                             git_submodule_helper_usage, 0);
1149
1150        gitmodules_config();
1151        git_config(submodule_config, NULL);
1152
1153        if (module_list_compute(argc, argv, prefix, &pathspec, &list) < 0)
1154                return 1;
1155
1156        for (i = 0; i < list.nr; i++)
1157                absorb_git_dir_into_superproject(prefix,
1158                                list.entries[i]->name, flags);
1159
1160        return 0;
1161}
1162
1163static int is_active(int argc, const char **argv, const char *prefix)
1164{
1165        if (argc != 2)
1166                die("submodule--helper is-active takes exactly 1 arguments");
1167
1168        gitmodules_config();
1169
1170        return !is_submodule_initialized(argv[1]);
1171}
1172
1173#define SUPPORT_SUPER_PREFIX (1<<0)
1174
1175struct cmd_struct {
1176        const char *cmd;
1177        int (*fn)(int, const char **, const char *);
1178        unsigned option;
1179};
1180
1181static struct cmd_struct commands[] = {
1182        {"list", module_list, 0},
1183        {"name", module_name, 0},
1184        {"clone", module_clone, 0},
1185        {"update-clone", update_clone, 0},
1186        {"relative-path", resolve_relative_path, 0},
1187        {"resolve-relative-url", resolve_relative_url, 0},
1188        {"resolve-relative-url-test", resolve_relative_url_test, 0},
1189        {"init", module_init, SUPPORT_SUPER_PREFIX},
1190        {"remote-branch", resolve_remote_submodule_branch, 0},
1191        {"absorb-git-dirs", absorb_git_dirs, SUPPORT_SUPER_PREFIX},
1192        {"is-active", is_active, 0},
1193};
1194
1195int cmd_submodule__helper(int argc, const char **argv, const char *prefix)
1196{
1197        int i;
1198        if (argc < 2)
1199                die(_("submodule--helper subcommand must be "
1200                      "called with a subcommand"));
1201
1202        for (i = 0; i < ARRAY_SIZE(commands); i++) {
1203                if (!strcmp(argv[1], commands[i].cmd)) {
1204                        if (get_super_prefix() &&
1205                            !(commands[i].option & SUPPORT_SUPER_PREFIX))
1206                                die(_("%s doesn't support --super-prefix"),
1207                                    commands[i].cmd);
1208                        return commands[i].fn(argc - 1, argv + 1, prefix);
1209                }
1210        }
1211
1212        die(_("'%s' is not a valid submodule--helper "
1213              "subcommand"), argv[1]);
1214}