2 #include "repository.h"
5 #include "parse-options.h"
10 #include "submodule-config.h"
11 #include "string-list.h"
12 #include "run-command.h"
20 #define OPT_QUIET (1 << 0)
21 #define OPT_CACHED (1 << 1)
22 #define OPT_RECURSIVE (1 << 2)
24 typedef void (*each_submodule_fn)(const struct cache_entry *list_item,
27 static char *get_default_remote(void)
29 char *dest = NULL, *ret;
30 struct strbuf sb = STRBUF_INIT;
31 const char *refname = resolve_ref_unsafe("HEAD", 0, NULL, NULL);
34 die(_("No such ref: %s"), "HEAD");
37 if (!strcmp(refname, "HEAD"))
38 return xstrdup("origin");
40 if (!skip_prefix(refname, "refs/heads/", &refname))
41 die(_("Expecting a full ref name, got %s"), refname);
43 strbuf_addf(&sb, "branch.%s.remote", refname);
44 if (git_config_get_string(sb.buf, &dest))
45 ret = xstrdup("origin");
53 static int print_default_remote(int argc, const char **argv, const char *prefix)
58 die(_("submodule--helper print-default-remote takes no arguments"));
60 remote = get_default_remote();
62 printf("%s\n", remote);
67 static int starts_with_dot_slash(const char *str)
69 return str[0] == '.' && is_dir_sep(str[1]);
72 static int starts_with_dot_dot_slash(const char *str)
74 return str[0] == '.' && str[1] == '.' && is_dir_sep(str[2]);
78 * Returns 1 if it was the last chop before ':'.
80 static int chop_last_dir(char **remoteurl, int is_relative)
82 char *rfind = find_last_dir_sep(*remoteurl);
88 rfind = strrchr(*remoteurl, ':');
94 if (is_relative || !strcmp(".", *remoteurl))
95 die(_("cannot strip one component off url '%s'"),
99 *remoteurl = xstrdup(".");
104 * The `url` argument is the URL that navigates to the submodule origin
105 * repo. When relative, this URL is relative to the superproject origin
106 * URL repo. The `up_path` argument, if specified, is the relative
107 * path that navigates from the submodule working tree to the superproject
108 * working tree. Returns the origin URL of the submodule.
110 * Return either an absolute URL or filesystem path (if the superproject
111 * origin URL is an absolute URL or filesystem path, respectively) or a
112 * relative file system path (if the superproject origin URL is a relative
115 * When the output is a relative file system path, the path is either
116 * relative to the submodule working tree, if up_path is specified, or to
117 * the superproject working tree otherwise.
119 * NEEDSWORK: This works incorrectly on the domain and protocol part.
120 * remote_url url outcome expectation
121 * http://a.com/b ../c http://a.com/c as is
122 * http://a.com/b/ ../c http://a.com/c same as previous line, but
123 * ignore trailing slash in url
124 * http://a.com/b ../../c http://c error out
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 .:c error out
128 * NEEDSWORK: Given how chop_last_dir() works, this function is broken
129 * when a local part has a colon in its path component, too.
131 static char *relative_url(const char *remote_url,
138 char *remoteurl = xstrdup(remote_url);
139 struct strbuf sb = STRBUF_INIT;
140 size_t len = strlen(remoteurl);
142 if (is_dir_sep(remoteurl[len-1]))
143 remoteurl[len-1] = '\0';
145 if (!url_is_local_not_ssh(remoteurl) || is_absolute_path(remoteurl))
150 * Prepend a './' to ensure all relative
151 * remoteurls start with './' or '../'
153 if (!starts_with_dot_slash(remoteurl) &&
154 !starts_with_dot_dot_slash(remoteurl)) {
156 strbuf_addf(&sb, "./%s", remoteurl);
158 remoteurl = strbuf_detach(&sb, NULL);
162 * When the url starts with '../', remove that and the
163 * last directory in remoteurl.
166 if (starts_with_dot_dot_slash(url)) {
168 colonsep |= chop_last_dir(&remoteurl, is_relative);
169 } else if (starts_with_dot_slash(url))
175 strbuf_addf(&sb, "%s%s%s", remoteurl, colonsep ? ":" : "/", url);
176 if (ends_with(url, "/"))
177 strbuf_setlen(&sb, sb.len - 1);
180 if (starts_with_dot_slash(sb.buf))
181 out = xstrdup(sb.buf + 2);
183 out = xstrdup(sb.buf);
186 if (!up_path || !is_relative)
189 strbuf_addf(&sb, "%s%s", up_path, out);
191 return strbuf_detach(&sb, NULL);
194 static int resolve_relative_url(int argc, const char **argv, const char *prefix)
196 char *remoteurl = NULL;
197 char *remote = get_default_remote();
198 const char *up_path = NULL;
201 struct strbuf sb = STRBUF_INIT;
203 if (argc != 2 && argc != 3)
204 die("resolve-relative-url only accepts one or two arguments");
207 strbuf_addf(&sb, "remote.%s.url", remote);
210 if (git_config_get_string(sb.buf, &remoteurl))
211 /* the repository is its own authoritative upstream */
212 remoteurl = xgetcwd();
217 res = relative_url(remoteurl, url, up_path);
224 static int resolve_relative_url_test(int argc, const char **argv, const char *prefix)
226 char *remoteurl, *res;
227 const char *up_path, *url;
230 die("resolve-relative-url-test only accepts three arguments: <up_path> <remoteurl> <url>");
233 remoteurl = xstrdup(argv[2]);
236 if (!strcmp(up_path, "(null)"))
239 res = relative_url(remoteurl, url, up_path);
246 /* the result should be freed by the caller. */
247 static char *get_submodule_displaypath(const char *path, const char *prefix)
249 const char *super_prefix = get_super_prefix();
251 if (prefix && super_prefix) {
252 BUG("cannot have prefix '%s' and superprefix '%s'",
253 prefix, super_prefix);
255 struct strbuf sb = STRBUF_INIT;
256 char *displaypath = xstrdup(relative_path(path, prefix, &sb));
259 } else if (super_prefix) {
260 return xstrfmt("%s%s", super_prefix, path);
262 return xstrdup(path);
266 static char *compute_rev_name(const char *sub_path, const char* object_id)
268 struct strbuf sb = STRBUF_INIT;
271 static const char *describe_bare[] = { NULL };
273 static const char *describe_tags[] = { "--tags", NULL };
275 static const char *describe_contains[] = { "--contains", NULL };
277 static const char *describe_all_always[] = { "--all", "--always", NULL };
279 static const char **describe_argv[] = { describe_bare, describe_tags,
281 describe_all_always, NULL };
283 for (d = describe_argv; *d; d++) {
284 struct child_process cp = CHILD_PROCESS_INIT;
285 prepare_submodule_repo_env(&cp.env_array);
290 argv_array_push(&cp.args, "describe");
291 argv_array_pushv(&cp.args, *d);
292 argv_array_push(&cp.args, object_id);
294 if (!capture_command(&cp, &sb, 0)) {
295 strbuf_strip_suffix(&sb, "\n");
296 return strbuf_detach(&sb, NULL);
305 const struct cache_entry **entries;
308 #define MODULE_LIST_INIT { NULL, 0, 0 }
310 static int module_list_compute(int argc, const char **argv,
312 struct pathspec *pathspec,
313 struct module_list *list)
316 char *ps_matched = NULL;
317 parse_pathspec(pathspec, 0,
318 PATHSPEC_PREFER_FULL,
322 ps_matched = xcalloc(pathspec->nr, 1);
324 if (read_cache() < 0)
325 die(_("index file corrupt"));
327 for (i = 0; i < active_nr; i++) {
328 const struct cache_entry *ce = active_cache[i];
330 if (!match_pathspec(pathspec, ce->name, ce_namelen(ce),
332 !S_ISGITLINK(ce->ce_mode))
335 ALLOC_GROW(list->entries, list->nr + 1, list->alloc);
336 list->entries[list->nr++] = ce;
337 while (i + 1 < active_nr &&
338 !strcmp(ce->name, active_cache[i + 1]->name))
340 * Skip entries with the same name in different stages
341 * to make sure an entry is returned only once.
346 if (ps_matched && report_path_error(ps_matched, pathspec, prefix))
354 static void module_list_active(struct module_list *list)
357 struct module_list active_modules = MODULE_LIST_INIT;
359 for (i = 0; i < list->nr; i++) {
360 const struct cache_entry *ce = list->entries[i];
362 if (!is_submodule_active(the_repository, ce->name))
365 ALLOC_GROW(active_modules.entries,
366 active_modules.nr + 1,
367 active_modules.alloc);
368 active_modules.entries[active_modules.nr++] = ce;
372 *list = active_modules;
375 static char *get_up_path(const char *path)
378 struct strbuf sb = STRBUF_INIT;
380 for (i = count_slashes(path); i; i--)
381 strbuf_addstr(&sb, "../");
384 * Check if 'path' ends with slash or not
385 * for having the same output for dir/sub_dir
388 if (!is_dir_sep(path[strlen(path) - 1]))
389 strbuf_addstr(&sb, "../");
391 return strbuf_detach(&sb, NULL);
394 static int module_list(int argc, const char **argv, const char *prefix)
397 struct pathspec pathspec;
398 struct module_list list = MODULE_LIST_INIT;
400 struct option module_list_options[] = {
401 OPT_STRING(0, "prefix", &prefix,
403 N_("alternative anchor for relative paths")),
407 const char *const git_submodule_helper_usage[] = {
408 N_("git submodule--helper list [--prefix=<path>] [<path>...]"),
412 argc = parse_options(argc, argv, prefix, module_list_options,
413 git_submodule_helper_usage, 0);
415 if (module_list_compute(argc, argv, prefix, &pathspec, &list) < 0)
418 for (i = 0; i < list.nr; i++) {
419 const struct cache_entry *ce = list.entries[i];
422 printf("%06o %s U\t", ce->ce_mode, sha1_to_hex(null_sha1));
424 printf("%06o %s %d\t", ce->ce_mode,
425 oid_to_hex(&ce->oid), ce_stage(ce));
427 fprintf(stdout, "%s\n", ce->name);
432 static void for_each_listed_submodule(const struct module_list *list,
433 each_submodule_fn fn, void *cb_data)
436 for (i = 0; i < list->nr; i++)
437 fn(list->entries[i], cb_data);
445 #define INIT_CB_INIT { NULL, 0 }
447 static void init_submodule(const char *path, const char *prefix,
450 const struct submodule *sub;
451 struct strbuf sb = STRBUF_INIT;
452 char *upd = NULL, *url = NULL, *displaypath;
454 displaypath = get_submodule_displaypath(path, prefix);
456 sub = submodule_from_path(&null_oid, path);
459 die(_("No url found for submodule path '%s' in .gitmodules"),
463 * NEEDSWORK: In a multi-working-tree world, this needs to be
464 * set in the per-worktree config.
466 * Set active flag for the submodule being initialized
468 if (!is_submodule_active(the_repository, path)) {
469 strbuf_addf(&sb, "submodule.%s.active", sub->name);
470 git_config_set_gently(sb.buf, "true");
475 * Copy url setting when it is not set yet.
476 * To look up the url in .git/config, we must not fall back to
477 * .gitmodules, so look it up directly.
479 strbuf_addf(&sb, "submodule.%s.url", sub->name);
480 if (git_config_get_string(sb.buf, &url)) {
482 die(_("No url found for submodule path '%s' in .gitmodules"),
485 url = xstrdup(sub->url);
487 /* Possibly a url relative to parent */
488 if (starts_with_dot_dot_slash(url) ||
489 starts_with_dot_slash(url)) {
490 char *remoteurl, *relurl;
491 char *remote = get_default_remote();
492 struct strbuf remotesb = STRBUF_INIT;
493 strbuf_addf(&remotesb, "remote.%s.url", remote);
496 if (git_config_get_string(remotesb.buf, &remoteurl)) {
497 warning(_("could not lookup configuration '%s'. Assuming this repository is its own authoritative upstream."), remotesb.buf);
498 remoteurl = xgetcwd();
500 relurl = relative_url(remoteurl, url, NULL);
501 strbuf_release(&remotesb);
507 if (git_config_set_gently(sb.buf, url))
508 die(_("Failed to register url for submodule path '%s'"),
510 if (!(flags & OPT_QUIET))
512 _("Submodule '%s' (%s) registered for path '%s'\n"),
513 sub->name, url, displaypath);
517 /* Copy "update" setting when it is not set yet */
518 strbuf_addf(&sb, "submodule.%s.update", sub->name);
519 if (git_config_get_string(sb.buf, &upd) &&
520 sub->update_strategy.type != SM_UPDATE_UNSPECIFIED) {
521 if (sub->update_strategy.type == SM_UPDATE_COMMAND) {
522 fprintf(stderr, _("warning: command update mode suggested for submodule '%s'\n"),
524 upd = xstrdup("none");
526 upd = xstrdup(submodule_strategy_to_string(&sub->update_strategy));
528 if (git_config_set_gently(sb.buf, upd))
529 die(_("Failed to register update mode for submodule path '%s'"), displaypath);
537 static void init_submodule_cb(const struct cache_entry *list_item, void *cb_data)
539 struct init_cb *info = cb_data;
540 init_submodule(list_item->name, info->prefix, info->flags);
543 static int module_init(int argc, const char **argv, const char *prefix)
545 struct init_cb info = INIT_CB_INIT;
546 struct pathspec pathspec;
547 struct module_list list = MODULE_LIST_INIT;
550 struct option module_init_options[] = {
551 OPT__QUIET(&quiet, N_("Suppress output for initializing a submodule")),
555 const char *const git_submodule_helper_usage[] = {
556 N_("git submodule--helper init [<path>]"),
560 argc = parse_options(argc, argv, prefix, module_init_options,
561 git_submodule_helper_usage, 0);
563 if (module_list_compute(argc, argv, prefix, &pathspec, &list) < 0)
567 * If there are no path args and submodule.active is set then,
568 * by default, only initialize 'active' modules.
570 if (!argc && git_config_get_value_multi("submodule.active"))
571 module_list_active(&list);
573 info.prefix = prefix;
575 info.flags |= OPT_QUIET;
577 for_each_listed_submodule(&list, init_submodule_cb, &info);
587 #define STATUS_CB_INIT { NULL, 0 }
589 static void print_status(unsigned int flags, char state, const char *path,
590 const struct object_id *oid, const char *displaypath)
592 if (flags & OPT_QUIET)
595 printf("%c%s %s", state, oid_to_hex(oid), displaypath);
597 if (state == ' ' || state == '+')
598 printf(" (%s)", compute_rev_name(path, oid_to_hex(oid)));
603 static int handle_submodule_head_ref(const char *refname,
604 const struct object_id *oid, int flags,
607 struct object_id *output = cb_data;
614 static void status_submodule(const char *path, const struct object_id *ce_oid,
615 unsigned int ce_flags, const char *prefix,
619 struct argv_array diff_files_args = ARGV_ARRAY_INIT;
621 int diff_files_result;
623 if (!submodule_from_path(&null_oid, path))
624 die(_("no submodule mapping found in .gitmodules for path '%s'"),
627 displaypath = get_submodule_displaypath(path, prefix);
629 if ((CE_STAGEMASK & ce_flags) >> CE_STAGESHIFT) {
630 print_status(flags, 'U', path, &null_oid, displaypath);
634 if (!is_submodule_active(the_repository, path)) {
635 print_status(flags, '-', path, ce_oid, displaypath);
639 argv_array_pushl(&diff_files_args, "diff-files",
640 "--ignore-submodules=dirty", "--quiet", "--",
643 git_config(git_diff_basic_config, NULL);
644 init_revisions(&rev, prefix);
646 diff_files_args.argc = setup_revisions(diff_files_args.argc,
647 diff_files_args.argv,
649 diff_files_result = run_diff_files(&rev, 0);
651 if (!diff_result_code(&rev.diffopt, diff_files_result)) {
652 print_status(flags, ' ', path, ce_oid,
654 } else if (!(flags & OPT_CACHED)) {
655 struct object_id oid;
657 if (refs_head_ref(get_submodule_ref_store(path),
658 handle_submodule_head_ref, &oid))
659 die(_("could not resolve HEAD ref inside the "
660 "submodule '%s'"), path);
662 print_status(flags, '+', path, &oid, displaypath);
664 print_status(flags, '+', path, ce_oid, displaypath);
667 if (flags & OPT_RECURSIVE) {
668 struct child_process cpr = CHILD_PROCESS_INIT;
672 prepare_submodule_repo_env(&cpr.env_array);
674 argv_array_push(&cpr.args, "--super-prefix");
675 argv_array_pushf(&cpr.args, "%s/", displaypath);
676 argv_array_pushl(&cpr.args, "submodule--helper", "status",
677 "--recursive", NULL);
679 if (flags & OPT_CACHED)
680 argv_array_push(&cpr.args, "--cached");
682 if (flags & OPT_QUIET)
683 argv_array_push(&cpr.args, "--quiet");
685 if (run_command(&cpr))
686 die(_("failed to recurse into submodule '%s'"), path);
690 argv_array_clear(&diff_files_args);
694 static void status_submodule_cb(const struct cache_entry *list_item,
697 struct status_cb *info = cb_data;
698 status_submodule(list_item->name, &list_item->oid, list_item->ce_flags,
699 info->prefix, info->flags);
702 static int module_status(int argc, const char **argv, const char *prefix)
704 struct status_cb info = STATUS_CB_INIT;
705 struct pathspec pathspec;
706 struct module_list list = MODULE_LIST_INIT;
709 struct option module_status_options[] = {
710 OPT__QUIET(&quiet, N_("Suppress submodule status output")),
711 OPT_BIT(0, "cached", &info.flags, N_("Use commit stored in the index instead of the one stored in the submodule HEAD"), OPT_CACHED),
712 OPT_BIT(0, "recursive", &info.flags, N_("recurse into nested submodules"), OPT_RECURSIVE),
716 const char *const git_submodule_helper_usage[] = {
717 N_("git submodule status [--quiet] [--cached] [--recursive] [<path>...]"),
721 argc = parse_options(argc, argv, prefix, module_status_options,
722 git_submodule_helper_usage, 0);
724 if (module_list_compute(argc, argv, prefix, &pathspec, &list) < 0)
727 info.prefix = prefix;
729 info.flags |= OPT_QUIET;
731 for_each_listed_submodule(&list, status_submodule_cb, &info);
736 static int module_name(int argc, const char **argv, const char *prefix)
738 const struct submodule *sub;
741 usage(_("git submodule--helper name <path>"));
743 sub = submodule_from_path(&null_oid, argv[1]);
746 die(_("no submodule mapping found in .gitmodules for path '%s'"),
749 printf("%s\n", sub->name);
759 #define SYNC_CB_INIT { NULL, 0 }
761 static void sync_submodule(const char *path, const char *prefix,
764 const struct submodule *sub;
765 char *remote_key = NULL;
766 char *sub_origin_url, *super_config_url, *displaypath;
767 struct strbuf sb = STRBUF_INIT;
768 struct child_process cp = CHILD_PROCESS_INIT;
769 char *sub_config_path = NULL;
771 if (!is_submodule_active(the_repository, path))
774 sub = submodule_from_path(&null_oid, path);
776 if (sub && sub->url) {
777 if (starts_with_dot_dot_slash(sub->url) ||
778 starts_with_dot_slash(sub->url)) {
779 char *remote_url, *up_path;
780 char *remote = get_default_remote();
781 strbuf_addf(&sb, "remote.%s.url", remote);
783 if (git_config_get_string(sb.buf, &remote_url))
784 remote_url = xgetcwd();
786 up_path = get_up_path(path);
787 sub_origin_url = relative_url(remote_url, sub->url, up_path);
788 super_config_url = relative_url(remote_url, sub->url, NULL);
794 sub_origin_url = xstrdup(sub->url);
795 super_config_url = xstrdup(sub->url);
798 sub_origin_url = xstrdup("");
799 super_config_url = xstrdup("");
802 displaypath = get_submodule_displaypath(path, prefix);
804 if (!(flags & OPT_QUIET))
805 printf(_("Synchronizing submodule url for '%s'\n"),
809 strbuf_addf(&sb, "submodule.%s.url", sub->name);
810 if (git_config_set_gently(sb.buf, super_config_url))
811 die(_("failed to register url for submodule path '%s'"),
814 if (!is_submodule_populated_gently(path, NULL))
817 prepare_submodule_repo_env(&cp.env_array);
820 argv_array_pushl(&cp.args, "submodule--helper",
821 "print-default-remote", NULL);
824 if (capture_command(&cp, &sb, 0))
825 die(_("failed to get the default remote for submodule '%s'"),
828 strbuf_strip_suffix(&sb, "\n");
829 remote_key = xstrfmt("remote.%s.url", sb.buf);
832 submodule_to_gitdir(&sb, path);
833 strbuf_addstr(&sb, "/config");
835 if (git_config_set_in_file_gently(sb.buf, remote_key, sub_origin_url))
836 die(_("failed to update remote for submodule '%s'"),
839 if (flags & OPT_RECURSIVE) {
840 struct child_process cpr = CHILD_PROCESS_INIT;
844 prepare_submodule_repo_env(&cpr.env_array);
846 argv_array_push(&cpr.args, "--super-prefix");
847 argv_array_pushf(&cpr.args, "%s/", displaypath);
848 argv_array_pushl(&cpr.args, "submodule--helper", "sync",
849 "--recursive", NULL);
851 if (flags & OPT_QUIET)
852 argv_array_push(&cpr.args, "--quiet");
854 if (run_command(&cpr))
855 die(_("failed to recurse into submodule '%s'"),
860 free(super_config_url);
861 free(sub_origin_url);
865 free(sub_config_path);
868 static void sync_submodule_cb(const struct cache_entry *list_item, void *cb_data)
870 struct sync_cb *info = cb_data;
871 sync_submodule(list_item->name, info->prefix, info->flags);
875 static int module_sync(int argc, const char **argv, const char *prefix)
877 struct sync_cb info = SYNC_CB_INIT;
878 struct pathspec pathspec;
879 struct module_list list = MODULE_LIST_INIT;
883 struct option module_sync_options[] = {
884 OPT__QUIET(&quiet, N_("Suppress output of synchronizing submodule url")),
885 OPT_BOOL(0, "recursive", &recursive,
886 N_("Recurse into nested submodules")),
890 const char *const git_submodule_helper_usage[] = {
891 N_("git submodule--helper sync [--quiet] [--recursive] [<path>]"),
895 argc = parse_options(argc, argv, prefix, module_sync_options,
896 git_submodule_helper_usage, 0);
898 if (module_list_compute(argc, argv, prefix, &pathspec, &list) < 0)
901 info.prefix = prefix;
903 info.flags |= OPT_QUIET;
905 info.flags |= OPT_RECURSIVE;
907 for_each_listed_submodule(&list, sync_submodule_cb, &info);
912 static int clone_submodule(const char *path, const char *gitdir, const char *url,
913 const char *depth, struct string_list *reference,
914 int quiet, int progress)
916 struct child_process cp = CHILD_PROCESS_INIT;
918 argv_array_push(&cp.args, "clone");
919 argv_array_push(&cp.args, "--no-checkout");
921 argv_array_push(&cp.args, "--quiet");
923 argv_array_push(&cp.args, "--progress");
925 argv_array_pushl(&cp.args, "--depth", depth, NULL);
927 struct string_list_item *item;
928 for_each_string_list_item(item, reference)
929 argv_array_pushl(&cp.args, "--reference",
932 if (gitdir && *gitdir)
933 argv_array_pushl(&cp.args, "--separate-git-dir", gitdir, NULL);
935 argv_array_push(&cp.args, url);
936 argv_array_push(&cp.args, path);
939 prepare_submodule_repo_env(&cp.env_array);
942 return run_command(&cp);
945 struct submodule_alternate_setup {
946 const char *submodule_name;
947 enum SUBMODULE_ALTERNATE_ERROR_MODE {
948 SUBMODULE_ALTERNATE_ERROR_DIE,
949 SUBMODULE_ALTERNATE_ERROR_INFO,
950 SUBMODULE_ALTERNATE_ERROR_IGNORE
952 struct string_list *reference;
954 #define SUBMODULE_ALTERNATE_SETUP_INIT { NULL, \
955 SUBMODULE_ALTERNATE_ERROR_IGNORE, NULL }
957 static int add_possible_reference_from_superproject(
958 struct alternate_object_database *alt, void *sas_cb)
960 struct submodule_alternate_setup *sas = sas_cb;
963 * If the alternate object store is another repository, try the
964 * standard layout with .git/(modules/<name>)+/objects
966 if (ends_with(alt->path, "/objects")) {
968 struct strbuf sb = STRBUF_INIT;
969 struct strbuf err = STRBUF_INIT;
970 strbuf_add(&sb, alt->path, strlen(alt->path) - strlen("objects"));
973 * We need to end the new path with '/' to mark it as a dir,
974 * otherwise a submodule name containing '/' will be broken
975 * as the last part of a missing submodule reference would
976 * be taken as a file name.
978 strbuf_addf(&sb, "modules/%s/", sas->submodule_name);
980 sm_alternate = compute_alternate_path(sb.buf, &err);
982 string_list_append(sas->reference, xstrdup(sb.buf));
985 switch (sas->error_mode) {
986 case SUBMODULE_ALTERNATE_ERROR_DIE:
987 die(_("submodule '%s' cannot add alternate: %s"),
988 sas->submodule_name, err.buf);
989 case SUBMODULE_ALTERNATE_ERROR_INFO:
990 fprintf(stderr, _("submodule '%s' cannot add alternate: %s"),
991 sas->submodule_name, err.buf);
992 case SUBMODULE_ALTERNATE_ERROR_IGNORE:
1002 static void prepare_possible_alternates(const char *sm_name,
1003 struct string_list *reference)
1005 char *sm_alternate = NULL, *error_strategy = NULL;
1006 struct submodule_alternate_setup sas = SUBMODULE_ALTERNATE_SETUP_INIT;
1008 git_config_get_string("submodule.alternateLocation", &sm_alternate);
1012 git_config_get_string("submodule.alternateErrorStrategy", &error_strategy);
1014 if (!error_strategy)
1015 error_strategy = xstrdup("die");
1017 sas.submodule_name = sm_name;
1018 sas.reference = reference;
1019 if (!strcmp(error_strategy, "die"))
1020 sas.error_mode = SUBMODULE_ALTERNATE_ERROR_DIE;
1021 else if (!strcmp(error_strategy, "info"))
1022 sas.error_mode = SUBMODULE_ALTERNATE_ERROR_INFO;
1023 else if (!strcmp(error_strategy, "ignore"))
1024 sas.error_mode = SUBMODULE_ALTERNATE_ERROR_IGNORE;
1026 die(_("Value '%s' for submodule.alternateErrorStrategy is not recognized"), error_strategy);
1028 if (!strcmp(sm_alternate, "superproject"))
1029 foreach_alt_odb(add_possible_reference_from_superproject, &sas);
1030 else if (!strcmp(sm_alternate, "no"))
1033 die(_("Value '%s' for submodule.alternateLocation is not recognized"), sm_alternate);
1036 free(error_strategy);
1039 static int module_clone(int argc, const char **argv, const char *prefix)
1041 const char *name = NULL, *url = NULL, *depth = NULL;
1044 char *p, *path = NULL, *sm_gitdir;
1045 struct strbuf sb = STRBUF_INIT;
1046 struct string_list reference = STRING_LIST_INIT_NODUP;
1047 char *sm_alternate = NULL, *error_strategy = NULL;
1049 struct option module_clone_options[] = {
1050 OPT_STRING(0, "prefix", &prefix,
1052 N_("alternative anchor for relative paths")),
1053 OPT_STRING(0, "path", &path,
1055 N_("where the new submodule will be cloned to")),
1056 OPT_STRING(0, "name", &name,
1058 N_("name of the new submodule")),
1059 OPT_STRING(0, "url", &url,
1061 N_("url where to clone the submodule from")),
1062 OPT_STRING_LIST(0, "reference", &reference,
1064 N_("reference repository")),
1065 OPT_STRING(0, "depth", &depth,
1067 N_("depth for shallow clones")),
1068 OPT__QUIET(&quiet, "Suppress output for cloning a submodule"),
1069 OPT_BOOL(0, "progress", &progress,
1070 N_("force cloning progress")),
1074 const char *const git_submodule_helper_usage[] = {
1075 N_("git submodule--helper clone [--prefix=<path>] [--quiet] "
1076 "[--reference <repository>] [--name <name>] [--depth <depth>] "
1077 "--url <url> --path <path>"),
1081 argc = parse_options(argc, argv, prefix, module_clone_options,
1082 git_submodule_helper_usage, 0);
1084 if (argc || !url || !path || !*path)
1085 usage_with_options(git_submodule_helper_usage,
1086 module_clone_options);
1088 strbuf_addf(&sb, "%s/modules/%s", get_git_dir(), name);
1089 sm_gitdir = absolute_pathdup(sb.buf);
1092 if (!is_absolute_path(path)) {
1093 strbuf_addf(&sb, "%s/%s", get_git_work_tree(), path);
1094 path = strbuf_detach(&sb, NULL);
1096 path = xstrdup(path);
1098 if (!file_exists(sm_gitdir)) {
1099 if (safe_create_leading_directories_const(sm_gitdir) < 0)
1100 die(_("could not create directory '%s'"), sm_gitdir);
1102 prepare_possible_alternates(name, &reference);
1104 if (clone_submodule(path, sm_gitdir, url, depth, &reference,
1106 die(_("clone of '%s' into submodule path '%s' failed"),
1109 if (safe_create_leading_directories_const(path) < 0)
1110 die(_("could not create directory '%s'"), path);
1111 strbuf_addf(&sb, "%s/index", sm_gitdir);
1112 unlink_or_warn(sb.buf);
1116 /* Connect module worktree and git dir */
1117 connect_work_tree_and_git_dir(path, sm_gitdir);
1119 p = git_pathdup_submodule(path, "config");
1121 die(_("could not get submodule directory for '%s'"), path);
1123 /* setup alternateLocation and alternateErrorStrategy in the cloned submodule if needed */
1124 git_config_get_string("submodule.alternateLocation", &sm_alternate);
1126 git_config_set_in_file(p, "submodule.alternateLocation",
1128 git_config_get_string("submodule.alternateErrorStrategy", &error_strategy);
1130 git_config_set_in_file(p, "submodule.alternateErrorStrategy",
1134 free(error_strategy);
1136 strbuf_release(&sb);
1143 struct submodule_update_clone {
1144 /* index into 'list', the list of submodules to look into for cloning */
1146 struct module_list list;
1147 unsigned warn_if_uninitialized : 1;
1149 /* update parameter passed via commandline */
1150 struct submodule_update_strategy update;
1152 /* configuration parameters which are passed on to the children */
1155 int recommend_shallow;
1156 struct string_list references;
1158 const char *recursive_prefix;
1161 /* Machine-readable status lines to be consumed by git-submodule.sh */
1162 struct string_list projectlines;
1164 /* If we want to stop as fast as possible and return an error */
1165 unsigned quickstop : 1;
1167 /* failed clones to be retried again */
1168 const struct cache_entry **failed_clones;
1169 int failed_clones_nr, failed_clones_alloc;
1171 #define SUBMODULE_UPDATE_CLONE_INIT {0, MODULE_LIST_INIT, 0, \
1172 SUBMODULE_UPDATE_STRATEGY_INIT, 0, 0, -1, STRING_LIST_INIT_DUP, \
1174 STRING_LIST_INIT_DUP, 0, NULL, 0, 0}
1177 static void next_submodule_warn_missing(struct submodule_update_clone *suc,
1178 struct strbuf *out, const char *displaypath)
1181 * Only mention uninitialized submodules when their
1182 * paths have been specified.
1184 if (suc->warn_if_uninitialized) {
1186 _("Submodule path '%s' not initialized"),
1188 strbuf_addch(out, '\n');
1190 _("Maybe you want to use 'update --init'?"));
1191 strbuf_addch(out, '\n');
1196 * Determine whether 'ce' needs to be cloned. If so, prepare the 'child' to
1197 * run the clone. Returns 1 if 'ce' needs to be cloned, 0 otherwise.
1199 static int prepare_to_clone_next_submodule(const struct cache_entry *ce,
1200 struct child_process *child,
1201 struct submodule_update_clone *suc,
1204 const struct submodule *sub = NULL;
1205 const char *url = NULL;
1206 const char *update_string;
1207 enum submodule_update_type update_type;
1209 struct strbuf displaypath_sb = STRBUF_INIT;
1210 struct strbuf sb = STRBUF_INIT;
1211 const char *displaypath = NULL;
1212 int needs_cloning = 0;
1215 if (suc->recursive_prefix)
1216 strbuf_addf(&sb, "%s/%s", suc->recursive_prefix, ce->name);
1218 strbuf_addstr(&sb, ce->name);
1219 strbuf_addf(out, _("Skipping unmerged submodule %s"), sb.buf);
1220 strbuf_addch(out, '\n');
1224 sub = submodule_from_path(&null_oid, ce->name);
1226 if (suc->recursive_prefix)
1227 displaypath = relative_path(suc->recursive_prefix,
1228 ce->name, &displaypath_sb);
1230 displaypath = ce->name;
1233 next_submodule_warn_missing(suc, out, displaypath);
1237 key = xstrfmt("submodule.%s.update", sub->name);
1238 if (!repo_config_get_string_const(the_repository, key, &update_string)) {
1239 update_type = parse_submodule_update_type(update_string);
1241 update_type = sub->update_strategy.type;
1245 if (suc->update.type == SM_UPDATE_NONE
1246 || (suc->update.type == SM_UPDATE_UNSPECIFIED
1247 && update_type == SM_UPDATE_NONE)) {
1248 strbuf_addf(out, _("Skipping submodule '%s'"), displaypath);
1249 strbuf_addch(out, '\n');
1253 /* Check if the submodule has been initialized. */
1254 if (!is_submodule_active(the_repository, ce->name)) {
1255 next_submodule_warn_missing(suc, out, displaypath);
1260 strbuf_addf(&sb, "submodule.%s.url", sub->name);
1261 if (repo_config_get_string_const(the_repository, sb.buf, &url))
1265 strbuf_addf(&sb, "%s/.git", ce->name);
1266 needs_cloning = !file_exists(sb.buf);
1269 strbuf_addf(&sb, "%06o %s %d %d\t%s\n", ce->ce_mode,
1270 oid_to_hex(&ce->oid), ce_stage(ce),
1271 needs_cloning, ce->name);
1272 string_list_append(&suc->projectlines, sb.buf);
1278 child->no_stdin = 1;
1279 child->stdout_to_stderr = 1;
1281 argv_array_push(&child->args, "submodule--helper");
1282 argv_array_push(&child->args, "clone");
1284 argv_array_push(&child->args, "--progress");
1286 argv_array_push(&child->args, "--quiet");
1288 argv_array_pushl(&child->args, "--prefix", suc->prefix, NULL);
1289 if (suc->recommend_shallow && sub->recommend_shallow == 1)
1290 argv_array_push(&child->args, "--depth=1");
1291 argv_array_pushl(&child->args, "--path", sub->path, NULL);
1292 argv_array_pushl(&child->args, "--name", sub->name, NULL);
1293 argv_array_pushl(&child->args, "--url", url, NULL);
1294 if (suc->references.nr) {
1295 struct string_list_item *item;
1296 for_each_string_list_item(item, &suc->references)
1297 argv_array_pushl(&child->args, "--reference", item->string, NULL);
1300 argv_array_push(&child->args, suc->depth);
1303 strbuf_reset(&displaypath_sb);
1306 return needs_cloning;
1309 static int update_clone_get_next_task(struct child_process *child,
1314 struct submodule_update_clone *suc = suc_cb;
1315 const struct cache_entry *ce;
1318 for (; suc->current < suc->list.nr; suc->current++) {
1319 ce = suc->list.entries[suc->current];
1320 if (prepare_to_clone_next_submodule(ce, child, suc, err)) {
1321 int *p = xmalloc(sizeof(*p));
1330 * The loop above tried cloning each submodule once, now try the
1331 * stragglers again, which we can imagine as an extension of the
1334 index = suc->current - suc->list.nr;
1335 if (index < suc->failed_clones_nr) {
1337 ce = suc->failed_clones[index];
1338 if (!prepare_to_clone_next_submodule(ce, child, suc, err)) {
1340 strbuf_addstr(err, "BUG: submodule considered for "
1341 "cloning, doesn't need cloning "
1345 p = xmalloc(sizeof(*p));
1355 static int update_clone_start_failure(struct strbuf *err,
1359 struct submodule_update_clone *suc = suc_cb;
1364 static int update_clone_task_finished(int result,
1369 const struct cache_entry *ce;
1370 struct submodule_update_clone *suc = suc_cb;
1372 int *idxP = idx_task_cb;
1379 if (idx < suc->list.nr) {
1380 ce = suc->list.entries[idx];
1381 strbuf_addf(err, _("Failed to clone '%s'. Retry scheduled"),
1383 strbuf_addch(err, '\n');
1384 ALLOC_GROW(suc->failed_clones,
1385 suc->failed_clones_nr + 1,
1386 suc->failed_clones_alloc);
1387 suc->failed_clones[suc->failed_clones_nr++] = ce;
1390 idx -= suc->list.nr;
1391 ce = suc->failed_clones[idx];
1392 strbuf_addf(err, _("Failed to clone '%s' a second time, aborting"),
1394 strbuf_addch(err, '\n');
1402 static int gitmodules_update_clone_config(const char *var, const char *value,
1406 if (!strcmp(var, "submodule.fetchjobs"))
1407 *max_jobs = parse_submodule_fetchjobs(var, value);
1411 static int update_clone(int argc, const char **argv, const char *prefix)
1413 const char *update = NULL;
1415 struct string_list_item *item;
1416 struct pathspec pathspec;
1417 struct submodule_update_clone suc = SUBMODULE_UPDATE_CLONE_INIT;
1419 struct option module_update_clone_options[] = {
1420 OPT_STRING(0, "prefix", &prefix,
1422 N_("path into the working tree")),
1423 OPT_STRING(0, "recursive-prefix", &suc.recursive_prefix,
1425 N_("path into the working tree, across nested "
1426 "submodule boundaries")),
1427 OPT_STRING(0, "update", &update,
1429 N_("rebase, merge, checkout or none")),
1430 OPT_STRING_LIST(0, "reference", &suc.references, N_("repo"),
1431 N_("reference repository")),
1432 OPT_STRING(0, "depth", &suc.depth, "<depth>",
1433 N_("Create a shallow clone truncated to the "
1434 "specified number of revisions")),
1435 OPT_INTEGER('j', "jobs", &max_jobs,
1436 N_("parallel jobs")),
1437 OPT_BOOL(0, "recommend-shallow", &suc.recommend_shallow,
1438 N_("whether the initial clone should follow the shallow recommendation")),
1439 OPT__QUIET(&suc.quiet, N_("don't print cloning progress")),
1440 OPT_BOOL(0, "progress", &suc.progress,
1441 N_("force cloning progress")),
1445 const char *const git_submodule_helper_usage[] = {
1446 N_("git submodule--helper update_clone [--prefix=<path>] [<path>...]"),
1449 suc.prefix = prefix;
1451 config_from_gitmodules(gitmodules_update_clone_config, &max_jobs);
1452 git_config(gitmodules_update_clone_config, &max_jobs);
1454 argc = parse_options(argc, argv, prefix, module_update_clone_options,
1455 git_submodule_helper_usage, 0);
1458 if (parse_submodule_update_strategy(update, &suc.update) < 0)
1459 die(_("bad value for update parameter"));
1461 if (module_list_compute(argc, argv, prefix, &pathspec, &suc.list) < 0)
1465 suc.warn_if_uninitialized = 1;
1467 run_processes_parallel(max_jobs,
1468 update_clone_get_next_task,
1469 update_clone_start_failure,
1470 update_clone_task_finished,
1474 * We saved the output and put it out all at once now.
1476 * - the listener does not have to interleave their (checkout)
1477 * work with our fetching. The writes involved in a
1478 * checkout involve more straightforward sequential I/O.
1479 * - the listener can avoid doing any work if fetching failed.
1484 for_each_string_list_item(item, &suc.projectlines)
1485 fprintf(stdout, "%s", item->string);
1490 static int resolve_relative_path(int argc, const char **argv, const char *prefix)
1492 struct strbuf sb = STRBUF_INIT;
1494 die("submodule--helper relative-path takes exactly 2 arguments, got %d", argc);
1496 printf("%s", relative_path(argv[1], argv[2], &sb));
1497 strbuf_release(&sb);
1501 static const char *remote_submodule_branch(const char *path)
1503 const struct submodule *sub;
1504 const char *branch = NULL;
1507 sub = submodule_from_path(&null_oid, path);
1511 key = xstrfmt("submodule.%s.branch", sub->name);
1512 if (repo_config_get_string_const(the_repository, key, &branch))
1513 branch = sub->branch;
1519 if (!strcmp(branch, ".")) {
1520 const char *refname = resolve_ref_unsafe("HEAD", 0, NULL, NULL);
1523 die(_("No such ref: %s"), "HEAD");
1526 if (!strcmp(refname, "HEAD"))
1527 die(_("Submodule (%s) branch configured to inherit "
1528 "branch from superproject, but the superproject "
1529 "is not on any branch"), sub->name);
1531 if (!skip_prefix(refname, "refs/heads/", &refname))
1532 die(_("Expecting a full ref name, got %s"), refname);
1539 static int resolve_remote_submodule_branch(int argc, const char **argv,
1543 struct strbuf sb = STRBUF_INIT;
1545 die("submodule--helper remote-branch takes exactly one arguments, got %d", argc);
1547 ret = remote_submodule_branch(argv[1]);
1549 die("submodule %s doesn't exist", argv[1]);
1552 strbuf_release(&sb);
1556 static int push_check(int argc, const char **argv, const char *prefix)
1558 struct remote *remote;
1559 const char *superproject_head;
1561 int detached_head = 0;
1562 struct object_id head_oid;
1565 die("submodule--helper push-check requires at least 2 arguments");
1568 * superproject's resolved head ref.
1569 * if HEAD then the superproject is in a detached head state, otherwise
1570 * it will be the resolved head ref.
1572 superproject_head = argv[1];
1575 /* Get the submodule's head ref and determine if it is detached */
1576 head = resolve_refdup("HEAD", 0, &head_oid, NULL);
1578 die(_("Failed to resolve HEAD as a valid ref."));
1579 if (!strcmp(head, "HEAD"))
1583 * The remote must be configured.
1584 * This is to avoid pushing to the exact same URL as the parent.
1586 remote = pushremote_get(argv[1]);
1587 if (!remote || remote->origin == REMOTE_UNCONFIGURED)
1588 die("remote '%s' not configured", argv[1]);
1590 /* Check the refspec */
1592 int i, refspec_nr = argc - 2;
1593 struct ref *local_refs = get_local_heads();
1594 struct refspec *refspec = parse_push_refspec(refspec_nr,
1597 for (i = 0; i < refspec_nr; i++) {
1598 struct refspec *rs = refspec + i;
1600 if (rs->pattern || rs->matching)
1603 /* LHS must match a single ref */
1604 switch (count_refspec_match(rs->src, local_refs, NULL)) {
1609 * If LHS matches 'HEAD' then we need to ensure
1610 * that it matches the same named branch
1611 * checked out in the superproject.
1613 if (!strcmp(rs->src, "HEAD")) {
1614 if (!detached_head &&
1615 !strcmp(head, superproject_head))
1617 die("HEAD does not match the named branch in the superproject");
1621 die("src refspec '%s' must name a ref",
1625 free_refspec(refspec_nr, refspec);
1632 static int absorb_git_dirs(int argc, const char **argv, const char *prefix)
1635 struct pathspec pathspec;
1636 struct module_list list = MODULE_LIST_INIT;
1637 unsigned flags = ABSORB_GITDIR_RECURSE_SUBMODULES;
1639 struct option embed_gitdir_options[] = {
1640 OPT_STRING(0, "prefix", &prefix,
1642 N_("path into the working tree")),
1643 OPT_BIT(0, "--recursive", &flags, N_("recurse into submodules"),
1644 ABSORB_GITDIR_RECURSE_SUBMODULES),
1648 const char *const git_submodule_helper_usage[] = {
1649 N_("git submodule--helper embed-git-dir [<path>...]"),
1653 argc = parse_options(argc, argv, prefix, embed_gitdir_options,
1654 git_submodule_helper_usage, 0);
1656 if (module_list_compute(argc, argv, prefix, &pathspec, &list) < 0)
1659 for (i = 0; i < list.nr; i++)
1660 absorb_git_dir_into_superproject(prefix,
1661 list.entries[i]->name, flags);
1666 static int is_active(int argc, const char **argv, const char *prefix)
1669 die("submodule--helper is-active takes exactly 1 argument");
1671 return !is_submodule_active(the_repository, argv[1]);
1674 #define SUPPORT_SUPER_PREFIX (1<<0)
1678 int (*fn)(int, const char **, const char *);
1682 static struct cmd_struct commands[] = {
1683 {"list", module_list, 0},
1684 {"name", module_name, 0},
1685 {"clone", module_clone, 0},
1686 {"update-clone", update_clone, 0},
1687 {"relative-path", resolve_relative_path, 0},
1688 {"resolve-relative-url", resolve_relative_url, 0},
1689 {"resolve-relative-url-test", resolve_relative_url_test, 0},
1690 {"init", module_init, SUPPORT_SUPER_PREFIX},
1691 {"status", module_status, SUPPORT_SUPER_PREFIX},
1692 {"print-default-remote", print_default_remote, 0},
1693 {"sync", module_sync, SUPPORT_SUPER_PREFIX},
1694 {"remote-branch", resolve_remote_submodule_branch, 0},
1695 {"push-check", push_check, 0},
1696 {"absorb-git-dirs", absorb_git_dirs, SUPPORT_SUPER_PREFIX},
1697 {"is-active", is_active, 0},
1700 int cmd_submodule__helper(int argc, const char **argv, const char *prefix)
1703 if (argc < 2 || !strcmp(argv[1], "-h"))
1704 usage("git submodule--helper <command>");
1706 for (i = 0; i < ARRAY_SIZE(commands); i++) {
1707 if (!strcmp(argv[1], commands[i].cmd)) {
1708 if (get_super_prefix() &&
1709 !(commands[i].option & SUPPORT_SUPER_PREFIX))
1710 die(_("%s doesn't support --super-prefix"),
1712 return commands[i].fn(argc - 1, argv + 1, prefix);
1716 die(_("'%s' is not a valid submodule--helper "
1717 "subcommand"), argv[1]);