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