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