1 #define USE_THE_INDEX_COMPATIBILITY_MACROS
3 #include "repository.h"
6 #include "parse-options.h"
10 #include "submodule.h"
11 #include "submodule-config.h"
12 #include "string-list.h"
13 #include "run-command.h"
21 #include "object-store.h"
25 #define OPT_QUIET (1 << 0)
26 #define OPT_CACHED (1 << 1)
27 #define OPT_RECURSIVE (1 << 2)
28 #define OPT_FORCE (1 << 3)
30 typedef void (*each_submodule_fn)(const struct cache_entry *list_item,
33 static char *get_default_remote(void)
35 char *dest = NULL, *ret;
36 struct strbuf sb = STRBUF_INIT;
37 const char *refname = resolve_ref_unsafe("HEAD", 0, NULL, NULL);
40 die(_("No such ref: %s"), "HEAD");
43 if (!strcmp(refname, "HEAD"))
44 return xstrdup("origin");
46 if (!skip_prefix(refname, "refs/heads/", &refname))
47 die(_("Expecting a full ref name, got %s"), refname);
49 strbuf_addf(&sb, "branch.%s.remote", refname);
50 if (git_config_get_string(sb.buf, &dest))
51 ret = xstrdup("origin");
59 static int print_default_remote(int argc, const char **argv, const char *prefix)
64 die(_("submodule--helper print-default-remote takes no arguments"));
66 remote = get_default_remote();
68 printf("%s\n", remote);
74 static int starts_with_dot_slash(const char *str)
76 return str[0] == '.' && is_dir_sep(str[1]);
79 static int starts_with_dot_dot_slash(const char *str)
81 return str[0] == '.' && str[1] == '.' && is_dir_sep(str[2]);
85 * Returns 1 if it was the last chop before ':'.
87 static int chop_last_dir(char **remoteurl, int is_relative)
89 char *rfind = find_last_dir_sep(*remoteurl);
95 rfind = strrchr(*remoteurl, ':');
101 if (is_relative || !strcmp(".", *remoteurl))
102 die(_("cannot strip one component off url '%s'"),
106 *remoteurl = xstrdup(".");
111 * The `url` argument is the URL that navigates to the submodule origin
112 * repo. When relative, this URL is relative to the superproject origin
113 * URL repo. The `up_path` argument, if specified, is the relative
114 * path that navigates from the submodule working tree to the superproject
115 * working tree. Returns the origin URL of the submodule.
117 * Return either an absolute URL or filesystem path (if the superproject
118 * origin URL is an absolute URL or filesystem path, respectively) or a
119 * relative file system path (if the superproject origin URL is a relative
122 * When the output is a relative file system path, the path is either
123 * relative to the submodule working tree, if up_path is specified, or to
124 * the superproject working tree otherwise.
126 * NEEDSWORK: This works incorrectly on the domain and protocol part.
127 * remote_url url outcome expectation
128 * http://a.com/b ../c http://a.com/c as is
129 * http://a.com/b/ ../c http://a.com/c same as previous line, but
130 * ignore trailing slash in url
131 * http://a.com/b ../../c http://c error out
132 * http://a.com/b ../../../c http:/c error out
133 * http://a.com/b ../../../../c http:c error out
134 * http://a.com/b ../../../../../c .:c error out
135 * NEEDSWORK: Given how chop_last_dir() works, this function is broken
136 * when a local part has a colon in its path component, too.
138 static char *relative_url(const char *remote_url,
145 char *remoteurl = xstrdup(remote_url);
146 struct strbuf sb = STRBUF_INIT;
147 size_t len = strlen(remoteurl);
149 if (is_dir_sep(remoteurl[len-1]))
150 remoteurl[len-1] = '\0';
152 if (!url_is_local_not_ssh(remoteurl) || is_absolute_path(remoteurl))
157 * Prepend a './' to ensure all relative
158 * remoteurls start with './' or '../'
160 if (!starts_with_dot_slash(remoteurl) &&
161 !starts_with_dot_dot_slash(remoteurl)) {
163 strbuf_addf(&sb, "./%s", remoteurl);
165 remoteurl = strbuf_detach(&sb, NULL);
169 * When the url starts with '../', remove that and the
170 * last directory in remoteurl.
173 if (starts_with_dot_dot_slash(url)) {
175 colonsep |= chop_last_dir(&remoteurl, is_relative);
176 } else if (starts_with_dot_slash(url))
182 strbuf_addf(&sb, "%s%s%s", remoteurl, colonsep ? ":" : "/", url);
183 if (ends_with(url, "/"))
184 strbuf_setlen(&sb, sb.len - 1);
187 if (starts_with_dot_slash(sb.buf))
188 out = xstrdup(sb.buf + 2);
190 out = xstrdup(sb.buf);
193 if (!up_path || !is_relative)
196 strbuf_addf(&sb, "%s%s", up_path, out);
198 return strbuf_detach(&sb, NULL);
201 static int resolve_relative_url(int argc, const char **argv, const char *prefix)
203 char *remoteurl = NULL;
204 char *remote = get_default_remote();
205 const char *up_path = NULL;
208 struct strbuf sb = STRBUF_INIT;
210 if (argc != 2 && argc != 3)
211 die("resolve-relative-url only accepts one or two arguments");
214 strbuf_addf(&sb, "remote.%s.url", remote);
217 if (git_config_get_string(sb.buf, &remoteurl))
218 /* the repository is its own authoritative upstream */
219 remoteurl = xgetcwd();
224 res = relative_url(remoteurl, url, up_path);
231 static int resolve_relative_url_test(int argc, const char **argv, const char *prefix)
233 char *remoteurl, *res;
234 const char *up_path, *url;
237 die("resolve-relative-url-test only accepts three arguments: <up_path> <remoteurl> <url>");
240 remoteurl = xstrdup(argv[2]);
243 if (!strcmp(up_path, "(null)"))
246 res = relative_url(remoteurl, url, up_path);
253 /* the result should be freed by the caller. */
254 static char *get_submodule_displaypath(const char *path, const char *prefix)
256 const char *super_prefix = get_super_prefix();
258 if (prefix && super_prefix) {
259 BUG("cannot have prefix '%s' and superprefix '%s'",
260 prefix, super_prefix);
262 struct strbuf sb = STRBUF_INIT;
263 char *displaypath = xstrdup(relative_path(path, prefix, &sb));
266 } else if (super_prefix) {
267 return xstrfmt("%s%s", super_prefix, path);
269 return xstrdup(path);
273 static char *compute_rev_name(const char *sub_path, const char* object_id)
275 struct strbuf sb = STRBUF_INIT;
278 static const char *describe_bare[] = { NULL };
280 static const char *describe_tags[] = { "--tags", NULL };
282 static const char *describe_contains[] = { "--contains", NULL };
284 static const char *describe_all_always[] = { "--all", "--always", NULL };
286 static const char **describe_argv[] = { describe_bare, describe_tags,
288 describe_all_always, NULL };
290 for (d = describe_argv; *d; d++) {
291 struct child_process cp = CHILD_PROCESS_INIT;
292 prepare_submodule_repo_env(&cp.env_array);
297 strvec_push(&cp.args, "describe");
298 strvec_pushv(&cp.args, *d);
299 strvec_push(&cp.args, object_id);
301 if (!capture_command(&cp, &sb, 0)) {
302 strbuf_strip_suffix(&sb, "\n");
303 return strbuf_detach(&sb, NULL);
312 const struct cache_entry **entries;
315 #define MODULE_LIST_INIT { NULL, 0, 0 }
317 static int module_list_compute(int argc, const char **argv,
319 struct pathspec *pathspec,
320 struct module_list *list)
323 char *ps_matched = NULL;
324 parse_pathspec(pathspec, 0,
325 PATHSPEC_PREFER_FULL,
329 ps_matched = xcalloc(pathspec->nr, 1);
331 if (read_cache() < 0)
332 die(_("index file corrupt"));
334 for (i = 0; i < active_nr; i++) {
335 const struct cache_entry *ce = active_cache[i];
337 if (!match_pathspec(&the_index, pathspec, ce->name, ce_namelen(ce),
339 !S_ISGITLINK(ce->ce_mode))
342 ALLOC_GROW(list->entries, list->nr + 1, list->alloc);
343 list->entries[list->nr++] = ce;
344 while (i + 1 < active_nr &&
345 !strcmp(ce->name, active_cache[i + 1]->name))
347 * Skip entries with the same name in different stages
348 * to make sure an entry is returned only once.
353 if (ps_matched && report_path_error(ps_matched, pathspec))
361 static void module_list_active(struct module_list *list)
364 struct module_list active_modules = MODULE_LIST_INIT;
366 for (i = 0; i < list->nr; i++) {
367 const struct cache_entry *ce = list->entries[i];
369 if (!is_submodule_active(the_repository, ce->name))
372 ALLOC_GROW(active_modules.entries,
373 active_modules.nr + 1,
374 active_modules.alloc);
375 active_modules.entries[active_modules.nr++] = ce;
379 *list = active_modules;
382 static char *get_up_path(const char *path)
385 struct strbuf sb = STRBUF_INIT;
387 for (i = count_slashes(path); i; i--)
388 strbuf_addstr(&sb, "../");
391 * Check if 'path' ends with slash or not
392 * for having the same output for dir/sub_dir
395 if (!is_dir_sep(path[strlen(path) - 1]))
396 strbuf_addstr(&sb, "../");
398 return strbuf_detach(&sb, NULL);
401 static int module_list(int argc, const char **argv, const char *prefix)
404 struct pathspec pathspec;
405 struct module_list list = MODULE_LIST_INIT;
407 struct option module_list_options[] = {
408 OPT_STRING(0, "prefix", &prefix,
410 N_("alternative anchor for relative paths")),
414 const char *const git_submodule_helper_usage[] = {
415 N_("git submodule--helper list [--prefix=<path>] [<path>...]"),
419 argc = parse_options(argc, argv, prefix, module_list_options,
420 git_submodule_helper_usage, 0);
422 if (module_list_compute(argc, argv, prefix, &pathspec, &list) < 0)
425 for (i = 0; i < list.nr; i++) {
426 const struct cache_entry *ce = list.entries[i];
429 printf("%06o %s U\t", ce->ce_mode,
430 oid_to_hex(null_oid()));
432 printf("%06o %s %d\t", ce->ce_mode,
433 oid_to_hex(&ce->oid), ce_stage(ce));
435 fprintf(stdout, "%s\n", ce->name);
440 static void for_each_listed_submodule(const struct module_list *list,
441 each_submodule_fn fn, void *cb_data)
444 for (i = 0; i < list->nr; i++)
445 fn(list->entries[i], cb_data);
455 #define FOREACH_CB_INIT { 0 }
457 static void runcommand_in_submodule_cb(const struct cache_entry *list_item,
460 struct foreach_cb *info = cb_data;
461 const char *path = list_item->name;
462 const struct object_id *ce_oid = &list_item->oid;
464 const struct submodule *sub;
465 struct child_process cp = CHILD_PROCESS_INIT;
468 displaypath = get_submodule_displaypath(path, info->prefix);
470 sub = submodule_from_path(the_repository, null_oid(), path);
473 die(_("No url found for submodule path '%s' in .gitmodules"),
476 if (!is_submodule_populated_gently(path, NULL))
479 prepare_submodule_repo_env(&cp.env_array);
482 * For the purpose of executing <command> in the submodule,
483 * separate shell is used for the purpose of running the
490 * NEEDSWORK: the command currently has access to the variables $name,
491 * $sm_path, $displaypath, $sha1 and $toplevel only when the command
492 * contains a single argument. This is done for maintaining a faithful
493 * translation from shell script.
495 if (info->argc == 1) {
496 char *toplevel = xgetcwd();
497 struct strbuf sb = STRBUF_INIT;
499 strvec_pushf(&cp.env_array, "name=%s", sub->name);
500 strvec_pushf(&cp.env_array, "sm_path=%s", path);
501 strvec_pushf(&cp.env_array, "displaypath=%s", displaypath);
502 strvec_pushf(&cp.env_array, "sha1=%s",
504 strvec_pushf(&cp.env_array, "toplevel=%s", toplevel);
507 * Since the path variable was accessible from the script
508 * before porting, it is also made available after porting.
509 * The environment variable "PATH" has a very special purpose
510 * on windows. And since environment variables are
511 * case-insensitive in windows, it interferes with the
512 * existing PATH variable. Hence, to avoid that, we expose
513 * path via the args strvec and not via env_array.
515 sq_quote_buf(&sb, path);
516 strvec_pushf(&cp.args, "path=%s; %s",
517 sb.buf, info->argv[0]);
521 strvec_pushv(&cp.args, info->argv);
525 printf(_("Entering '%s'\n"), displaypath);
527 if (info->argv[0] && run_command(&cp))
528 die(_("run_command returned non-zero status for %s\n."),
531 if (info->recursive) {
532 struct child_process cpr = CHILD_PROCESS_INIT;
536 prepare_submodule_repo_env(&cpr.env_array);
538 strvec_pushl(&cpr.args, "--super-prefix", NULL);
539 strvec_pushf(&cpr.args, "%s/", displaypath);
540 strvec_pushl(&cpr.args, "submodule--helper", "foreach", "--recursive",
544 strvec_push(&cpr.args, "--quiet");
546 strvec_push(&cpr.args, "--");
547 strvec_pushv(&cpr.args, info->argv);
549 if (run_command(&cpr))
550 die(_("run_command returned non-zero status while "
551 "recursing in the nested submodules of %s\n."),
559 static int module_foreach(int argc, const char **argv, const char *prefix)
561 struct foreach_cb info = FOREACH_CB_INIT;
562 struct pathspec pathspec;
563 struct module_list list = MODULE_LIST_INIT;
565 struct option module_foreach_options[] = {
566 OPT__QUIET(&info.quiet, N_("suppress output of entering each submodule command")),
567 OPT_BOOL(0, "recursive", &info.recursive,
568 N_("recurse into nested submodules")),
572 const char *const git_submodule_helper_usage[] = {
573 N_("git submodule--helper foreach [--quiet] [--recursive] [--] <command>"),
577 argc = parse_options(argc, argv, prefix, module_foreach_options,
578 git_submodule_helper_usage, 0);
580 if (module_list_compute(0, NULL, prefix, &pathspec, &list) < 0)
585 info.prefix = prefix;
587 for_each_listed_submodule(&list, runcommand_in_submodule_cb, &info);
592 static char *compute_submodule_clone_url(const char *rel_url)
594 char *remoteurl, *relurl;
595 char *remote = get_default_remote();
596 struct strbuf remotesb = STRBUF_INIT;
598 strbuf_addf(&remotesb, "remote.%s.url", remote);
599 if (git_config_get_string(remotesb.buf, &remoteurl)) {
600 warning(_("could not look up configuration '%s'. Assuming this repository is its own authoritative upstream."), remotesb.buf);
601 remoteurl = xgetcwd();
603 relurl = relative_url(remoteurl, rel_url, NULL);
607 strbuf_release(&remotesb);
616 #define INIT_CB_INIT { NULL, 0 }
618 static void init_submodule(const char *path, const char *prefix,
621 const struct submodule *sub;
622 struct strbuf sb = STRBUF_INIT;
623 char *upd = NULL, *url = NULL, *displaypath;
625 displaypath = get_submodule_displaypath(path, prefix);
627 sub = submodule_from_path(the_repository, null_oid(), path);
630 die(_("No url found for submodule path '%s' in .gitmodules"),
634 * NEEDSWORK: In a multi-working-tree world, this needs to be
635 * set in the per-worktree config.
637 * Set active flag for the submodule being initialized
639 if (!is_submodule_active(the_repository, path)) {
640 strbuf_addf(&sb, "submodule.%s.active", sub->name);
641 git_config_set_gently(sb.buf, "true");
646 * Copy url setting when it is not set yet.
647 * To look up the url in .git/config, we must not fall back to
648 * .gitmodules, so look it up directly.
650 strbuf_addf(&sb, "submodule.%s.url", sub->name);
651 if (git_config_get_string(sb.buf, &url)) {
653 die(_("No url found for submodule path '%s' in .gitmodules"),
656 url = xstrdup(sub->url);
658 /* Possibly a url relative to parent */
659 if (starts_with_dot_dot_slash(url) ||
660 starts_with_dot_slash(url)) {
662 url = compute_submodule_clone_url(oldurl);
666 if (git_config_set_gently(sb.buf, url))
667 die(_("Failed to register url for submodule path '%s'"),
669 if (!(flags & OPT_QUIET))
671 _("Submodule '%s' (%s) registered for path '%s'\n"),
672 sub->name, url, displaypath);
676 /* Copy "update" setting when it is not set yet */
677 strbuf_addf(&sb, "submodule.%s.update", sub->name);
678 if (git_config_get_string(sb.buf, &upd) &&
679 sub->update_strategy.type != SM_UPDATE_UNSPECIFIED) {
680 if (sub->update_strategy.type == SM_UPDATE_COMMAND) {
681 fprintf(stderr, _("warning: command update mode suggested for submodule '%s'\n"),
683 upd = xstrdup("none");
685 upd = xstrdup(submodule_strategy_to_string(&sub->update_strategy));
687 if (git_config_set_gently(sb.buf, upd))
688 die(_("Failed to register update mode for submodule path '%s'"), displaypath);
696 static void init_submodule_cb(const struct cache_entry *list_item, void *cb_data)
698 struct init_cb *info = cb_data;
699 init_submodule(list_item->name, info->prefix, info->flags);
702 static int module_init(int argc, const char **argv, const char *prefix)
704 struct init_cb info = INIT_CB_INIT;
705 struct pathspec pathspec;
706 struct module_list list = MODULE_LIST_INIT;
709 struct option module_init_options[] = {
710 OPT__QUIET(&quiet, N_("suppress output for initializing a submodule")),
714 const char *const git_submodule_helper_usage[] = {
715 N_("git submodule--helper init [<options>] [<path>]"),
719 argc = parse_options(argc, argv, prefix, module_init_options,
720 git_submodule_helper_usage, 0);
722 if (module_list_compute(argc, argv, prefix, &pathspec, &list) < 0)
726 * If there are no path args and submodule.active is set then,
727 * by default, only initialize 'active' modules.
729 if (!argc && git_config_get_value_multi("submodule.active"))
730 module_list_active(&list);
732 info.prefix = prefix;
734 info.flags |= OPT_QUIET;
736 for_each_listed_submodule(&list, init_submodule_cb, &info);
745 #define STATUS_CB_INIT { NULL, 0 }
747 static void print_status(unsigned int flags, char state, const char *path,
748 const struct object_id *oid, const char *displaypath)
750 if (flags & OPT_QUIET)
753 printf("%c%s %s", state, oid_to_hex(oid), displaypath);
755 if (state == ' ' || state == '+') {
756 const char *name = compute_rev_name(path, oid_to_hex(oid));
759 printf(" (%s)", name);
765 static int handle_submodule_head_ref(const char *refname,
766 const struct object_id *oid, int flags,
769 struct object_id *output = cb_data;
776 static void status_submodule(const char *path, const struct object_id *ce_oid,
777 unsigned int ce_flags, const char *prefix,
781 struct strvec diff_files_args = STRVEC_INIT;
783 int diff_files_result;
784 struct strbuf buf = STRBUF_INIT;
787 if (!submodule_from_path(the_repository, null_oid(), path))
788 die(_("no submodule mapping found in .gitmodules for path '%s'"),
791 displaypath = get_submodule_displaypath(path, prefix);
793 if ((CE_STAGEMASK & ce_flags) >> CE_STAGESHIFT) {
794 print_status(flags, 'U', path, null_oid(), displaypath);
798 strbuf_addf(&buf, "%s/.git", path);
799 git_dir = read_gitfile(buf.buf);
803 if (!is_submodule_active(the_repository, path) ||
804 !is_git_directory(git_dir)) {
805 print_status(flags, '-', path, ce_oid, displaypath);
806 strbuf_release(&buf);
809 strbuf_release(&buf);
811 strvec_pushl(&diff_files_args, "diff-files",
812 "--ignore-submodules=dirty", "--quiet", "--",
815 git_config(git_diff_basic_config, NULL);
817 repo_init_revisions(the_repository, &rev, NULL);
819 diff_files_args.nr = setup_revisions(diff_files_args.nr,
822 diff_files_result = run_diff_files(&rev, 0);
824 if (!diff_result_code(&rev.diffopt, diff_files_result)) {
825 print_status(flags, ' ', path, ce_oid,
827 } else if (!(flags & OPT_CACHED)) {
828 struct object_id oid;
829 struct ref_store *refs = get_submodule_ref_store(path);
832 print_status(flags, '-', path, ce_oid, displaypath);
835 if (refs_head_ref(refs, handle_submodule_head_ref, &oid))
836 die(_("could not resolve HEAD ref inside the "
837 "submodule '%s'"), path);
839 print_status(flags, '+', path, &oid, displaypath);
841 print_status(flags, '+', path, ce_oid, displaypath);
844 if (flags & OPT_RECURSIVE) {
845 struct child_process cpr = CHILD_PROCESS_INIT;
849 prepare_submodule_repo_env(&cpr.env_array);
851 strvec_push(&cpr.args, "--super-prefix");
852 strvec_pushf(&cpr.args, "%s/", displaypath);
853 strvec_pushl(&cpr.args, "submodule--helper", "status",
854 "--recursive", NULL);
856 if (flags & OPT_CACHED)
857 strvec_push(&cpr.args, "--cached");
859 if (flags & OPT_QUIET)
860 strvec_push(&cpr.args, "--quiet");
862 if (run_command(&cpr))
863 die(_("failed to recurse into submodule '%s'"), path);
867 strvec_clear(&diff_files_args);
871 static void status_submodule_cb(const struct cache_entry *list_item,
874 struct status_cb *info = cb_data;
875 status_submodule(list_item->name, &list_item->oid, list_item->ce_flags,
876 info->prefix, info->flags);
879 static int module_status(int argc, const char **argv, const char *prefix)
881 struct status_cb info = STATUS_CB_INIT;
882 struct pathspec pathspec;
883 struct module_list list = MODULE_LIST_INIT;
886 struct option module_status_options[] = {
887 OPT__QUIET(&quiet, N_("suppress submodule status output")),
888 OPT_BIT(0, "cached", &info.flags, N_("use commit stored in the index instead of the one stored in the submodule HEAD"), OPT_CACHED),
889 OPT_BIT(0, "recursive", &info.flags, N_("recurse into nested submodules"), OPT_RECURSIVE),
893 const char *const git_submodule_helper_usage[] = {
894 N_("git submodule status [--quiet] [--cached] [--recursive] [<path>...]"),
898 argc = parse_options(argc, argv, prefix, module_status_options,
899 git_submodule_helper_usage, 0);
901 if (module_list_compute(argc, argv, prefix, &pathspec, &list) < 0)
904 info.prefix = prefix;
906 info.flags |= OPT_QUIET;
908 for_each_listed_submodule(&list, status_submodule_cb, &info);
913 static int module_name(int argc, const char **argv, const char *prefix)
915 const struct submodule *sub;
918 usage(_("git submodule--helper name <path>"));
920 sub = submodule_from_path(the_repository, null_oid(), argv[1]);
923 die(_("no submodule mapping found in .gitmodules for path '%s'"),
926 printf("%s\n", sub->name);
932 unsigned int mod_src;
933 unsigned int mod_dst;
934 struct object_id oid_src;
935 struct object_id oid_dst;
939 #define MODULE_CB_INIT { 0, 0, NULL, NULL, '\0', NULL }
941 struct module_cb_list {
942 struct module_cb **entries;
945 #define MODULE_CB_LIST_INIT { NULL, 0, 0 }
951 unsigned int cached: 1;
952 unsigned int for_status: 1;
953 unsigned int files: 1;
956 #define SUMMARY_CB_INIT { 0, NULL, NULL, 0, 0, 0, 0 }
963 static char *verify_submodule_committish(const char *sm_path,
964 const char *committish)
966 struct child_process cp_rev_parse = CHILD_PROCESS_INIT;
967 struct strbuf result = STRBUF_INIT;
969 cp_rev_parse.git_cmd = 1;
970 cp_rev_parse.dir = sm_path;
971 prepare_submodule_repo_env(&cp_rev_parse.env_array);
972 strvec_pushl(&cp_rev_parse.args, "rev-parse", "-q", "--short", NULL);
973 strvec_pushf(&cp_rev_parse.args, "%s^0", committish);
974 strvec_push(&cp_rev_parse.args, "--");
976 if (capture_command(&cp_rev_parse, &result, 0))
979 strbuf_trim_trailing_newline(&result);
980 return strbuf_detach(&result, NULL);
983 static void print_submodule_summary(struct summary_cb *info, char *errmsg,
984 int total_commits, const char *displaypath,
985 const char *src_abbrev, const char *dst_abbrev,
988 if (p->status == 'T') {
989 if (S_ISGITLINK(p->mod_dst))
990 printf(_("* %s %s(blob)->%s(submodule)"),
991 displaypath, src_abbrev, dst_abbrev);
993 printf(_("* %s %s(submodule)->%s(blob)"),
994 displaypath, src_abbrev, dst_abbrev);
996 printf("* %s %s...%s",
997 displaypath, src_abbrev, dst_abbrev);
1000 if (total_commits < 0)
1003 printf(" (%d):\n", total_commits);
1006 printf(_("%s"), errmsg);
1007 } else if (total_commits > 0) {
1008 struct child_process cp_log = CHILD_PROCESS_INIT;
1011 cp_log.dir = p->sm_path;
1012 prepare_submodule_repo_env(&cp_log.env_array);
1013 strvec_pushl(&cp_log.args, "log", NULL);
1015 if (S_ISGITLINK(p->mod_src) && S_ISGITLINK(p->mod_dst)) {
1016 if (info->summary_limit > 0)
1017 strvec_pushf(&cp_log.args, "-%d",
1018 info->summary_limit);
1020 strvec_pushl(&cp_log.args, "--pretty= %m %s",
1021 "--first-parent", NULL);
1022 strvec_pushf(&cp_log.args, "%s...%s",
1023 src_abbrev, dst_abbrev);
1024 } else if (S_ISGITLINK(p->mod_dst)) {
1025 strvec_pushl(&cp_log.args, "--pretty= > %s",
1026 "-1", dst_abbrev, NULL);
1028 strvec_pushl(&cp_log.args, "--pretty= < %s",
1029 "-1", src_abbrev, NULL);
1031 run_command(&cp_log);
1036 static void generate_submodule_summary(struct summary_cb *info,
1037 struct module_cb *p)
1039 char *displaypath, *src_abbrev = NULL, *dst_abbrev;
1040 int missing_src = 0, missing_dst = 0;
1041 char *errmsg = NULL;
1042 int total_commits = -1;
1044 if (!info->cached && oideq(&p->oid_dst, null_oid())) {
1045 if (S_ISGITLINK(p->mod_dst)) {
1046 struct ref_store *refs = get_submodule_ref_store(p->sm_path);
1048 refs_head_ref(refs, handle_submodule_head_ref, &p->oid_dst);
1049 } else if (S_ISLNK(p->mod_dst) || S_ISREG(p->mod_dst)) {
1051 int fd = open(p->sm_path, O_RDONLY);
1053 if (fd < 0 || fstat(fd, &st) < 0 ||
1054 index_fd(&the_index, &p->oid_dst, fd, &st, OBJ_BLOB,
1056 error(_("couldn't hash object from '%s'"), p->sm_path);
1058 /* for a submodule removal (mode:0000000), don't warn */
1060 warning(_("unexpected mode %o\n"), p->mod_dst);
1064 if (S_ISGITLINK(p->mod_src)) {
1065 if (p->status != 'D')
1066 src_abbrev = verify_submodule_committish(p->sm_path,
1067 oid_to_hex(&p->oid_src));
1071 * As `rev-parse` failed, we fallback to getting
1072 * the abbreviated hash using oid_src. We do
1073 * this as we might still need the abbreviated
1074 * hash in cases like a submodule type change, etc.
1076 src_abbrev = xstrndup(oid_to_hex(&p->oid_src), 7);
1080 * The source does not point to a submodule.
1081 * So, we fallback to getting the abbreviation using
1082 * oid_src as we might still need the abbreviated
1083 * hash in cases like submodule add, etc.
1085 src_abbrev = xstrndup(oid_to_hex(&p->oid_src), 7);
1088 if (S_ISGITLINK(p->mod_dst)) {
1089 dst_abbrev = verify_submodule_committish(p->sm_path,
1090 oid_to_hex(&p->oid_dst));
1094 * As `rev-parse` failed, we fallback to getting
1095 * the abbreviated hash using oid_dst. We do
1096 * this as we might still need the abbreviated
1097 * hash in cases like a submodule type change, etc.
1099 dst_abbrev = xstrndup(oid_to_hex(&p->oid_dst), 7);
1103 * The destination does not point to a submodule.
1104 * So, we fallback to getting the abbreviation using
1105 * oid_dst as we might still need the abbreviated
1106 * hash in cases like a submodule removal, etc.
1108 dst_abbrev = xstrndup(oid_to_hex(&p->oid_dst), 7);
1111 displaypath = get_submodule_displaypath(p->sm_path, info->prefix);
1113 if (!missing_src && !missing_dst) {
1114 struct child_process cp_rev_list = CHILD_PROCESS_INIT;
1115 struct strbuf sb_rev_list = STRBUF_INIT;
1117 strvec_pushl(&cp_rev_list.args, "rev-list",
1118 "--first-parent", "--count", NULL);
1119 if (S_ISGITLINK(p->mod_src) && S_ISGITLINK(p->mod_dst))
1120 strvec_pushf(&cp_rev_list.args, "%s...%s",
1121 src_abbrev, dst_abbrev);
1123 strvec_push(&cp_rev_list.args, S_ISGITLINK(p->mod_src) ?
1124 src_abbrev : dst_abbrev);
1125 strvec_push(&cp_rev_list.args, "--");
1127 cp_rev_list.git_cmd = 1;
1128 cp_rev_list.dir = p->sm_path;
1129 prepare_submodule_repo_env(&cp_rev_list.env_array);
1131 if (!capture_command(&cp_rev_list, &sb_rev_list, 0))
1132 total_commits = atoi(sb_rev_list.buf);
1134 strbuf_release(&sb_rev_list);
1137 * Don't give error msg for modification whose dst is not
1138 * submodule, i.e., deleted or changed to blob
1140 if (S_ISGITLINK(p->mod_dst)) {
1141 struct strbuf errmsg_str = STRBUF_INIT;
1142 if (missing_src && missing_dst) {
1143 strbuf_addf(&errmsg_str, " Warn: %s doesn't contain commits %s and %s\n",
1144 displaypath, oid_to_hex(&p->oid_src),
1145 oid_to_hex(&p->oid_dst));
1147 strbuf_addf(&errmsg_str, " Warn: %s doesn't contain commit %s\n",
1148 displaypath, missing_src ?
1149 oid_to_hex(&p->oid_src) :
1150 oid_to_hex(&p->oid_dst));
1152 errmsg = strbuf_detach(&errmsg_str, NULL);
1156 print_submodule_summary(info, errmsg, total_commits,
1157 displaypath, src_abbrev,
1165 static void prepare_submodule_summary(struct summary_cb *info,
1166 struct module_cb_list *list)
1169 for (i = 0; i < list->nr; i++) {
1170 const struct submodule *sub;
1171 struct module_cb *p = list->entries[i];
1172 struct strbuf sm_gitdir = STRBUF_INIT;
1174 if (p->status == 'D' || p->status == 'T') {
1175 generate_submodule_summary(info, p);
1179 if (info->for_status && p->status != 'A' &&
1180 (sub = submodule_from_path(the_repository,
1181 null_oid(), p->sm_path))) {
1182 char *config_key = NULL;
1186 config_key = xstrfmt("submodule.%s.ignore",
1188 if (!git_config_get_string_tmp(config_key, &value))
1189 ignore_all = !strcmp(value, "all");
1190 else if (sub->ignore)
1191 ignore_all = !strcmp(sub->ignore, "all");
1198 /* Also show added or modified modules which are checked out */
1199 strbuf_addstr(&sm_gitdir, p->sm_path);
1200 if (is_nonbare_repository_dir(&sm_gitdir))
1201 generate_submodule_summary(info, p);
1202 strbuf_release(&sm_gitdir);
1206 static void submodule_summary_callback(struct diff_queue_struct *q,
1207 struct diff_options *options,
1211 struct module_cb_list *list = data;
1212 for (i = 0; i < q->nr; i++) {
1213 struct diff_filepair *p = q->queue[i];
1214 struct module_cb *temp;
1216 if (!S_ISGITLINK(p->one->mode) && !S_ISGITLINK(p->two->mode))
1218 temp = (struct module_cb*)malloc(sizeof(struct module_cb));
1219 temp->mod_src = p->one->mode;
1220 temp->mod_dst = p->two->mode;
1221 temp->oid_src = p->one->oid;
1222 temp->oid_dst = p->two->oid;
1223 temp->status = p->status;
1224 temp->sm_path = xstrdup(p->one->path);
1226 ALLOC_GROW(list->entries, list->nr + 1, list->alloc);
1227 list->entries[list->nr++] = temp;
1231 static const char *get_diff_cmd(enum diff_cmd diff_cmd)
1234 case DIFF_INDEX: return "diff-index";
1235 case DIFF_FILES: return "diff-files";
1236 default: BUG("bad diff_cmd value %d", diff_cmd);
1240 static int compute_summary_module_list(struct object_id *head_oid,
1241 struct summary_cb *info,
1242 enum diff_cmd diff_cmd)
1244 struct strvec diff_args = STRVEC_INIT;
1245 struct rev_info rev;
1246 struct module_cb_list list = MODULE_CB_LIST_INIT;
1248 strvec_push(&diff_args, get_diff_cmd(diff_cmd));
1250 strvec_push(&diff_args, "--cached");
1251 strvec_pushl(&diff_args, "--ignore-submodules=dirty", "--raw", NULL);
1253 strvec_push(&diff_args, oid_to_hex(head_oid));
1254 strvec_push(&diff_args, "--");
1256 strvec_pushv(&diff_args, info->argv);
1258 git_config(git_diff_basic_config, NULL);
1259 init_revisions(&rev, info->prefix);
1261 precompose_argv_prefix(diff_args.nr, diff_args.v, NULL);
1262 setup_revisions(diff_args.nr, diff_args.v, &rev, NULL);
1263 rev.diffopt.output_format = DIFF_FORMAT_NO_OUTPUT | DIFF_FORMAT_CALLBACK;
1264 rev.diffopt.format_callback = submodule_summary_callback;
1265 rev.diffopt.format_callback_data = &list;
1267 if (!info->cached) {
1268 if (diff_cmd == DIFF_INDEX)
1270 if (read_cache_preload(&rev.diffopt.pathspec) < 0) {
1271 perror("read_cache_preload");
1274 } else if (read_cache() < 0) {
1275 perror("read_cache");
1279 if (diff_cmd == DIFF_INDEX)
1280 run_diff_index(&rev, info->cached);
1282 run_diff_files(&rev, 0);
1283 prepare_submodule_summary(info, &list);
1284 strvec_clear(&diff_args);
1288 static int module_summary(int argc, const char **argv, const char *prefix)
1290 struct summary_cb info = SUMMARY_CB_INIT;
1294 int summary_limit = -1;
1295 enum diff_cmd diff_cmd = DIFF_INDEX;
1296 struct object_id head_oid;
1299 struct option module_summary_options[] = {
1300 OPT_BOOL(0, "cached", &cached,
1301 N_("use the commit stored in the index instead of the submodule HEAD")),
1302 OPT_BOOL(0, "files", &files,
1303 N_("compare the commit in the index with that in the submodule HEAD")),
1304 OPT_BOOL(0, "for-status", &for_status,
1305 N_("skip submodules with 'ignore_config' value set to 'all'")),
1306 OPT_INTEGER('n', "summary-limit", &summary_limit,
1307 N_("limit the summary size")),
1311 const char *const git_submodule_helper_usage[] = {
1312 N_("git submodule--helper summary [<options>] [<commit>] [--] [<path>]"),
1316 argc = parse_options(argc, argv, prefix, module_summary_options,
1317 git_submodule_helper_usage, 0);
1322 if (!get_oid(argc ? argv[0] : "HEAD", &head_oid)) {
1327 } else if (!argc || !strcmp(argv[0], "HEAD")) {
1328 /* before the first commit: compare with an empty tree */
1329 oidcpy(&head_oid, the_hash_algo->empty_tree);
1335 if (get_oid("HEAD", &head_oid))
1336 die(_("could not fetch a revision for HEAD"));
1341 die(_("--cached and --files are mutually exclusive"));
1342 diff_cmd = DIFF_FILES;
1347 info.prefix = prefix;
1348 info.cached = !!cached;
1349 info.files = !!files;
1350 info.for_status = !!for_status;
1351 info.summary_limit = summary_limit;
1353 ret = compute_summary_module_list((diff_cmd == DIFF_INDEX) ? &head_oid : NULL,
1362 #define SYNC_CB_INIT { NULL, 0 }
1364 static void sync_submodule(const char *path, const char *prefix,
1367 const struct submodule *sub;
1368 char *remote_key = NULL;
1369 char *sub_origin_url, *super_config_url, *displaypath;
1370 struct strbuf sb = STRBUF_INIT;
1371 struct child_process cp = CHILD_PROCESS_INIT;
1372 char *sub_config_path = NULL;
1374 if (!is_submodule_active(the_repository, path))
1377 sub = submodule_from_path(the_repository, null_oid(), path);
1379 if (sub && sub->url) {
1380 if (starts_with_dot_dot_slash(sub->url) ||
1381 starts_with_dot_slash(sub->url)) {
1382 char *remote_url, *up_path;
1383 char *remote = get_default_remote();
1384 strbuf_addf(&sb, "remote.%s.url", remote);
1386 if (git_config_get_string(sb.buf, &remote_url))
1387 remote_url = xgetcwd();
1389 up_path = get_up_path(path);
1390 sub_origin_url = relative_url(remote_url, sub->url, up_path);
1391 super_config_url = relative_url(remote_url, sub->url, NULL);
1397 sub_origin_url = xstrdup(sub->url);
1398 super_config_url = xstrdup(sub->url);
1401 sub_origin_url = xstrdup("");
1402 super_config_url = xstrdup("");
1405 displaypath = get_submodule_displaypath(path, prefix);
1407 if (!(flags & OPT_QUIET))
1408 printf(_("Synchronizing submodule url for '%s'\n"),
1412 strbuf_addf(&sb, "submodule.%s.url", sub->name);
1413 if (git_config_set_gently(sb.buf, super_config_url))
1414 die(_("failed to register url for submodule path '%s'"),
1417 if (!is_submodule_populated_gently(path, NULL))
1420 prepare_submodule_repo_env(&cp.env_array);
1423 strvec_pushl(&cp.args, "submodule--helper",
1424 "print-default-remote", NULL);
1427 if (capture_command(&cp, &sb, 0))
1428 die(_("failed to get the default remote for submodule '%s'"),
1431 strbuf_strip_suffix(&sb, "\n");
1432 remote_key = xstrfmt("remote.%s.url", sb.buf);
1435 submodule_to_gitdir(&sb, path);
1436 strbuf_addstr(&sb, "/config");
1438 if (git_config_set_in_file_gently(sb.buf, remote_key, sub_origin_url))
1439 die(_("failed to update remote for submodule '%s'"),
1442 if (flags & OPT_RECURSIVE) {
1443 struct child_process cpr = CHILD_PROCESS_INIT;
1447 prepare_submodule_repo_env(&cpr.env_array);
1449 strvec_push(&cpr.args, "--super-prefix");
1450 strvec_pushf(&cpr.args, "%s/", displaypath);
1451 strvec_pushl(&cpr.args, "submodule--helper", "sync",
1452 "--recursive", NULL);
1454 if (flags & OPT_QUIET)
1455 strvec_push(&cpr.args, "--quiet");
1457 if (run_command(&cpr))
1458 die(_("failed to recurse into submodule '%s'"),
1463 free(super_config_url);
1464 free(sub_origin_url);
1465 strbuf_release(&sb);
1468 free(sub_config_path);
1471 static void sync_submodule_cb(const struct cache_entry *list_item, void *cb_data)
1473 struct sync_cb *info = cb_data;
1474 sync_submodule(list_item->name, info->prefix, info->flags);
1477 static int module_sync(int argc, const char **argv, const char *prefix)
1479 struct sync_cb info = SYNC_CB_INIT;
1480 struct pathspec pathspec;
1481 struct module_list list = MODULE_LIST_INIT;
1485 struct option module_sync_options[] = {
1486 OPT__QUIET(&quiet, N_("suppress output of synchronizing submodule url")),
1487 OPT_BOOL(0, "recursive", &recursive,
1488 N_("recurse into nested submodules")),
1492 const char *const git_submodule_helper_usage[] = {
1493 N_("git submodule--helper sync [--quiet] [--recursive] [<path>]"),
1497 argc = parse_options(argc, argv, prefix, module_sync_options,
1498 git_submodule_helper_usage, 0);
1500 if (module_list_compute(argc, argv, prefix, &pathspec, &list) < 0)
1503 info.prefix = prefix;
1505 info.flags |= OPT_QUIET;
1507 info.flags |= OPT_RECURSIVE;
1509 for_each_listed_submodule(&list, sync_submodule_cb, &info);
1518 #define DEINIT_CB_INIT { NULL, 0 }
1520 static void deinit_submodule(const char *path, const char *prefix,
1523 const struct submodule *sub;
1524 char *displaypath = NULL;
1525 struct child_process cp_config = CHILD_PROCESS_INIT;
1526 struct strbuf sb_config = STRBUF_INIT;
1527 char *sub_git_dir = xstrfmt("%s/.git", path);
1529 sub = submodule_from_path(the_repository, null_oid(), path);
1531 if (!sub || !sub->name)
1534 displaypath = get_submodule_displaypath(path, prefix);
1536 /* remove the submodule work tree (unless the user already did it) */
1537 if (is_directory(path)) {
1538 struct strbuf sb_rm = STRBUF_INIT;
1542 * protect submodules containing a .git directory
1543 * NEEDSWORK: instead of dying, automatically call
1544 * absorbgitdirs and (possibly) warn.
1546 if (is_directory(sub_git_dir))
1547 die(_("Submodule work tree '%s' contains a .git "
1548 "directory (use 'rm -rf' if you really want "
1549 "to remove it including all of its history)"),
1552 if (!(flags & OPT_FORCE)) {
1553 struct child_process cp_rm = CHILD_PROCESS_INIT;
1555 strvec_pushl(&cp_rm.args, "rm", "-qn",
1558 if (run_command(&cp_rm))
1559 die(_("Submodule work tree '%s' contains local "
1560 "modifications; use '-f' to discard them"),
1564 strbuf_addstr(&sb_rm, path);
1566 if (!remove_dir_recursively(&sb_rm, 0))
1567 format = _("Cleared directory '%s'\n");
1569 format = _("Could not remove submodule work tree '%s'\n");
1571 if (!(flags & OPT_QUIET))
1572 printf(format, displaypath);
1574 submodule_unset_core_worktree(sub);
1576 strbuf_release(&sb_rm);
1579 if (mkdir(path, 0777))
1580 printf(_("could not create empty submodule directory %s"),
1583 cp_config.git_cmd = 1;
1584 strvec_pushl(&cp_config.args, "config", "--get-regexp", NULL);
1585 strvec_pushf(&cp_config.args, "submodule.%s\\.", sub->name);
1587 /* remove the .git/config entries (unless the user already did it) */
1588 if (!capture_command(&cp_config, &sb_config, 0) && sb_config.len) {
1589 char *sub_key = xstrfmt("submodule.%s", sub->name);
1591 * remove the whole section so we have a clean state when
1592 * the user later decides to init this submodule again
1594 git_config_rename_section_in_file(NULL, sub_key, NULL);
1595 if (!(flags & OPT_QUIET))
1596 printf(_("Submodule '%s' (%s) unregistered for path '%s'\n"),
1597 sub->name, sub->url, displaypath);
1604 strbuf_release(&sb_config);
1607 static void deinit_submodule_cb(const struct cache_entry *list_item,
1610 struct deinit_cb *info = cb_data;
1611 deinit_submodule(list_item->name, info->prefix, info->flags);
1614 static int module_deinit(int argc, const char **argv, const char *prefix)
1616 struct deinit_cb info = DEINIT_CB_INIT;
1617 struct pathspec pathspec;
1618 struct module_list list = MODULE_LIST_INIT;
1623 struct option module_deinit_options[] = {
1624 OPT__QUIET(&quiet, N_("suppress submodule status output")),
1625 OPT__FORCE(&force, N_("remove submodule working trees even if they contain local changes"), 0),
1626 OPT_BOOL(0, "all", &all, N_("unregister all submodules")),
1630 const char *const git_submodule_helper_usage[] = {
1631 N_("git submodule deinit [--quiet] [-f | --force] [--all | [--] [<path>...]]"),
1635 argc = parse_options(argc, argv, prefix, module_deinit_options,
1636 git_submodule_helper_usage, 0);
1639 error("pathspec and --all are incompatible");
1640 usage_with_options(git_submodule_helper_usage,
1641 module_deinit_options);
1645 die(_("Use '--all' if you really want to deinitialize all submodules"));
1647 if (module_list_compute(argc, argv, prefix, &pathspec, &list) < 0)
1650 info.prefix = prefix;
1652 info.flags |= OPT_QUIET;
1654 info.flags |= OPT_FORCE;
1656 for_each_listed_submodule(&list, deinit_submodule_cb, &info);
1661 struct module_clone_data {
1667 struct string_list reference;
1668 unsigned int quiet: 1;
1669 unsigned int progress: 1;
1670 unsigned int dissociate: 1;
1671 unsigned int require_init: 1;
1674 #define MODULE_CLONE_DATA_INIT { .reference = STRING_LIST_INIT_NODUP, .single_branch = -1 }
1676 struct submodule_alternate_setup {
1677 const char *submodule_name;
1678 enum SUBMODULE_ALTERNATE_ERROR_MODE {
1679 SUBMODULE_ALTERNATE_ERROR_DIE,
1680 SUBMODULE_ALTERNATE_ERROR_INFO,
1681 SUBMODULE_ALTERNATE_ERROR_IGNORE
1683 struct string_list *reference;
1685 #define SUBMODULE_ALTERNATE_SETUP_INIT { NULL, \
1686 SUBMODULE_ALTERNATE_ERROR_IGNORE, NULL }
1688 static const char alternate_error_advice[] = N_(
1689 "An alternate computed from a superproject's alternate is invalid.\n"
1690 "To allow Git to clone without an alternate in such a case, set\n"
1691 "submodule.alternateErrorStrategy to 'info' or, equivalently, clone with\n"
1692 "'--reference-if-able' instead of '--reference'."
1695 static int add_possible_reference_from_superproject(
1696 struct object_directory *odb, void *sas_cb)
1698 struct submodule_alternate_setup *sas = sas_cb;
1702 * If the alternate object store is another repository, try the
1703 * standard layout with .git/(modules/<name>)+/objects
1705 if (strip_suffix(odb->path, "/objects", &len)) {
1707 struct strbuf sb = STRBUF_INIT;
1708 struct strbuf err = STRBUF_INIT;
1709 strbuf_add(&sb, odb->path, len);
1712 * We need to end the new path with '/' to mark it as a dir,
1713 * otherwise a submodule name containing '/' will be broken
1714 * as the last part of a missing submodule reference would
1715 * be taken as a file name.
1717 strbuf_addf(&sb, "/modules/%s/", sas->submodule_name);
1719 sm_alternate = compute_alternate_path(sb.buf, &err);
1721 string_list_append(sas->reference, xstrdup(sb.buf));
1724 switch (sas->error_mode) {
1725 case SUBMODULE_ALTERNATE_ERROR_DIE:
1726 if (advice_submodule_alternate_error_strategy_die)
1727 advise(_(alternate_error_advice));
1728 die(_("submodule '%s' cannot add alternate: %s"),
1729 sas->submodule_name, err.buf);
1730 case SUBMODULE_ALTERNATE_ERROR_INFO:
1731 fprintf_ln(stderr, _("submodule '%s' cannot add alternate: %s"),
1732 sas->submodule_name, err.buf);
1733 case SUBMODULE_ALTERNATE_ERROR_IGNORE:
1737 strbuf_release(&sb);
1743 static void prepare_possible_alternates(const char *sm_name,
1744 struct string_list *reference)
1746 char *sm_alternate = NULL, *error_strategy = NULL;
1747 struct submodule_alternate_setup sas = SUBMODULE_ALTERNATE_SETUP_INIT;
1749 git_config_get_string("submodule.alternateLocation", &sm_alternate);
1753 git_config_get_string("submodule.alternateErrorStrategy", &error_strategy);
1755 if (!error_strategy)
1756 error_strategy = xstrdup("die");
1758 sas.submodule_name = sm_name;
1759 sas.reference = reference;
1760 if (!strcmp(error_strategy, "die"))
1761 sas.error_mode = SUBMODULE_ALTERNATE_ERROR_DIE;
1762 else if (!strcmp(error_strategy, "info"))
1763 sas.error_mode = SUBMODULE_ALTERNATE_ERROR_INFO;
1764 else if (!strcmp(error_strategy, "ignore"))
1765 sas.error_mode = SUBMODULE_ALTERNATE_ERROR_IGNORE;
1767 die(_("Value '%s' for submodule.alternateErrorStrategy is not recognized"), error_strategy);
1769 if (!strcmp(sm_alternate, "superproject"))
1770 foreach_alt_odb(add_possible_reference_from_superproject, &sas);
1771 else if (!strcmp(sm_alternate, "no"))
1774 die(_("Value '%s' for submodule.alternateLocation is not recognized"), sm_alternate);
1777 free(error_strategy);
1780 static int clone_submodule(struct module_clone_data *clone_data)
1782 char *p, *sm_gitdir;
1783 char *sm_alternate = NULL, *error_strategy = NULL;
1784 struct strbuf sb = STRBUF_INIT;
1785 struct child_process cp = CHILD_PROCESS_INIT;
1787 strbuf_addf(&sb, "%s/modules/%s", get_git_dir(), clone_data->name);
1788 sm_gitdir = absolute_pathdup(sb.buf);
1791 if (!is_absolute_path(clone_data->path)) {
1792 strbuf_addf(&sb, "%s/%s", get_git_work_tree(), clone_data->path);
1793 clone_data->path = strbuf_detach(&sb, NULL);
1795 clone_data->path = xstrdup(clone_data->path);
1798 if (validate_submodule_git_dir(sm_gitdir, clone_data->name) < 0)
1799 die(_("refusing to create/use '%s' in another submodule's "
1800 "git dir"), sm_gitdir);
1802 if (!file_exists(sm_gitdir)) {
1803 if (safe_create_leading_directories_const(sm_gitdir) < 0)
1804 die(_("could not create directory '%s'"), sm_gitdir);
1806 prepare_possible_alternates(clone_data->name, &clone_data->reference);
1808 strvec_push(&cp.args, "clone");
1809 strvec_push(&cp.args, "--no-checkout");
1810 if (clone_data->quiet)
1811 strvec_push(&cp.args, "--quiet");
1812 if (clone_data->progress)
1813 strvec_push(&cp.args, "--progress");
1814 if (clone_data->depth && *(clone_data->depth))
1815 strvec_pushl(&cp.args, "--depth", clone_data->depth, NULL);
1816 if (clone_data->reference.nr) {
1817 struct string_list_item *item;
1818 for_each_string_list_item(item, &clone_data->reference)
1819 strvec_pushl(&cp.args, "--reference",
1820 item->string, NULL);
1822 if (clone_data->dissociate)
1823 strvec_push(&cp.args, "--dissociate");
1824 if (sm_gitdir && *sm_gitdir)
1825 strvec_pushl(&cp.args, "--separate-git-dir", sm_gitdir, NULL);
1826 if (clone_data->single_branch >= 0)
1827 strvec_push(&cp.args, clone_data->single_branch ?
1829 "--no-single-branch");
1831 strvec_push(&cp.args, "--");
1832 strvec_push(&cp.args, clone_data->url);
1833 strvec_push(&cp.args, clone_data->path);
1836 prepare_submodule_repo_env(&cp.env_array);
1839 if(run_command(&cp))
1840 die(_("clone of '%s' into submodule path '%s' failed"),
1841 clone_data->url, clone_data->path);
1843 if (clone_data->require_init && !access(clone_data->path, X_OK) &&
1844 !is_empty_dir(clone_data->path))
1845 die(_("directory not empty: '%s'"), clone_data->path);
1846 if (safe_create_leading_directories_const(clone_data->path) < 0)
1847 die(_("could not create directory '%s'"), clone_data->path);
1848 strbuf_addf(&sb, "%s/index", sm_gitdir);
1849 unlink_or_warn(sb.buf);
1853 connect_work_tree_and_git_dir(clone_data->path, sm_gitdir, 0);
1855 p = git_pathdup_submodule(clone_data->path, "config");
1857 die(_("could not get submodule directory for '%s'"), clone_data->path);
1859 /* setup alternateLocation and alternateErrorStrategy in the cloned submodule if needed */
1860 git_config_get_string("submodule.alternateLocation", &sm_alternate);
1862 git_config_set_in_file(p, "submodule.alternateLocation",
1864 git_config_get_string("submodule.alternateErrorStrategy", &error_strategy);
1866 git_config_set_in_file(p, "submodule.alternateErrorStrategy",
1869 git_config_set_in_file(p, "submodule.superprojectGitdir",
1870 relative_path(absolute_path(get_git_dir()),
1871 clone_data->path, &sb));
1874 free(error_strategy);
1876 strbuf_release(&sb);
1882 static int module_clone(int argc, const char **argv, const char *prefix)
1884 int dissociate = 0, quiet = 0, progress = 0, require_init = 0;
1885 struct module_clone_data clone_data = MODULE_CLONE_DATA_INIT;
1887 struct option module_clone_options[] = {
1888 OPT_STRING(0, "prefix", &clone_data.prefix,
1890 N_("alternative anchor for relative paths")),
1891 OPT_STRING(0, "path", &clone_data.path,
1893 N_("where the new submodule will be cloned to")),
1894 OPT_STRING(0, "name", &clone_data.name,
1896 N_("name of the new submodule")),
1897 OPT_STRING(0, "url", &clone_data.url,
1899 N_("url where to clone the submodule from")),
1900 OPT_STRING_LIST(0, "reference", &clone_data.reference,
1902 N_("reference repository")),
1903 OPT_BOOL(0, "dissociate", &dissociate,
1904 N_("use --reference only while cloning")),
1905 OPT_STRING(0, "depth", &clone_data.depth,
1907 N_("depth for shallow clones")),
1908 OPT__QUIET(&quiet, "Suppress output for cloning a submodule"),
1909 OPT_BOOL(0, "progress", &progress,
1910 N_("force cloning progress")),
1911 OPT_BOOL(0, "require-init", &require_init,
1912 N_("disallow cloning into non-empty directory")),
1913 OPT_BOOL(0, "single-branch", &clone_data.single_branch,
1914 N_("clone only one branch, HEAD or --branch")),
1918 const char *const git_submodule_helper_usage[] = {
1919 N_("git submodule--helper clone [--prefix=<path>] [--quiet] "
1920 "[--reference <repository>] [--name <name>] [--depth <depth>] "
1921 "[--single-branch] "
1922 "--url <url> --path <path>"),
1926 argc = parse_options(argc, argv, prefix, module_clone_options,
1927 git_submodule_helper_usage, 0);
1929 clone_data.dissociate = !!dissociate;
1930 clone_data.quiet = !!quiet;
1931 clone_data.progress = !!progress;
1932 clone_data.require_init = !!require_init;
1934 if (argc || !clone_data.url || !clone_data.path || !*(clone_data.path))
1935 usage_with_options(git_submodule_helper_usage,
1936 module_clone_options);
1938 clone_submodule(&clone_data);
1942 static void determine_submodule_update_strategy(struct repository *r,
1946 struct submodule_update_strategy *out)
1948 const struct submodule *sub = submodule_from_path(r, null_oid(), path);
1952 key = xstrfmt("submodule.%s.update", sub->name);
1955 if (parse_submodule_update_strategy(update, out) < 0)
1956 die(_("Invalid update mode '%s' for submodule path '%s'"),
1958 } else if (!repo_config_get_string_tmp(r, key, &val)) {
1959 if (parse_submodule_update_strategy(val, out) < 0)
1960 die(_("Invalid update mode '%s' configured for submodule path '%s'"),
1962 } else if (sub->update_strategy.type != SM_UPDATE_UNSPECIFIED) {
1963 if (sub->update_strategy.type == SM_UPDATE_COMMAND)
1964 BUG("how did we read update = !command from .gitmodules?");
1965 out->type = sub->update_strategy.type;
1966 out->command = sub->update_strategy.command;
1968 out->type = SM_UPDATE_CHECKOUT;
1971 (out->type == SM_UPDATE_MERGE ||
1972 out->type == SM_UPDATE_REBASE ||
1973 out->type == SM_UPDATE_NONE))
1974 out->type = SM_UPDATE_CHECKOUT;
1979 static int module_update_module_mode(int argc, const char **argv, const char *prefix)
1981 const char *path, *update = NULL;
1983 struct submodule_update_strategy update_strategy = { .type = SM_UPDATE_CHECKOUT };
1985 if (argc < 3 || argc > 4)
1986 die("submodule--helper update-module-clone expects <just-cloned> <path> [<update>]");
1988 just_cloned = git_config_int("just_cloned", argv[1]);
1994 determine_submodule_update_strategy(the_repository,
1995 just_cloned, path, update,
1997 fputs(submodule_strategy_to_string(&update_strategy), stdout);
2002 struct update_clone_data {
2003 const struct submodule *sub;
2004 struct object_id oid;
2005 unsigned just_cloned;
2008 struct submodule_update_clone {
2009 /* index into 'list', the list of submodules to look into for cloning */
2011 struct module_list list;
2012 unsigned warn_if_uninitialized : 1;
2014 /* update parameter passed via commandline */
2015 struct submodule_update_strategy update;
2017 /* configuration parameters which are passed on to the children */
2020 int recommend_shallow;
2021 struct string_list references;
2023 unsigned require_init;
2025 const char *recursive_prefix;
2029 /* to be consumed by git-submodule.sh */
2030 struct update_clone_data *update_clone;
2031 int update_clone_nr; int update_clone_alloc;
2033 /* If we want to stop as fast as possible and return an error */
2034 unsigned quickstop : 1;
2036 /* failed clones to be retried again */
2037 const struct cache_entry **failed_clones;
2038 int failed_clones_nr, failed_clones_alloc;
2042 #define SUBMODULE_UPDATE_CLONE_INIT { \
2043 .list = MODULE_LIST_INIT, \
2044 .update = SUBMODULE_UPDATE_STRATEGY_INIT, \
2045 .recommend_shallow = -1, \
2046 .references = STRING_LIST_INIT_DUP, \
2047 .single_branch = -1, \
2052 static void next_submodule_warn_missing(struct submodule_update_clone *suc,
2053 struct strbuf *out, const char *displaypath)
2056 * Only mention uninitialized submodules when their
2057 * paths have been specified.
2059 if (suc->warn_if_uninitialized) {
2061 _("Submodule path '%s' not initialized"),
2063 strbuf_addch(out, '\n');
2065 _("Maybe you want to use 'update --init'?"));
2066 strbuf_addch(out, '\n');
2071 * Determine whether 'ce' needs to be cloned. If so, prepare the 'child' to
2072 * run the clone. Returns 1 if 'ce' needs to be cloned, 0 otherwise.
2074 static int prepare_to_clone_next_submodule(const struct cache_entry *ce,
2075 struct child_process *child,
2076 struct submodule_update_clone *suc,
2079 const struct submodule *sub = NULL;
2080 const char *url = NULL;
2081 const char *update_string;
2082 enum submodule_update_type update_type;
2084 struct strbuf displaypath_sb = STRBUF_INIT;
2085 struct strbuf sb = STRBUF_INIT;
2086 const char *displaypath = NULL;
2087 int needs_cloning = 0;
2088 int need_free_url = 0;
2091 if (suc->recursive_prefix)
2092 strbuf_addf(&sb, "%s/%s", suc->recursive_prefix, ce->name);
2094 strbuf_addstr(&sb, ce->name);
2095 strbuf_addf(out, _("Skipping unmerged submodule %s"), sb.buf);
2096 strbuf_addch(out, '\n');
2100 sub = submodule_from_path(the_repository, null_oid(), ce->name);
2102 if (suc->recursive_prefix)
2103 displaypath = relative_path(suc->recursive_prefix,
2104 ce->name, &displaypath_sb);
2106 displaypath = ce->name;
2109 next_submodule_warn_missing(suc, out, displaypath);
2113 key = xstrfmt("submodule.%s.update", sub->name);
2114 if (!repo_config_get_string_tmp(the_repository, key, &update_string)) {
2115 update_type = parse_submodule_update_type(update_string);
2117 update_type = sub->update_strategy.type;
2121 if (suc->update.type == SM_UPDATE_NONE
2122 || (suc->update.type == SM_UPDATE_UNSPECIFIED
2123 && update_type == SM_UPDATE_NONE)) {
2124 strbuf_addf(out, _("Skipping submodule '%s'"), displaypath);
2125 strbuf_addch(out, '\n');
2129 /* Check if the submodule has been initialized. */
2130 if (!is_submodule_active(the_repository, ce->name)) {
2131 next_submodule_warn_missing(suc, out, displaypath);
2136 strbuf_addf(&sb, "submodule.%s.url", sub->name);
2137 if (repo_config_get_string_tmp(the_repository, sb.buf, &url)) {
2138 if (starts_with_dot_slash(sub->url) ||
2139 starts_with_dot_dot_slash(sub->url)) {
2140 url = compute_submodule_clone_url(sub->url);
2147 strbuf_addf(&sb, "%s/.git", ce->name);
2148 needs_cloning = !file_exists(sb.buf);
2150 ALLOC_GROW(suc->update_clone, suc->update_clone_nr + 1,
2151 suc->update_clone_alloc);
2152 oidcpy(&suc->update_clone[suc->update_clone_nr].oid, &ce->oid);
2153 suc->update_clone[suc->update_clone_nr].just_cloned = needs_cloning;
2154 suc->update_clone[suc->update_clone_nr].sub = sub;
2155 suc->update_clone_nr++;
2161 child->no_stdin = 1;
2162 child->stdout_to_stderr = 1;
2164 strvec_push(&child->args, "submodule--helper");
2165 strvec_push(&child->args, "clone");
2167 strvec_push(&child->args, "--progress");
2169 strvec_push(&child->args, "--quiet");
2171 strvec_pushl(&child->args, "--prefix", suc->prefix, NULL);
2172 if (suc->recommend_shallow && sub->recommend_shallow == 1)
2173 strvec_push(&child->args, "--depth=1");
2174 if (suc->require_init)
2175 strvec_push(&child->args, "--require-init");
2176 strvec_pushl(&child->args, "--path", sub->path, NULL);
2177 strvec_pushl(&child->args, "--name", sub->name, NULL);
2178 strvec_pushl(&child->args, "--url", url, NULL);
2179 if (suc->references.nr) {
2180 struct string_list_item *item;
2181 for_each_string_list_item(item, &suc->references)
2182 strvec_pushl(&child->args, "--reference", item->string, NULL);
2184 if (suc->dissociate)
2185 strvec_push(&child->args, "--dissociate");
2187 strvec_push(&child->args, suc->depth);
2188 if (suc->single_branch >= 0)
2189 strvec_push(&child->args, suc->single_branch ?
2191 "--no-single-branch");
2194 strbuf_release(&displaypath_sb);
2195 strbuf_release(&sb);
2199 return needs_cloning;
2202 static int update_clone_get_next_task(struct child_process *child,
2207 struct submodule_update_clone *suc = suc_cb;
2208 const struct cache_entry *ce;
2211 for (; suc->current < suc->list.nr; suc->current++) {
2212 ce = suc->list.entries[suc->current];
2213 if (prepare_to_clone_next_submodule(ce, child, suc, err)) {
2214 int *p = xmalloc(sizeof(*p));
2223 * The loop above tried cloning each submodule once, now try the
2224 * stragglers again, which we can imagine as an extension of the
2227 index = suc->current - suc->list.nr;
2228 if (index < suc->failed_clones_nr) {
2230 ce = suc->failed_clones[index];
2231 if (!prepare_to_clone_next_submodule(ce, child, suc, err)) {
2233 strbuf_addstr(err, "BUG: submodule considered for "
2234 "cloning, doesn't need cloning "
2238 p = xmalloc(sizeof(*p));
2248 static int update_clone_start_failure(struct strbuf *err,
2252 struct submodule_update_clone *suc = suc_cb;
2257 static int update_clone_task_finished(int result,
2262 const struct cache_entry *ce;
2263 struct submodule_update_clone *suc = suc_cb;
2265 int *idxP = idx_task_cb;
2272 if (idx < suc->list.nr) {
2273 ce = suc->list.entries[idx];
2274 strbuf_addf(err, _("Failed to clone '%s'. Retry scheduled"),
2276 strbuf_addch(err, '\n');
2277 ALLOC_GROW(suc->failed_clones,
2278 suc->failed_clones_nr + 1,
2279 suc->failed_clones_alloc);
2280 suc->failed_clones[suc->failed_clones_nr++] = ce;
2283 idx -= suc->list.nr;
2284 ce = suc->failed_clones[idx];
2285 strbuf_addf(err, _("Failed to clone '%s' a second time, aborting"),
2287 strbuf_addch(err, '\n');
2295 static int git_update_clone_config(const char *var, const char *value,
2299 if (!strcmp(var, "submodule.fetchjobs"))
2300 *max_jobs = parse_submodule_fetchjobs(var, value);
2304 static void update_submodule(struct update_clone_data *ucd)
2306 fprintf(stdout, "dummy %s %d\t%s\n",
2307 oid_to_hex(&ucd->oid),
2312 static int update_submodules(struct submodule_update_clone *suc)
2316 run_processes_parallel_tr2(suc->max_jobs, update_clone_get_next_task,
2317 update_clone_start_failure, NULL, NULL,
2318 update_clone_task_finished, suc, "submodule",
2322 * We saved the output and put it out all at once now.
2324 * - the listener does not have to interleave their (checkout)
2325 * work with our fetching. The writes involved in a
2326 * checkout involve more straightforward sequential I/O.
2327 * - the listener can avoid doing any work if fetching failed.
2332 for (i = 0; i < suc->update_clone_nr; i++)
2333 update_submodule(&suc->update_clone[i]);
2338 static int update_clone(int argc, const char **argv, const char *prefix)
2340 const char *update = NULL;
2341 struct pathspec pathspec;
2342 struct submodule_update_clone suc = SUBMODULE_UPDATE_CLONE_INIT;
2344 struct option module_update_clone_options[] = {
2345 OPT_STRING(0, "prefix", &prefix,
2347 N_("path into the working tree")),
2348 OPT_STRING(0, "recursive-prefix", &suc.recursive_prefix,
2350 N_("path into the working tree, across nested "
2351 "submodule boundaries")),
2352 OPT_STRING(0, "update", &update,
2354 N_("rebase, merge, checkout or none")),
2355 OPT_STRING_LIST(0, "reference", &suc.references, N_("repo"),
2356 N_("reference repository")),
2357 OPT_BOOL(0, "dissociate", &suc.dissociate,
2358 N_("use --reference only while cloning")),
2359 OPT_STRING(0, "depth", &suc.depth, "<depth>",
2360 N_("create a shallow clone truncated to the "
2361 "specified number of revisions")),
2362 OPT_INTEGER('j', "jobs", &suc.max_jobs,
2363 N_("parallel jobs")),
2364 OPT_BOOL(0, "recommend-shallow", &suc.recommend_shallow,
2365 N_("whether the initial clone should follow the shallow recommendation")),
2366 OPT__QUIET(&suc.quiet, N_("don't print cloning progress")),
2367 OPT_BOOL(0, "progress", &suc.progress,
2368 N_("force cloning progress")),
2369 OPT_BOOL(0, "require-init", &suc.require_init,
2370 N_("disallow cloning into non-empty directory")),
2371 OPT_BOOL(0, "single-branch", &suc.single_branch,
2372 N_("clone only one branch, HEAD or --branch")),
2376 const char *const git_submodule_helper_usage[] = {
2377 N_("git submodule--helper update-clone [--prefix=<path>] [<path>...]"),
2380 suc.prefix = prefix;
2382 update_clone_config_from_gitmodules(&suc.max_jobs);
2383 git_config(git_update_clone_config, &suc.max_jobs);
2385 argc = parse_options(argc, argv, prefix, module_update_clone_options,
2386 git_submodule_helper_usage, 0);
2389 if (parse_submodule_update_strategy(update, &suc.update) < 0)
2390 die(_("bad value for update parameter"));
2392 if (module_list_compute(argc, argv, prefix, &pathspec, &suc.list) < 0)
2396 suc.warn_if_uninitialized = 1;
2398 return update_submodules(&suc);
2401 static int resolve_relative_path(int argc, const char **argv, const char *prefix)
2403 struct strbuf sb = STRBUF_INIT;
2405 die("submodule--helper relative-path takes exactly 2 arguments, got %d", argc);
2407 printf("%s", relative_path(argv[1], argv[2], &sb));
2408 strbuf_release(&sb);
2412 static const char *remote_submodule_branch(const char *path)
2414 const struct submodule *sub;
2415 const char *branch = NULL;
2418 sub = submodule_from_path(the_repository, null_oid(), path);
2422 key = xstrfmt("submodule.%s.branch", sub->name);
2423 if (repo_config_get_string_tmp(the_repository, key, &branch))
2424 branch = sub->branch;
2430 if (!strcmp(branch, ".")) {
2431 const char *refname = resolve_ref_unsafe("HEAD", 0, NULL, NULL);
2434 die(_("No such ref: %s"), "HEAD");
2437 if (!strcmp(refname, "HEAD"))
2438 die(_("Submodule (%s) branch configured to inherit "
2439 "branch from superproject, but the superproject "
2440 "is not on any branch"), sub->name);
2442 if (!skip_prefix(refname, "refs/heads/", &refname))
2443 die(_("Expecting a full ref name, got %s"), refname);
2450 static int resolve_remote_submodule_branch(int argc, const char **argv,
2454 struct strbuf sb = STRBUF_INIT;
2456 die("submodule--helper remote-branch takes exactly one arguments, got %d", argc);
2458 ret = remote_submodule_branch(argv[1]);
2460 die("submodule %s doesn't exist", argv[1]);
2463 strbuf_release(&sb);
2467 static int push_check(int argc, const char **argv, const char *prefix)
2469 struct remote *remote;
2470 const char *superproject_head;
2472 int detached_head = 0;
2473 struct object_id head_oid;
2476 die("submodule--helper push-check requires at least 2 arguments");
2479 * superproject's resolved head ref.
2480 * if HEAD then the superproject is in a detached head state, otherwise
2481 * it will be the resolved head ref.
2483 superproject_head = argv[1];
2486 /* Get the submodule's head ref and determine if it is detached */
2487 head = resolve_refdup("HEAD", 0, &head_oid, NULL);
2489 die(_("Failed to resolve HEAD as a valid ref."));
2490 if (!strcmp(head, "HEAD"))
2494 * The remote must be configured.
2495 * This is to avoid pushing to the exact same URL as the parent.
2497 remote = pushremote_get(argv[1]);
2498 if (!remote || remote->origin == REMOTE_UNCONFIGURED)
2499 die("remote '%s' not configured", argv[1]);
2501 /* Check the refspec */
2504 struct ref *local_refs = get_local_heads();
2505 struct refspec refspec = REFSPEC_INIT_PUSH;
2507 refspec_appendn(&refspec, argv + 2, argc - 2);
2509 for (i = 0; i < refspec.nr; i++) {
2510 const struct refspec_item *rs = &refspec.items[i];
2512 if (rs->pattern || rs->matching)
2515 /* LHS must match a single ref */
2516 switch (count_refspec_match(rs->src, local_refs, NULL)) {
2521 * If LHS matches 'HEAD' then we need to ensure
2522 * that it matches the same named branch
2523 * checked out in the superproject.
2525 if (!strcmp(rs->src, "HEAD")) {
2526 if (!detached_head &&
2527 !strcmp(head, superproject_head))
2529 die("HEAD does not match the named branch in the superproject");
2533 die("src refspec '%s' must name a ref",
2537 refspec_clear(&refspec);
2544 static int ensure_core_worktree(int argc, const char **argv, const char *prefix)
2546 const struct submodule *sub;
2549 struct repository subrepo;
2552 BUG("submodule--helper ensure-core-worktree <path>");
2556 sub = submodule_from_path(the_repository, null_oid(), path);
2558 BUG("We could get the submodule handle before?");
2560 if (repo_submodule_init(&subrepo, the_repository, sub))
2561 die(_("could not get a repository handle for submodule '%s'"), path);
2563 if (!repo_config_get_string_tmp(&subrepo, "core.worktree", &cw)) {
2564 char *cfg_file, *abs_path;
2565 const char *rel_path;
2566 struct strbuf sb = STRBUF_INIT;
2568 cfg_file = repo_git_path(&subrepo, "config");
2570 abs_path = absolute_pathdup(path);
2571 rel_path = relative_path(abs_path, subrepo.gitdir, &sb);
2573 git_config_set_in_file(cfg_file, "core.worktree", rel_path);
2577 strbuf_release(&sb);
2583 static int absorb_git_dirs(int argc, const char **argv, const char *prefix)
2586 struct pathspec pathspec;
2587 struct module_list list = MODULE_LIST_INIT;
2588 unsigned flags = ABSORB_GITDIR_RECURSE_SUBMODULES;
2590 struct option embed_gitdir_options[] = {
2591 OPT_STRING(0, "prefix", &prefix,
2593 N_("path into the working tree")),
2594 OPT_BIT(0, "--recursive", &flags, N_("recurse into submodules"),
2595 ABSORB_GITDIR_RECURSE_SUBMODULES),
2599 const char *const git_submodule_helper_usage[] = {
2600 N_("git submodule--helper absorb-git-dirs [<options>] [<path>...]"),
2604 argc = parse_options(argc, argv, prefix, embed_gitdir_options,
2605 git_submodule_helper_usage, 0);
2607 if (module_list_compute(argc, argv, prefix, &pathspec, &list) < 0)
2610 for (i = 0; i < list.nr; i++)
2611 absorb_git_dir_into_superproject(list.entries[i]->name, flags);
2616 static int is_active(int argc, const char **argv, const char *prefix)
2619 die("submodule--helper is-active takes exactly 1 argument");
2621 return !is_submodule_active(the_repository, argv[1]);
2625 * Exit non-zero if any of the submodule names given on the command line is
2626 * invalid. If no names are given, filter stdin to print only valid names
2627 * (which is primarily intended for testing).
2629 static int check_name(int argc, const char **argv, const char *prefix)
2633 if (check_submodule_name(*argv) < 0)
2637 struct strbuf buf = STRBUF_INIT;
2638 while (strbuf_getline(&buf, stdin) != EOF) {
2639 if (!check_submodule_name(buf.buf))
2640 printf("%s\n", buf.buf);
2642 strbuf_release(&buf);
2647 static int module_config(int argc, const char **argv, const char *prefix)
2650 CHECK_WRITEABLE = 1,
2654 struct option module_config_options[] = {
2655 OPT_CMDMODE(0, "check-writeable", &command,
2656 N_("check if it is safe to write to the .gitmodules file"),
2658 OPT_CMDMODE(0, "unset", &command,
2659 N_("unset the config in the .gitmodules file"),
2663 const char *const git_submodule_helper_usage[] = {
2664 N_("git submodule--helper config <name> [<value>]"),
2665 N_("git submodule--helper config --unset <name>"),
2666 N_("git submodule--helper config --check-writeable"),
2670 argc = parse_options(argc, argv, prefix, module_config_options,
2671 git_submodule_helper_usage, PARSE_OPT_KEEP_ARGV0);
2673 if (argc == 1 && command == CHECK_WRITEABLE)
2674 return is_writing_gitmodules_ok() ? 0 : -1;
2676 /* Equivalent to ACTION_GET in builtin/config.c */
2677 if (argc == 2 && command != DO_UNSET)
2678 return print_config_from_gitmodules(the_repository, argv[1]);
2680 /* Equivalent to ACTION_SET in builtin/config.c */
2681 if (argc == 3 || (argc == 2 && command == DO_UNSET)) {
2682 const char *value = (argc == 3) ? argv[2] : NULL;
2684 if (!is_writing_gitmodules_ok())
2685 die(_("please make sure that the .gitmodules file is in the working tree"));
2687 return config_set_in_gitmodules_file_gently(argv[1], value);
2690 usage_with_options(git_submodule_helper_usage, module_config_options);
2693 static int module_set_url(int argc, const char **argv, const char *prefix)
2700 struct option options[] = {
2701 OPT__QUIET(&quiet, N_("suppress output for setting url of a submodule")),
2704 const char *const usage[] = {
2705 N_("git submodule--helper set-url [--quiet] <path> <newurl>"),
2709 argc = parse_options(argc, argv, prefix, options, usage, 0);
2711 if (argc != 2 || !(path = argv[0]) || !(newurl = argv[1]))
2712 usage_with_options(usage, options);
2714 config_name = xstrfmt("submodule.%s.url", path);
2716 config_set_in_gitmodules_file_gently(config_name, newurl);
2717 sync_submodule(path, prefix, quiet ? OPT_QUIET : 0);
2724 static int module_set_branch(int argc, const char **argv, const char *prefix)
2726 int opt_default = 0, ret;
2727 const char *opt_branch = NULL;
2732 * We accept the `quiet` option for uniformity across subcommands,
2733 * though there is nothing to make less verbose in this subcommand.
2735 struct option options[] = {
2736 OPT_NOOP_NOARG('q', "quiet"),
2737 OPT_BOOL('d', "default", &opt_default,
2738 N_("set the default tracking branch to master")),
2739 OPT_STRING('b', "branch", &opt_branch, N_("branch"),
2740 N_("set the default tracking branch")),
2743 const char *const usage[] = {
2744 N_("git submodule--helper set-branch [-q|--quiet] (-d|--default) <path>"),
2745 N_("git submodule--helper set-branch [-q|--quiet] (-b|--branch) <branch> <path>"),
2749 argc = parse_options(argc, argv, prefix, options, usage, 0);
2751 if (!opt_branch && !opt_default)
2752 die(_("--branch or --default required"));
2754 if (opt_branch && opt_default)
2755 die(_("--branch and --default are mutually exclusive"));
2757 if (argc != 1 || !(path = argv[0]))
2758 usage_with_options(usage, options);
2760 config_name = xstrfmt("submodule.%s.branch", path);
2761 ret = config_set_in_gitmodules_file_gently(config_name, opt_branch);
2770 const char *reference_path;
2771 const char *sm_path;
2772 const char *sm_name;
2774 const char *realrepo;
2776 unsigned int force: 1;
2777 unsigned int quiet: 1;
2778 unsigned int progress: 1;
2779 unsigned int dissociate: 1;
2781 #define ADD_DATA_INIT { .depth = -1 }
2783 static void show_fetch_remotes(FILE *output, const char *sm_name, const char *git_dir_path)
2785 struct child_process cp_remote = CHILD_PROCESS_INIT;
2786 struct strbuf sb_remote_out = STRBUF_INIT;
2788 cp_remote.git_cmd = 1;
2789 strvec_pushf(&cp_remote.env_array,
2790 "GIT_DIR=%s", git_dir_path);
2791 strvec_push(&cp_remote.env_array, "GIT_WORK_TREE=.");
2792 strvec_pushl(&cp_remote.args, "remote", "-v", NULL);
2793 if (!capture_command(&cp_remote, &sb_remote_out, 0)) {
2795 char *line = sb_remote_out.buf;
2796 while ((next_line = strchr(line, '\n')) != NULL) {
2797 size_t len = next_line - line;
2798 if (strip_suffix_mem(line, &len, " (fetch)"))
2799 fprintf(output, " %.*s\n", (int)len, line);
2800 line = next_line + 1;
2804 strbuf_release(&sb_remote_out);
2807 static int add_submodule(const struct add_data *add_data)
2809 char *submod_gitdir_path;
2810 struct module_clone_data clone_data = MODULE_CLONE_DATA_INIT;
2812 /* perhaps the path already exists and is already a git repo, else clone it */
2813 if (is_directory(add_data->sm_path)) {
2814 struct strbuf sm_path = STRBUF_INIT;
2815 strbuf_addstr(&sm_path, add_data->sm_path);
2816 submod_gitdir_path = xstrfmt("%s/.git", add_data->sm_path);
2817 if (is_nonbare_repository_dir(&sm_path))
2818 printf(_("Adding existing repo at '%s' to the index\n"),
2821 die(_("'%s' already exists and is not a valid git repo"),
2823 strbuf_release(&sm_path);
2824 free(submod_gitdir_path);
2826 struct child_process cp = CHILD_PROCESS_INIT;
2827 submod_gitdir_path = xstrfmt(".git/modules/%s", add_data->sm_name);
2829 if (is_directory(submod_gitdir_path)) {
2830 if (!add_data->force) {
2831 fprintf(stderr, _("A git directory for '%s' is found "
2832 "locally with remote(s):"),
2834 show_fetch_remotes(stderr, add_data->sm_name,
2835 submod_gitdir_path);
2836 free(submod_gitdir_path);
2837 die(_("If you want to reuse this local git "
2838 "directory instead of cloning again from\n"
2840 "use the '--force' option. If the local git "
2841 "directory is not the correct repo\n"
2842 "or if you are unsure what this means, choose "
2843 "another name with the '--name' option.\n"),
2844 add_data->realrepo);
2846 printf(_("Reactivating local git directory for "
2847 "submodule '%s'\n"), add_data->sm_name);
2850 free(submod_gitdir_path);
2852 clone_data.prefix = add_data->prefix;
2853 clone_data.path = add_data->sm_path;
2854 clone_data.name = add_data->sm_name;
2855 clone_data.url = add_data->realrepo;
2856 clone_data.quiet = add_data->quiet;
2857 clone_data.progress = add_data->progress;
2858 if (add_data->reference_path)
2859 string_list_append(&clone_data.reference,
2860 xstrdup(add_data->reference_path));
2861 clone_data.dissociate = add_data->dissociate;
2862 if (add_data->depth >= 0)
2863 clone_data.depth = xstrfmt("%d", add_data->depth);
2865 if (clone_submodule(&clone_data))
2868 prepare_submodule_repo_env(&cp.env_array);
2870 cp.dir = add_data->sm_path;
2871 strvec_pushl(&cp.args, "checkout", "-f", "-q", NULL);
2873 if (add_data->branch) {
2874 strvec_pushl(&cp.args, "-B", add_data->branch, NULL);
2875 strvec_pushf(&cp.args, "origin/%s", add_data->branch);
2878 if (run_command(&cp))
2879 die(_("unable to checkout submodule '%s'"), add_data->sm_path);
2884 static int add_clone(int argc, const char **argv, const char *prefix)
2886 int force = 0, quiet = 0, dissociate = 0, progress = 0;
2887 struct add_data add_data = ADD_DATA_INIT;
2889 struct option options[] = {
2890 OPT_STRING('b', "branch", &add_data.branch,
2892 N_("branch of repository to checkout on cloning")),
2893 OPT_STRING(0, "prefix", &prefix,
2895 N_("alternative anchor for relative paths")),
2896 OPT_STRING(0, "path", &add_data.sm_path,
2898 N_("where the new submodule will be cloned to")),
2899 OPT_STRING(0, "name", &add_data.sm_name,
2901 N_("name of the new submodule")),
2902 OPT_STRING(0, "url", &add_data.realrepo,
2904 N_("url where to clone the submodule from")),
2905 OPT_STRING(0, "reference", &add_data.reference_path,
2907 N_("reference repository")),
2908 OPT_BOOL(0, "dissociate", &dissociate,
2909 N_("use --reference only while cloning")),
2910 OPT_INTEGER(0, "depth", &add_data.depth,
2911 N_("depth for shallow clones")),
2912 OPT_BOOL(0, "progress", &progress,
2913 N_("force cloning progress")),
2914 OPT__FORCE(&force, N_("allow adding an otherwise ignored submodule path"),
2915 PARSE_OPT_NOCOMPLETE),
2916 OPT__QUIET(&quiet, "suppress output for cloning a submodule"),
2920 const char *const usage[] = {
2921 N_("git submodule--helper add-clone [<options>...] "
2922 "--url <url> --path <path> --name <name>"),
2926 argc = parse_options(argc, argv, prefix, options, usage, 0);
2929 usage_with_options(usage, options);
2931 add_data.prefix = prefix;
2932 add_data.progress = !!progress;
2933 add_data.dissociate = !!dissociate;
2934 add_data.force = !!force;
2935 add_data.quiet = !!quiet;
2937 if (add_submodule(&add_data))
2943 static void config_submodule_in_gitmodules(const char *name, const char *var, const char *value)
2947 if (!is_writing_gitmodules_ok())
2948 die(_("please make sure that the .gitmodules file is in the working tree"));
2950 key = xstrfmt("submodule.%s.%s", name, var);
2951 config_set_in_gitmodules_file_gently(key, value);
2955 static void configure_added_submodule(struct add_data *add_data)
2957 char *key, *submod_pathspec = NULL;
2958 struct child_process add_submod = CHILD_PROCESS_INIT;
2959 struct child_process add_gitmodules = CHILD_PROCESS_INIT;
2960 int pathspec_key_exists, activate = 0;
2962 key = xstrfmt("submodule.%s.url", add_data->sm_name);
2963 git_config_set_gently(key, add_data->realrepo);
2966 add_submod.git_cmd = 1;
2967 strvec_pushl(&add_submod.args, "add",
2968 "--no-warn-embedded-repo", NULL);
2969 if (add_data->force)
2970 strvec_push(&add_submod.args, "--force");
2971 strvec_pushl(&add_submod.args, "--", add_data->sm_path, NULL);
2973 if (run_command(&add_submod))
2974 die(_("Failed to add submodule '%s'"), add_data->sm_path);
2976 config_submodule_in_gitmodules(add_data->sm_name, "path", add_data->sm_path);
2977 config_submodule_in_gitmodules(add_data->sm_name, "url", add_data->repo);
2978 if (add_data->branch)
2979 config_submodule_in_gitmodules(add_data->sm_name,
2980 "branch", add_data->branch);
2982 add_gitmodules.git_cmd = 1;
2983 strvec_pushl(&add_gitmodules.args,
2984 "add", "--force", "--", ".gitmodules", NULL);
2986 if (run_command(&add_gitmodules))
2987 die(_("Failed to register submodule '%s'"), add_data->sm_path);
2990 * NEEDSWORK: In a multi-working-tree world this needs to be
2991 * set in the per-worktree config.
2993 pathspec_key_exists = !git_config_get_string("submodule.active",
2995 if (pathspec_key_exists && !submod_pathspec) {
2996 warning(_("The submodule.active configuration exists, but the "
2997 "pathspec was unset. If the submodule is not already "
2998 "active, the value of submodule.%s.active will be "
2999 "be set to 'true'."), add_data->sm_name);
3004 * If submodule.active does not exist, or if the pathspec was unset,
3005 * we will activate this module unconditionally.
3007 * Otherwise, we ask is_submodule_active(), which iterates
3008 * through all the values of 'submodule.active' to determine
3009 * if this module is already active.
3011 if (!pathspec_key_exists || activate ||
3012 !is_submodule_active(the_repository, add_data->sm_path)) {
3013 key = xstrfmt("submodule.%s.active", add_data->sm_name);
3014 git_config_set_gently(key, "true");
3019 static int add_config(int argc, const char **argv, const char *prefix)
3022 struct add_data add_data = ADD_DATA_INIT;
3024 struct option options[] = {
3025 OPT_STRING('b', "branch", &add_data.branch,
3027 N_("branch of repository to store in "
3028 "the submodule configuration")),
3029 OPT_STRING(0, "url", &add_data.repo,
3031 N_("url to clone submodule from")),
3032 OPT_STRING(0, "resolved-url", &add_data.realrepo,
3034 N_("url to clone the submodule from, after it has "
3035 "been dereferenced relative to parent's url, "
3036 "in the case where <url> is a relative url")),
3037 OPT_STRING(0, "path", &add_data.sm_path,
3039 N_("where the new submodule will be cloned to")),
3040 OPT_STRING(0, "name", &add_data.sm_name,
3042 N_("name of the new submodule")),
3043 OPT__FORCE(&force, N_("allow adding an otherwise ignored submodule path"),
3044 PARSE_OPT_NOCOMPLETE),
3048 const char *const usage[] = {
3049 N_("git submodule--helper add-config "
3050 "[--force|-f] [--branch|-b <branch>] "
3051 "--url <url> --resolved-url <resolved-url> "
3052 "--path <path> --name <name>"),
3056 argc = parse_options(argc, argv, prefix, options, usage, 0);
3059 usage_with_options(usage, options);
3061 add_data.force = !!force;
3062 configure_added_submodule(&add_data);
3067 #define SUPPORT_SUPER_PREFIX (1<<0)
3071 int (*fn)(int, const char **, const char *);
3075 static struct cmd_struct commands[] = {
3076 {"list", module_list, 0},
3077 {"name", module_name, 0},
3078 {"clone", module_clone, 0},
3079 {"add-clone", add_clone, 0},
3080 {"add-config", add_config, 0},
3081 {"update-module-mode", module_update_module_mode, 0},
3082 {"update-clone", update_clone, 0},
3083 {"ensure-core-worktree", ensure_core_worktree, 0},
3084 {"relative-path", resolve_relative_path, 0},
3085 {"resolve-relative-url", resolve_relative_url, 0},
3086 {"resolve-relative-url-test", resolve_relative_url_test, 0},
3087 {"foreach", module_foreach, SUPPORT_SUPER_PREFIX},
3088 {"init", module_init, SUPPORT_SUPER_PREFIX},
3089 {"status", module_status, SUPPORT_SUPER_PREFIX},
3090 {"print-default-remote", print_default_remote, 0},
3091 {"sync", module_sync, SUPPORT_SUPER_PREFIX},
3092 {"deinit", module_deinit, 0},
3093 {"summary", module_summary, SUPPORT_SUPER_PREFIX},
3094 {"remote-branch", resolve_remote_submodule_branch, 0},
3095 {"push-check", push_check, 0},
3096 {"absorb-git-dirs", absorb_git_dirs, SUPPORT_SUPER_PREFIX},
3097 {"is-active", is_active, 0},
3098 {"check-name", check_name, 0},
3099 {"config", module_config, 0},
3100 {"set-url", module_set_url, 0},
3101 {"set-branch", module_set_branch, 0},
3104 int cmd_submodule__helper(int argc, const char **argv, const char *prefix)
3107 if (argc < 2 || !strcmp(argv[1], "-h"))
3108 usage("git submodule--helper <command>");
3110 for (i = 0; i < ARRAY_SIZE(commands); i++) {
3111 if (!strcmp(argv[1], commands[i].cmd)) {
3112 if (get_super_prefix() &&
3113 !(commands[i].option & SUPPORT_SUPER_PREFIX))
3114 die(_("%s doesn't support --super-prefix"),
3116 return commands[i].fn(argc - 1, argv + 1, prefix);
3120 die(_("'%s' is not a valid submodule--helper "
3121 "subcommand"), argv[1]);