Merge branch 'en/show-ref-doc-fix'
[git.git] / builtin / submodule--helper.c
blob6881b6a9cb0fa1cd44118663cd8d7c8eaef1c95a
1 #include "builtin.h"
2 #include "repository.h"
3 #include "cache.h"
4 #include "config.h"
5 #include "parse-options.h"
6 #include "quote.h"
7 #include "pathspec.h"
8 #include "dir.h"
9 #include "submodule.h"
10 #include "submodule-config.h"
11 #include "string-list.h"
12 #include "run-command.h"
13 #include "remote.h"
14 #include "refs.h"
15 #include "refspec.h"
16 #include "connect.h"
17 #include "revision.h"
18 #include "diffcore.h"
19 #include "diff.h"
20 #include "object-store.h"
22 #define OPT_QUIET (1 << 0)
23 #define OPT_CACHED (1 << 1)
24 #define OPT_RECURSIVE (1 << 2)
25 #define OPT_FORCE (1 << 3)
27 typedef void (*each_submodule_fn)(const struct cache_entry *list_item,
28 void *cb_data);
30 static char *get_default_remote(void)
32 char *dest = NULL, *ret;
33 struct strbuf sb = STRBUF_INIT;
34 const char *refname = resolve_ref_unsafe("HEAD", 0, NULL, NULL);
36 if (!refname)
37 die(_("No such ref: %s"), "HEAD");
39 /* detached HEAD */
40 if (!strcmp(refname, "HEAD"))
41 return xstrdup("origin");
43 if (!skip_prefix(refname, "refs/heads/", &refname))
44 die(_("Expecting a full ref name, got %s"), refname);
46 strbuf_addf(&sb, "branch.%s.remote", refname);
47 if (git_config_get_string(sb.buf, &dest))
48 ret = xstrdup("origin");
49 else
50 ret = dest;
52 strbuf_release(&sb);
53 return ret;
56 static int print_default_remote(int argc, const char **argv, const char *prefix)
58 char *remote;
60 if (argc != 1)
61 die(_("submodule--helper print-default-remote takes no arguments"));
63 remote = get_default_remote();
64 if (remote)
65 printf("%s\n", remote);
67 free(remote);
68 return 0;
71 static int starts_with_dot_slash(const char *str)
73 return str[0] == '.' && is_dir_sep(str[1]);
76 static int starts_with_dot_dot_slash(const char *str)
78 return str[0] == '.' && str[1] == '.' && is_dir_sep(str[2]);
82 * Returns 1 if it was the last chop before ':'.
84 static int chop_last_dir(char **remoteurl, int is_relative)
86 char *rfind = find_last_dir_sep(*remoteurl);
87 if (rfind) {
88 *rfind = '\0';
89 return 0;
92 rfind = strrchr(*remoteurl, ':');
93 if (rfind) {
94 *rfind = '\0';
95 return 1;
98 if (is_relative || !strcmp(".", *remoteurl))
99 die(_("cannot strip one component off url '%s'"),
100 *remoteurl);
102 free(*remoteurl);
103 *remoteurl = xstrdup(".");
104 return 0;
108 * The `url` argument is the URL that navigates to the submodule origin
109 * repo. When relative, this URL is relative to the superproject origin
110 * URL repo. The `up_path` argument, if specified, is the relative
111 * path that navigates from the submodule working tree to the superproject
112 * working tree. Returns the origin URL of the submodule.
114 * Return either an absolute URL or filesystem path (if the superproject
115 * origin URL is an absolute URL or filesystem path, respectively) or a
116 * relative file system path (if the superproject origin URL is a relative
117 * file system path).
119 * When the output is a relative file system path, the path is either
120 * relative to the submodule working tree, if up_path is specified, or to
121 * the superproject working tree otherwise.
123 * NEEDSWORK: This works incorrectly on the domain and protocol part.
124 * remote_url url outcome expectation
125 * http://a.com/b ../c http://a.com/c as is
126 * http://a.com/b/ ../c http://a.com/c same as previous line, but
127 * ignore trailing slash in url
128 * http://a.com/b ../../c http://c error out
129 * http://a.com/b ../../../c http:/c error out
130 * http://a.com/b ../../../../c http:c error out
131 * http://a.com/b ../../../../../c .:c error out
132 * NEEDSWORK: Given how chop_last_dir() works, this function is broken
133 * when a local part has a colon in its path component, too.
135 static char *relative_url(const char *remote_url,
136 const char *url,
137 const char *up_path)
139 int is_relative = 0;
140 int colonsep = 0;
141 char *out;
142 char *remoteurl = xstrdup(remote_url);
143 struct strbuf sb = STRBUF_INIT;
144 size_t len = strlen(remoteurl);
146 if (is_dir_sep(remoteurl[len-1]))
147 remoteurl[len-1] = '\0';
149 if (!url_is_local_not_ssh(remoteurl) || is_absolute_path(remoteurl))
150 is_relative = 0;
151 else {
152 is_relative = 1;
154 * Prepend a './' to ensure all relative
155 * remoteurls start with './' or '../'
157 if (!starts_with_dot_slash(remoteurl) &&
158 !starts_with_dot_dot_slash(remoteurl)) {
159 strbuf_reset(&sb);
160 strbuf_addf(&sb, "./%s", remoteurl);
161 free(remoteurl);
162 remoteurl = strbuf_detach(&sb, NULL);
166 * When the url starts with '../', remove that and the
167 * last directory in remoteurl.
169 while (url) {
170 if (starts_with_dot_dot_slash(url)) {
171 url += 3;
172 colonsep |= chop_last_dir(&remoteurl, is_relative);
173 } else if (starts_with_dot_slash(url))
174 url += 2;
175 else
176 break;
178 strbuf_reset(&sb);
179 strbuf_addf(&sb, "%s%s%s", remoteurl, colonsep ? ":" : "/", url);
180 if (ends_with(url, "/"))
181 strbuf_setlen(&sb, sb.len - 1);
182 free(remoteurl);
184 if (starts_with_dot_slash(sb.buf))
185 out = xstrdup(sb.buf + 2);
186 else
187 out = xstrdup(sb.buf);
188 strbuf_reset(&sb);
190 if (!up_path || !is_relative)
191 return out;
193 strbuf_addf(&sb, "%s%s", up_path, out);
194 free(out);
195 return strbuf_detach(&sb, NULL);
198 static int resolve_relative_url(int argc, const char **argv, const char *prefix)
200 char *remoteurl = NULL;
201 char *remote = get_default_remote();
202 const char *up_path = NULL;
203 char *res;
204 const char *url;
205 struct strbuf sb = STRBUF_INIT;
207 if (argc != 2 && argc != 3)
208 die("resolve-relative-url only accepts one or two arguments");
210 url = argv[1];
211 strbuf_addf(&sb, "remote.%s.url", remote);
212 free(remote);
214 if (git_config_get_string(sb.buf, &remoteurl))
215 /* the repository is its own authoritative upstream */
216 remoteurl = xgetcwd();
218 if (argc == 3)
219 up_path = argv[2];
221 res = relative_url(remoteurl, url, up_path);
222 puts(res);
223 free(res);
224 free(remoteurl);
225 return 0;
228 static int resolve_relative_url_test(int argc, const char **argv, const char *prefix)
230 char *remoteurl, *res;
231 const char *up_path, *url;
233 if (argc != 4)
234 die("resolve-relative-url-test only accepts three arguments: <up_path> <remoteurl> <url>");
236 up_path = argv[1];
237 remoteurl = xstrdup(argv[2]);
238 url = argv[3];
240 if (!strcmp(up_path, "(null)"))
241 up_path = NULL;
243 res = relative_url(remoteurl, url, up_path);
244 puts(res);
245 free(res);
246 free(remoteurl);
247 return 0;
250 /* the result should be freed by the caller. */
251 static char *get_submodule_displaypath(const char *path, const char *prefix)
253 const char *super_prefix = get_super_prefix();
255 if (prefix && super_prefix) {
256 BUG("cannot have prefix '%s' and superprefix '%s'",
257 prefix, super_prefix);
258 } else if (prefix) {
259 struct strbuf sb = STRBUF_INIT;
260 char *displaypath = xstrdup(relative_path(path, prefix, &sb));
261 strbuf_release(&sb);
262 return displaypath;
263 } else if (super_prefix) {
264 return xstrfmt("%s%s", super_prefix, path);
265 } else {
266 return xstrdup(path);
270 static char *compute_rev_name(const char *sub_path, const char* object_id)
272 struct strbuf sb = STRBUF_INIT;
273 const char ***d;
275 static const char *describe_bare[] = { NULL };
277 static const char *describe_tags[] = { "--tags", NULL };
279 static const char *describe_contains[] = { "--contains", NULL };
281 static const char *describe_all_always[] = { "--all", "--always", NULL };
283 static const char **describe_argv[] = { describe_bare, describe_tags,
284 describe_contains,
285 describe_all_always, NULL };
287 for (d = describe_argv; *d; d++) {
288 struct child_process cp = CHILD_PROCESS_INIT;
289 prepare_submodule_repo_env(&cp.env_array);
290 cp.dir = sub_path;
291 cp.git_cmd = 1;
292 cp.no_stderr = 1;
294 argv_array_push(&cp.args, "describe");
295 argv_array_pushv(&cp.args, *d);
296 argv_array_push(&cp.args, object_id);
298 if (!capture_command(&cp, &sb, 0)) {
299 strbuf_strip_suffix(&sb, "\n");
300 return strbuf_detach(&sb, NULL);
304 strbuf_release(&sb);
305 return NULL;
308 struct module_list {
309 const struct cache_entry **entries;
310 int alloc, nr;
312 #define MODULE_LIST_INIT { NULL, 0, 0 }
314 static int module_list_compute(int argc, const char **argv,
315 const char *prefix,
316 struct pathspec *pathspec,
317 struct module_list *list)
319 int i, result = 0;
320 char *ps_matched = NULL;
321 parse_pathspec(pathspec, 0,
322 PATHSPEC_PREFER_FULL,
323 prefix, argv);
325 if (pathspec->nr)
326 ps_matched = xcalloc(pathspec->nr, 1);
328 if (read_cache() < 0)
329 die(_("index file corrupt"));
331 for (i = 0; i < active_nr; i++) {
332 const struct cache_entry *ce = active_cache[i];
334 if (!match_pathspec(&the_index, pathspec, ce->name, ce_namelen(ce),
335 0, ps_matched, 1) ||
336 !S_ISGITLINK(ce->ce_mode))
337 continue;
339 ALLOC_GROW(list->entries, list->nr + 1, list->alloc);
340 list->entries[list->nr++] = ce;
341 while (i + 1 < active_nr &&
342 !strcmp(ce->name, active_cache[i + 1]->name))
344 * Skip entries with the same name in different stages
345 * to make sure an entry is returned only once.
347 i++;
350 if (ps_matched && report_path_error(ps_matched, pathspec, prefix))
351 result = -1;
353 free(ps_matched);
355 return result;
358 static void module_list_active(struct module_list *list)
360 int i;
361 struct module_list active_modules = MODULE_LIST_INIT;
363 for (i = 0; i < list->nr; i++) {
364 const struct cache_entry *ce = list->entries[i];
366 if (!is_submodule_active(the_repository, ce->name))
367 continue;
369 ALLOC_GROW(active_modules.entries,
370 active_modules.nr + 1,
371 active_modules.alloc);
372 active_modules.entries[active_modules.nr++] = ce;
375 free(list->entries);
376 *list = active_modules;
379 static char *get_up_path(const char *path)
381 int i;
382 struct strbuf sb = STRBUF_INIT;
384 for (i = count_slashes(path); i; i--)
385 strbuf_addstr(&sb, "../");
388 * Check if 'path' ends with slash or not
389 * for having the same output for dir/sub_dir
390 * and dir/sub_dir/
392 if (!is_dir_sep(path[strlen(path) - 1]))
393 strbuf_addstr(&sb, "../");
395 return strbuf_detach(&sb, NULL);
398 static int module_list(int argc, const char **argv, const char *prefix)
400 int i;
401 struct pathspec pathspec;
402 struct module_list list = MODULE_LIST_INIT;
404 struct option module_list_options[] = {
405 OPT_STRING(0, "prefix", &prefix,
406 N_("path"),
407 N_("alternative anchor for relative paths")),
408 OPT_END()
411 const char *const git_submodule_helper_usage[] = {
412 N_("git submodule--helper list [--prefix=<path>] [<path>...]"),
413 NULL
416 argc = parse_options(argc, argv, prefix, module_list_options,
417 git_submodule_helper_usage, 0);
419 if (module_list_compute(argc, argv, prefix, &pathspec, &list) < 0)
420 return 1;
422 for (i = 0; i < list.nr; i++) {
423 const struct cache_entry *ce = list.entries[i];
425 if (ce_stage(ce))
426 printf("%06o %s U\t", ce->ce_mode, sha1_to_hex(null_sha1));
427 else
428 printf("%06o %s %d\t", ce->ce_mode,
429 oid_to_hex(&ce->oid), ce_stage(ce));
431 fprintf(stdout, "%s\n", ce->name);
433 return 0;
436 static void for_each_listed_submodule(const struct module_list *list,
437 each_submodule_fn fn, void *cb_data)
439 int i;
440 for (i = 0; i < list->nr; i++)
441 fn(list->entries[i], cb_data);
444 struct cb_foreach {
445 int argc;
446 const char **argv;
447 const char *prefix;
448 int quiet;
449 int recursive;
451 #define CB_FOREACH_INIT { 0 }
453 static void runcommand_in_submodule_cb(const struct cache_entry *list_item,
454 void *cb_data)
456 struct cb_foreach *info = cb_data;
457 const char *path = list_item->name;
458 const struct object_id *ce_oid = &list_item->oid;
460 const struct submodule *sub;
461 struct child_process cp = CHILD_PROCESS_INIT;
462 char *displaypath;
464 displaypath = get_submodule_displaypath(path, info->prefix);
466 sub = submodule_from_path(the_repository, &null_oid, path);
468 if (!sub)
469 die(_("No url found for submodule path '%s' in .gitmodules"),
470 displaypath);
472 if (!is_submodule_populated_gently(path, NULL))
473 goto cleanup;
475 prepare_submodule_repo_env(&cp.env_array);
478 * For the purpose of executing <command> in the submodule,
479 * separate shell is used for the purpose of running the
480 * child process.
482 cp.use_shell = 1;
483 cp.dir = path;
486 * NEEDSWORK: the command currently has access to the variables $name,
487 * $sm_path, $displaypath, $sha1 and $toplevel only when the command
488 * contains a single argument. This is done for maintaining a faithful
489 * translation from shell script.
491 if (info->argc == 1) {
492 char *toplevel = xgetcwd();
493 struct strbuf sb = STRBUF_INIT;
495 argv_array_pushf(&cp.env_array, "name=%s", sub->name);
496 argv_array_pushf(&cp.env_array, "sm_path=%s", path);
497 argv_array_pushf(&cp.env_array, "displaypath=%s", displaypath);
498 argv_array_pushf(&cp.env_array, "sha1=%s",
499 oid_to_hex(ce_oid));
500 argv_array_pushf(&cp.env_array, "toplevel=%s", toplevel);
503 * Since the path variable was accessible from the script
504 * before porting, it is also made available after porting.
505 * The environment variable "PATH" has a very special purpose
506 * on windows. And since environment variables are
507 * case-insensitive in windows, it interferes with the
508 * existing PATH variable. Hence, to avoid that, we expose
509 * path via the args argv_array and not via env_array.
511 sq_quote_buf(&sb, path);
512 argv_array_pushf(&cp.args, "path=%s; %s",
513 sb.buf, info->argv[0]);
514 strbuf_release(&sb);
515 free(toplevel);
516 } else {
517 argv_array_pushv(&cp.args, info->argv);
520 if (!info->quiet)
521 printf(_("Entering '%s'\n"), displaypath);
523 if (info->argv[0] && run_command(&cp))
524 die(_("run_command returned non-zero status for %s\n."),
525 displaypath);
527 if (info->recursive) {
528 struct child_process cpr = CHILD_PROCESS_INIT;
530 cpr.git_cmd = 1;
531 cpr.dir = path;
532 prepare_submodule_repo_env(&cpr.env_array);
534 argv_array_pushl(&cpr.args, "--super-prefix", NULL);
535 argv_array_pushf(&cpr.args, "%s/", displaypath);
536 argv_array_pushl(&cpr.args, "submodule--helper", "foreach", "--recursive",
537 NULL);
539 if (info->quiet)
540 argv_array_push(&cpr.args, "--quiet");
542 argv_array_pushv(&cpr.args, info->argv);
544 if (run_command(&cpr))
545 die(_("run_command returned non-zero status while "
546 "recursing in the nested submodules of %s\n."),
547 displaypath);
550 cleanup:
551 free(displaypath);
554 static int module_foreach(int argc, const char **argv, const char *prefix)
556 struct cb_foreach info = CB_FOREACH_INIT;
557 struct pathspec pathspec;
558 struct module_list list = MODULE_LIST_INIT;
560 struct option module_foreach_options[] = {
561 OPT__QUIET(&info.quiet, N_("Suppress output of entering each submodule command")),
562 OPT_BOOL(0, "recursive", &info.recursive,
563 N_("Recurse into nested submodules")),
564 OPT_END()
567 const char *const git_submodule_helper_usage[] = {
568 N_("git submodule--helper foreach [--quiet] [--recursive] <command>"),
569 NULL
572 argc = parse_options(argc, argv, prefix, module_foreach_options,
573 git_submodule_helper_usage, PARSE_OPT_KEEP_UNKNOWN);
575 if (module_list_compute(0, NULL, prefix, &pathspec, &list) < 0)
576 return 1;
578 info.argc = argc;
579 info.argv = argv;
580 info.prefix = prefix;
582 for_each_listed_submodule(&list, runcommand_in_submodule_cb, &info);
584 return 0;
587 static char *compute_submodule_clone_url(const char *rel_url)
589 char *remoteurl, *relurl;
590 char *remote = get_default_remote();
591 struct strbuf remotesb = STRBUF_INIT;
593 strbuf_addf(&remotesb, "remote.%s.url", remote);
594 if (git_config_get_string(remotesb.buf, &remoteurl)) {
595 warning(_("could not look up configuration '%s'. Assuming this repository is its own authoritative upstream."), remotesb.buf);
596 remoteurl = xgetcwd();
598 relurl = relative_url(remoteurl, rel_url, NULL);
600 free(remote);
601 free(remoteurl);
602 strbuf_release(&remotesb);
604 return relurl;
607 struct init_cb {
608 const char *prefix;
609 unsigned int flags;
612 #define INIT_CB_INIT { NULL, 0 }
614 static void init_submodule(const char *path, const char *prefix,
615 unsigned int flags)
617 const struct submodule *sub;
618 struct strbuf sb = STRBUF_INIT;
619 char *upd = NULL, *url = NULL, *displaypath;
621 displaypath = get_submodule_displaypath(path, prefix);
623 sub = submodule_from_path(the_repository, &null_oid, path);
625 if (!sub)
626 die(_("No url found for submodule path '%s' in .gitmodules"),
627 displaypath);
630 * NEEDSWORK: In a multi-working-tree world, this needs to be
631 * set in the per-worktree config.
633 * Set active flag for the submodule being initialized
635 if (!is_submodule_active(the_repository, path)) {
636 strbuf_addf(&sb, "submodule.%s.active", sub->name);
637 git_config_set_gently(sb.buf, "true");
638 strbuf_reset(&sb);
642 * Copy url setting when it is not set yet.
643 * To look up the url in .git/config, we must not fall back to
644 * .gitmodules, so look it up directly.
646 strbuf_addf(&sb, "submodule.%s.url", sub->name);
647 if (git_config_get_string(sb.buf, &url)) {
648 if (!sub->url)
649 die(_("No url found for submodule path '%s' in .gitmodules"),
650 displaypath);
652 url = xstrdup(sub->url);
654 /* Possibly a url relative to parent */
655 if (starts_with_dot_dot_slash(url) ||
656 starts_with_dot_slash(url)) {
657 char *oldurl = url;
658 url = compute_submodule_clone_url(oldurl);
659 free(oldurl);
662 if (git_config_set_gently(sb.buf, url))
663 die(_("Failed to register url for submodule path '%s'"),
664 displaypath);
665 if (!(flags & OPT_QUIET))
666 fprintf(stderr,
667 _("Submodule '%s' (%s) registered for path '%s'\n"),
668 sub->name, url, displaypath);
670 strbuf_reset(&sb);
672 /* Copy "update" setting when it is not set yet */
673 strbuf_addf(&sb, "submodule.%s.update", sub->name);
674 if (git_config_get_string(sb.buf, &upd) &&
675 sub->update_strategy.type != SM_UPDATE_UNSPECIFIED) {
676 if (sub->update_strategy.type == SM_UPDATE_COMMAND) {
677 fprintf(stderr, _("warning: command update mode suggested for submodule '%s'\n"),
678 sub->name);
679 upd = xstrdup("none");
680 } else
681 upd = xstrdup(submodule_strategy_to_string(&sub->update_strategy));
683 if (git_config_set_gently(sb.buf, upd))
684 die(_("Failed to register update mode for submodule path '%s'"), displaypath);
686 strbuf_release(&sb);
687 free(displaypath);
688 free(url);
689 free(upd);
692 static void init_submodule_cb(const struct cache_entry *list_item, void *cb_data)
694 struct init_cb *info = cb_data;
695 init_submodule(list_item->name, info->prefix, info->flags);
698 static int module_init(int argc, const char **argv, const char *prefix)
700 struct init_cb info = INIT_CB_INIT;
701 struct pathspec pathspec;
702 struct module_list list = MODULE_LIST_INIT;
703 int quiet = 0;
705 struct option module_init_options[] = {
706 OPT__QUIET(&quiet, N_("Suppress output for initializing a submodule")),
707 OPT_END()
710 const char *const git_submodule_helper_usage[] = {
711 N_("git submodule--helper init [<path>]"),
712 NULL
715 argc = parse_options(argc, argv, prefix, module_init_options,
716 git_submodule_helper_usage, 0);
718 if (module_list_compute(argc, argv, prefix, &pathspec, &list) < 0)
719 return 1;
722 * If there are no path args and submodule.active is set then,
723 * by default, only initialize 'active' modules.
725 if (!argc && git_config_get_value_multi("submodule.active"))
726 module_list_active(&list);
728 info.prefix = prefix;
729 if (quiet)
730 info.flags |= OPT_QUIET;
732 for_each_listed_submodule(&list, init_submodule_cb, &info);
734 return 0;
737 struct status_cb {
738 const char *prefix;
739 unsigned int flags;
742 #define STATUS_CB_INIT { NULL, 0 }
744 static void print_status(unsigned int flags, char state, const char *path,
745 const struct object_id *oid, const char *displaypath)
747 if (flags & OPT_QUIET)
748 return;
750 printf("%c%s %s", state, oid_to_hex(oid), displaypath);
752 if (state == ' ' || state == '+') {
753 const char *name = compute_rev_name(path, oid_to_hex(oid));
755 if (name)
756 printf(" (%s)", name);
759 printf("\n");
762 static int handle_submodule_head_ref(const char *refname,
763 const struct object_id *oid, int flags,
764 void *cb_data)
766 struct object_id *output = cb_data;
767 if (oid)
768 oidcpy(output, oid);
770 return 0;
773 static void status_submodule(const char *path, const struct object_id *ce_oid,
774 unsigned int ce_flags, const char *prefix,
775 unsigned int flags)
777 char *displaypath;
778 struct argv_array diff_files_args = ARGV_ARRAY_INIT;
779 struct rev_info rev;
780 int diff_files_result;
782 if (!submodule_from_path(the_repository, &null_oid, path))
783 die(_("no submodule mapping found in .gitmodules for path '%s'"),
784 path);
786 displaypath = get_submodule_displaypath(path, prefix);
788 if ((CE_STAGEMASK & ce_flags) >> CE_STAGESHIFT) {
789 print_status(flags, 'U', path, &null_oid, displaypath);
790 goto cleanup;
793 if (!is_submodule_active(the_repository, path)) {
794 print_status(flags, '-', path, ce_oid, displaypath);
795 goto cleanup;
798 argv_array_pushl(&diff_files_args, "diff-files",
799 "--ignore-submodules=dirty", "--quiet", "--",
800 path, NULL);
802 git_config(git_diff_basic_config, NULL);
803 repo_init_revisions(the_repository, &rev, prefix);
804 rev.abbrev = 0;
805 diff_files_args.argc = setup_revisions(diff_files_args.argc,
806 diff_files_args.argv,
807 &rev, NULL);
808 diff_files_result = run_diff_files(&rev, 0);
810 if (!diff_result_code(&rev.diffopt, diff_files_result)) {
811 print_status(flags, ' ', path, ce_oid,
812 displaypath);
813 } else if (!(flags & OPT_CACHED)) {
814 struct object_id oid;
815 struct ref_store *refs = get_submodule_ref_store(path);
817 if (!refs) {
818 print_status(flags, '-', path, ce_oid, displaypath);
819 goto cleanup;
821 if (refs_head_ref(refs, handle_submodule_head_ref, &oid))
822 die(_("could not resolve HEAD ref inside the "
823 "submodule '%s'"), path);
825 print_status(flags, '+', path, &oid, displaypath);
826 } else {
827 print_status(flags, '+', path, ce_oid, displaypath);
830 if (flags & OPT_RECURSIVE) {
831 struct child_process cpr = CHILD_PROCESS_INIT;
833 cpr.git_cmd = 1;
834 cpr.dir = path;
835 prepare_submodule_repo_env(&cpr.env_array);
837 argv_array_push(&cpr.args, "--super-prefix");
838 argv_array_pushf(&cpr.args, "%s/", displaypath);
839 argv_array_pushl(&cpr.args, "submodule--helper", "status",
840 "--recursive", NULL);
842 if (flags & OPT_CACHED)
843 argv_array_push(&cpr.args, "--cached");
845 if (flags & OPT_QUIET)
846 argv_array_push(&cpr.args, "--quiet");
848 if (run_command(&cpr))
849 die(_("failed to recurse into submodule '%s'"), path);
852 cleanup:
853 argv_array_clear(&diff_files_args);
854 free(displaypath);
857 static void status_submodule_cb(const struct cache_entry *list_item,
858 void *cb_data)
860 struct status_cb *info = cb_data;
861 status_submodule(list_item->name, &list_item->oid, list_item->ce_flags,
862 info->prefix, info->flags);
865 static int module_status(int argc, const char **argv, const char *prefix)
867 struct status_cb info = STATUS_CB_INIT;
868 struct pathspec pathspec;
869 struct module_list list = MODULE_LIST_INIT;
870 int quiet = 0;
872 struct option module_status_options[] = {
873 OPT__QUIET(&quiet, N_("Suppress submodule status output")),
874 OPT_BIT(0, "cached", &info.flags, N_("Use commit stored in the index instead of the one stored in the submodule HEAD"), OPT_CACHED),
875 OPT_BIT(0, "recursive", &info.flags, N_("recurse into nested submodules"), OPT_RECURSIVE),
876 OPT_END()
879 const char *const git_submodule_helper_usage[] = {
880 N_("git submodule status [--quiet] [--cached] [--recursive] [<path>...]"),
881 NULL
884 argc = parse_options(argc, argv, prefix, module_status_options,
885 git_submodule_helper_usage, 0);
887 if (module_list_compute(argc, argv, prefix, &pathspec, &list) < 0)
888 return 1;
890 info.prefix = prefix;
891 if (quiet)
892 info.flags |= OPT_QUIET;
894 for_each_listed_submodule(&list, status_submodule_cb, &info);
896 return 0;
899 static int module_name(int argc, const char **argv, const char *prefix)
901 const struct submodule *sub;
903 if (argc != 2)
904 usage(_("git submodule--helper name <path>"));
906 sub = submodule_from_path(the_repository, &null_oid, argv[1]);
908 if (!sub)
909 die(_("no submodule mapping found in .gitmodules for path '%s'"),
910 argv[1]);
912 printf("%s\n", sub->name);
914 return 0;
917 struct sync_cb {
918 const char *prefix;
919 unsigned int flags;
922 #define SYNC_CB_INIT { NULL, 0 }
924 static void sync_submodule(const char *path, const char *prefix,
925 unsigned int flags)
927 const struct submodule *sub;
928 char *remote_key = NULL;
929 char *sub_origin_url, *super_config_url, *displaypath;
930 struct strbuf sb = STRBUF_INIT;
931 struct child_process cp = CHILD_PROCESS_INIT;
932 char *sub_config_path = NULL;
934 if (!is_submodule_active(the_repository, path))
935 return;
937 sub = submodule_from_path(the_repository, &null_oid, path);
939 if (sub && sub->url) {
940 if (starts_with_dot_dot_slash(sub->url) ||
941 starts_with_dot_slash(sub->url)) {
942 char *remote_url, *up_path;
943 char *remote = get_default_remote();
944 strbuf_addf(&sb, "remote.%s.url", remote);
946 if (git_config_get_string(sb.buf, &remote_url))
947 remote_url = xgetcwd();
949 up_path = get_up_path(path);
950 sub_origin_url = relative_url(remote_url, sub->url, up_path);
951 super_config_url = relative_url(remote_url, sub->url, NULL);
953 free(remote);
954 free(up_path);
955 free(remote_url);
956 } else {
957 sub_origin_url = xstrdup(sub->url);
958 super_config_url = xstrdup(sub->url);
960 } else {
961 sub_origin_url = xstrdup("");
962 super_config_url = xstrdup("");
965 displaypath = get_submodule_displaypath(path, prefix);
967 if (!(flags & OPT_QUIET))
968 printf(_("Synchronizing submodule url for '%s'\n"),
969 displaypath);
971 strbuf_reset(&sb);
972 strbuf_addf(&sb, "submodule.%s.url", sub->name);
973 if (git_config_set_gently(sb.buf, super_config_url))
974 die(_("failed to register url for submodule path '%s'"),
975 displaypath);
977 if (!is_submodule_populated_gently(path, NULL))
978 goto cleanup;
980 prepare_submodule_repo_env(&cp.env_array);
981 cp.git_cmd = 1;
982 cp.dir = path;
983 argv_array_pushl(&cp.args, "submodule--helper",
984 "print-default-remote", NULL);
986 strbuf_reset(&sb);
987 if (capture_command(&cp, &sb, 0))
988 die(_("failed to get the default remote for submodule '%s'"),
989 path);
991 strbuf_strip_suffix(&sb, "\n");
992 remote_key = xstrfmt("remote.%s.url", sb.buf);
994 strbuf_reset(&sb);
995 submodule_to_gitdir(&sb, path);
996 strbuf_addstr(&sb, "/config");
998 if (git_config_set_in_file_gently(sb.buf, remote_key, sub_origin_url))
999 die(_("failed to update remote for submodule '%s'"),
1000 path);
1002 if (flags & OPT_RECURSIVE) {
1003 struct child_process cpr = CHILD_PROCESS_INIT;
1005 cpr.git_cmd = 1;
1006 cpr.dir = path;
1007 prepare_submodule_repo_env(&cpr.env_array);
1009 argv_array_push(&cpr.args, "--super-prefix");
1010 argv_array_pushf(&cpr.args, "%s/", displaypath);
1011 argv_array_pushl(&cpr.args, "submodule--helper", "sync",
1012 "--recursive", NULL);
1014 if (flags & OPT_QUIET)
1015 argv_array_push(&cpr.args, "--quiet");
1017 if (run_command(&cpr))
1018 die(_("failed to recurse into submodule '%s'"),
1019 path);
1022 cleanup:
1023 free(super_config_url);
1024 free(sub_origin_url);
1025 strbuf_release(&sb);
1026 free(remote_key);
1027 free(displaypath);
1028 free(sub_config_path);
1031 static void sync_submodule_cb(const struct cache_entry *list_item, void *cb_data)
1033 struct sync_cb *info = cb_data;
1034 sync_submodule(list_item->name, info->prefix, info->flags);
1037 static int module_sync(int argc, const char **argv, const char *prefix)
1039 struct sync_cb info = SYNC_CB_INIT;
1040 struct pathspec pathspec;
1041 struct module_list list = MODULE_LIST_INIT;
1042 int quiet = 0;
1043 int recursive = 0;
1045 struct option module_sync_options[] = {
1046 OPT__QUIET(&quiet, N_("Suppress output of synchronizing submodule url")),
1047 OPT_BOOL(0, "recursive", &recursive,
1048 N_("Recurse into nested submodules")),
1049 OPT_END()
1052 const char *const git_submodule_helper_usage[] = {
1053 N_("git submodule--helper sync [--quiet] [--recursive] [<path>]"),
1054 NULL
1057 argc = parse_options(argc, argv, prefix, module_sync_options,
1058 git_submodule_helper_usage, 0);
1060 if (module_list_compute(argc, argv, prefix, &pathspec, &list) < 0)
1061 return 1;
1063 info.prefix = prefix;
1064 if (quiet)
1065 info.flags |= OPT_QUIET;
1066 if (recursive)
1067 info.flags |= OPT_RECURSIVE;
1069 for_each_listed_submodule(&list, sync_submodule_cb, &info);
1071 return 0;
1074 struct deinit_cb {
1075 const char *prefix;
1076 unsigned int flags;
1078 #define DEINIT_CB_INIT { NULL, 0 }
1080 static void deinit_submodule(const char *path, const char *prefix,
1081 unsigned int flags)
1083 const struct submodule *sub;
1084 char *displaypath = NULL;
1085 struct child_process cp_config = CHILD_PROCESS_INIT;
1086 struct strbuf sb_config = STRBUF_INIT;
1087 char *sub_git_dir = xstrfmt("%s/.git", path);
1089 sub = submodule_from_path(the_repository, &null_oid, path);
1091 if (!sub || !sub->name)
1092 goto cleanup;
1094 displaypath = get_submodule_displaypath(path, prefix);
1096 /* remove the submodule work tree (unless the user already did it) */
1097 if (is_directory(path)) {
1098 struct strbuf sb_rm = STRBUF_INIT;
1099 const char *format;
1102 * protect submodules containing a .git directory
1103 * NEEDSWORK: instead of dying, automatically call
1104 * absorbgitdirs and (possibly) warn.
1106 if (is_directory(sub_git_dir))
1107 die(_("Submodule work tree '%s' contains a .git "
1108 "directory (use 'rm -rf' if you really want "
1109 "to remove it including all of its history)"),
1110 displaypath);
1112 if (!(flags & OPT_FORCE)) {
1113 struct child_process cp_rm = CHILD_PROCESS_INIT;
1114 cp_rm.git_cmd = 1;
1115 argv_array_pushl(&cp_rm.args, "rm", "-qn",
1116 path, NULL);
1118 if (run_command(&cp_rm))
1119 die(_("Submodule work tree '%s' contains local "
1120 "modifications; use '-f' to discard them"),
1121 displaypath);
1124 strbuf_addstr(&sb_rm, path);
1126 if (!remove_dir_recursively(&sb_rm, 0))
1127 format = _("Cleared directory '%s'\n");
1128 else
1129 format = _("Could not remove submodule work tree '%s'\n");
1131 if (!(flags & OPT_QUIET))
1132 printf(format, displaypath);
1134 submodule_unset_core_worktree(sub);
1136 strbuf_release(&sb_rm);
1139 if (mkdir(path, 0777))
1140 printf(_("could not create empty submodule directory %s"),
1141 displaypath);
1143 cp_config.git_cmd = 1;
1144 argv_array_pushl(&cp_config.args, "config", "--get-regexp", NULL);
1145 argv_array_pushf(&cp_config.args, "submodule.%s\\.", sub->name);
1147 /* remove the .git/config entries (unless the user already did it) */
1148 if (!capture_command(&cp_config, &sb_config, 0) && sb_config.len) {
1149 char *sub_key = xstrfmt("submodule.%s", sub->name);
1151 * remove the whole section so we have a clean state when
1152 * the user later decides to init this submodule again
1154 git_config_rename_section_in_file(NULL, sub_key, NULL);
1155 if (!(flags & OPT_QUIET))
1156 printf(_("Submodule '%s' (%s) unregistered for path '%s'\n"),
1157 sub->name, sub->url, displaypath);
1158 free(sub_key);
1161 cleanup:
1162 free(displaypath);
1163 free(sub_git_dir);
1164 strbuf_release(&sb_config);
1167 static void deinit_submodule_cb(const struct cache_entry *list_item,
1168 void *cb_data)
1170 struct deinit_cb *info = cb_data;
1171 deinit_submodule(list_item->name, info->prefix, info->flags);
1174 static int module_deinit(int argc, const char **argv, const char *prefix)
1176 struct deinit_cb info = DEINIT_CB_INIT;
1177 struct pathspec pathspec;
1178 struct module_list list = MODULE_LIST_INIT;
1179 int quiet = 0;
1180 int force = 0;
1181 int all = 0;
1183 struct option module_deinit_options[] = {
1184 OPT__QUIET(&quiet, N_("Suppress submodule status output")),
1185 OPT__FORCE(&force, N_("Remove submodule working trees even if they contain local changes"), 0),
1186 OPT_BOOL(0, "all", &all, N_("Unregister all submodules")),
1187 OPT_END()
1190 const char *const git_submodule_helper_usage[] = {
1191 N_("git submodule deinit [--quiet] [-f | --force] [--all | [--] [<path>...]]"),
1192 NULL
1195 argc = parse_options(argc, argv, prefix, module_deinit_options,
1196 git_submodule_helper_usage, 0);
1198 if (all && argc) {
1199 error("pathspec and --all are incompatible");
1200 usage_with_options(git_submodule_helper_usage,
1201 module_deinit_options);
1204 if (!argc && !all)
1205 die(_("Use '--all' if you really want to deinitialize all submodules"));
1207 if (module_list_compute(argc, argv, prefix, &pathspec, &list) < 0)
1208 return 1;
1210 info.prefix = prefix;
1211 if (quiet)
1212 info.flags |= OPT_QUIET;
1213 if (force)
1214 info.flags |= OPT_FORCE;
1216 for_each_listed_submodule(&list, deinit_submodule_cb, &info);
1218 return 0;
1221 static int clone_submodule(const char *path, const char *gitdir, const char *url,
1222 const char *depth, struct string_list *reference, int dissociate,
1223 int quiet, int progress)
1225 struct child_process cp = CHILD_PROCESS_INIT;
1227 argv_array_push(&cp.args, "clone");
1228 argv_array_push(&cp.args, "--no-checkout");
1229 if (quiet)
1230 argv_array_push(&cp.args, "--quiet");
1231 if (progress)
1232 argv_array_push(&cp.args, "--progress");
1233 if (depth && *depth)
1234 argv_array_pushl(&cp.args, "--depth", depth, NULL);
1235 if (reference->nr) {
1236 struct string_list_item *item;
1237 for_each_string_list_item(item, reference)
1238 argv_array_pushl(&cp.args, "--reference",
1239 item->string, NULL);
1241 if (dissociate)
1242 argv_array_push(&cp.args, "--dissociate");
1243 if (gitdir && *gitdir)
1244 argv_array_pushl(&cp.args, "--separate-git-dir", gitdir, NULL);
1246 argv_array_push(&cp.args, "--");
1247 argv_array_push(&cp.args, url);
1248 argv_array_push(&cp.args, path);
1250 cp.git_cmd = 1;
1251 prepare_submodule_repo_env(&cp.env_array);
1252 cp.no_stdin = 1;
1254 return run_command(&cp);
1257 struct submodule_alternate_setup {
1258 const char *submodule_name;
1259 enum SUBMODULE_ALTERNATE_ERROR_MODE {
1260 SUBMODULE_ALTERNATE_ERROR_DIE,
1261 SUBMODULE_ALTERNATE_ERROR_INFO,
1262 SUBMODULE_ALTERNATE_ERROR_IGNORE
1263 } error_mode;
1264 struct string_list *reference;
1266 #define SUBMODULE_ALTERNATE_SETUP_INIT { NULL, \
1267 SUBMODULE_ALTERNATE_ERROR_IGNORE, NULL }
1269 static int add_possible_reference_from_superproject(
1270 struct object_directory *odb, void *sas_cb)
1272 struct submodule_alternate_setup *sas = sas_cb;
1273 size_t len;
1276 * If the alternate object store is another repository, try the
1277 * standard layout with .git/(modules/<name>)+/objects
1279 if (strip_suffix(odb->path, "/objects", &len)) {
1280 char *sm_alternate;
1281 struct strbuf sb = STRBUF_INIT;
1282 struct strbuf err = STRBUF_INIT;
1283 strbuf_add(&sb, odb->path, len);
1286 * We need to end the new path with '/' to mark it as a dir,
1287 * otherwise a submodule name containing '/' will be broken
1288 * as the last part of a missing submodule reference would
1289 * be taken as a file name.
1291 strbuf_addf(&sb, "/modules/%s/", sas->submodule_name);
1293 sm_alternate = compute_alternate_path(sb.buf, &err);
1294 if (sm_alternate) {
1295 string_list_append(sas->reference, xstrdup(sb.buf));
1296 free(sm_alternate);
1297 } else {
1298 switch (sas->error_mode) {
1299 case SUBMODULE_ALTERNATE_ERROR_DIE:
1300 die(_("submodule '%s' cannot add alternate: %s"),
1301 sas->submodule_name, err.buf);
1302 case SUBMODULE_ALTERNATE_ERROR_INFO:
1303 fprintf(stderr, _("submodule '%s' cannot add alternate: %s"),
1304 sas->submodule_name, err.buf);
1305 case SUBMODULE_ALTERNATE_ERROR_IGNORE:
1306 ; /* nothing */
1309 strbuf_release(&sb);
1312 return 0;
1315 static void prepare_possible_alternates(const char *sm_name,
1316 struct string_list *reference)
1318 char *sm_alternate = NULL, *error_strategy = NULL;
1319 struct submodule_alternate_setup sas = SUBMODULE_ALTERNATE_SETUP_INIT;
1321 git_config_get_string("submodule.alternateLocation", &sm_alternate);
1322 if (!sm_alternate)
1323 return;
1325 git_config_get_string("submodule.alternateErrorStrategy", &error_strategy);
1327 if (!error_strategy)
1328 error_strategy = xstrdup("die");
1330 sas.submodule_name = sm_name;
1331 sas.reference = reference;
1332 if (!strcmp(error_strategy, "die"))
1333 sas.error_mode = SUBMODULE_ALTERNATE_ERROR_DIE;
1334 else if (!strcmp(error_strategy, "info"))
1335 sas.error_mode = SUBMODULE_ALTERNATE_ERROR_INFO;
1336 else if (!strcmp(error_strategy, "ignore"))
1337 sas.error_mode = SUBMODULE_ALTERNATE_ERROR_IGNORE;
1338 else
1339 die(_("Value '%s' for submodule.alternateErrorStrategy is not recognized"), error_strategy);
1341 if (!strcmp(sm_alternate, "superproject"))
1342 foreach_alt_odb(add_possible_reference_from_superproject, &sas);
1343 else if (!strcmp(sm_alternate, "no"))
1344 ; /* do nothing */
1345 else
1346 die(_("Value '%s' for submodule.alternateLocation is not recognized"), sm_alternate);
1348 free(sm_alternate);
1349 free(error_strategy);
1352 static int module_clone(int argc, const char **argv, const char *prefix)
1354 const char *name = NULL, *url = NULL, *depth = NULL;
1355 int quiet = 0;
1356 int progress = 0;
1357 char *p, *path = NULL, *sm_gitdir;
1358 struct strbuf sb = STRBUF_INIT;
1359 struct string_list reference = STRING_LIST_INIT_NODUP;
1360 int dissociate = 0;
1361 char *sm_alternate = NULL, *error_strategy = NULL;
1363 struct option module_clone_options[] = {
1364 OPT_STRING(0, "prefix", &prefix,
1365 N_("path"),
1366 N_("alternative anchor for relative paths")),
1367 OPT_STRING(0, "path", &path,
1368 N_("path"),
1369 N_("where the new submodule will be cloned to")),
1370 OPT_STRING(0, "name", &name,
1371 N_("string"),
1372 N_("name of the new submodule")),
1373 OPT_STRING(0, "url", &url,
1374 N_("string"),
1375 N_("url where to clone the submodule from")),
1376 OPT_STRING_LIST(0, "reference", &reference,
1377 N_("repo"),
1378 N_("reference repository")),
1379 OPT_BOOL(0, "dissociate", &dissociate,
1380 N_("use --reference only while cloning")),
1381 OPT_STRING(0, "depth", &depth,
1382 N_("string"),
1383 N_("depth for shallow clones")),
1384 OPT__QUIET(&quiet, "Suppress output for cloning a submodule"),
1385 OPT_BOOL(0, "progress", &progress,
1386 N_("force cloning progress")),
1387 OPT_END()
1390 const char *const git_submodule_helper_usage[] = {
1391 N_("git submodule--helper clone [--prefix=<path>] [--quiet] "
1392 "[--reference <repository>] [--name <name>] [--depth <depth>] "
1393 "--url <url> --path <path>"),
1394 NULL
1397 argc = parse_options(argc, argv, prefix, module_clone_options,
1398 git_submodule_helper_usage, 0);
1400 if (argc || !url || !path || !*path)
1401 usage_with_options(git_submodule_helper_usage,
1402 module_clone_options);
1404 strbuf_addf(&sb, "%s/modules/%s", get_git_dir(), name);
1405 sm_gitdir = absolute_pathdup(sb.buf);
1406 strbuf_reset(&sb);
1408 if (!is_absolute_path(path)) {
1409 strbuf_addf(&sb, "%s/%s", get_git_work_tree(), path);
1410 path = strbuf_detach(&sb, NULL);
1411 } else
1412 path = xstrdup(path);
1414 if (!file_exists(sm_gitdir)) {
1415 if (safe_create_leading_directories_const(sm_gitdir) < 0)
1416 die(_("could not create directory '%s'"), sm_gitdir);
1418 prepare_possible_alternates(name, &reference);
1420 if (clone_submodule(path, sm_gitdir, url, depth, &reference, dissociate,
1421 quiet, progress))
1422 die(_("clone of '%s' into submodule path '%s' failed"),
1423 url, path);
1424 } else {
1425 if (safe_create_leading_directories_const(path) < 0)
1426 die(_("could not create directory '%s'"), path);
1427 strbuf_addf(&sb, "%s/index", sm_gitdir);
1428 unlink_or_warn(sb.buf);
1429 strbuf_reset(&sb);
1432 connect_work_tree_and_git_dir(path, sm_gitdir, 0);
1434 p = git_pathdup_submodule(path, "config");
1435 if (!p)
1436 die(_("could not get submodule directory for '%s'"), path);
1438 /* setup alternateLocation and alternateErrorStrategy in the cloned submodule if needed */
1439 git_config_get_string("submodule.alternateLocation", &sm_alternate);
1440 if (sm_alternate)
1441 git_config_set_in_file(p, "submodule.alternateLocation",
1442 sm_alternate);
1443 git_config_get_string("submodule.alternateErrorStrategy", &error_strategy);
1444 if (error_strategy)
1445 git_config_set_in_file(p, "submodule.alternateErrorStrategy",
1446 error_strategy);
1448 free(sm_alternate);
1449 free(error_strategy);
1451 strbuf_release(&sb);
1452 free(sm_gitdir);
1453 free(path);
1454 free(p);
1455 return 0;
1458 static void determine_submodule_update_strategy(struct repository *r,
1459 int just_cloned,
1460 const char *path,
1461 const char *update,
1462 struct submodule_update_strategy *out)
1464 const struct submodule *sub = submodule_from_path(r, &null_oid, path);
1465 char *key;
1466 const char *val;
1468 key = xstrfmt("submodule.%s.update", sub->name);
1470 if (update) {
1471 if (parse_submodule_update_strategy(update, out) < 0)
1472 die(_("Invalid update mode '%s' for submodule path '%s'"),
1473 update, path);
1474 } else if (!repo_config_get_string_const(r, key, &val)) {
1475 if (parse_submodule_update_strategy(val, out) < 0)
1476 die(_("Invalid update mode '%s' configured for submodule path '%s'"),
1477 val, path);
1478 } else if (sub->update_strategy.type != SM_UPDATE_UNSPECIFIED) {
1479 out->type = sub->update_strategy.type;
1480 out->command = sub->update_strategy.command;
1481 } else
1482 out->type = SM_UPDATE_CHECKOUT;
1484 if (just_cloned &&
1485 (out->type == SM_UPDATE_MERGE ||
1486 out->type == SM_UPDATE_REBASE ||
1487 out->type == SM_UPDATE_NONE))
1488 out->type = SM_UPDATE_CHECKOUT;
1490 free(key);
1493 static int module_update_module_mode(int argc, const char **argv, const char *prefix)
1495 const char *path, *update = NULL;
1496 int just_cloned;
1497 struct submodule_update_strategy update_strategy = { .type = SM_UPDATE_CHECKOUT };
1499 if (argc < 3 || argc > 4)
1500 die("submodule--helper update-module-clone expects <just-cloned> <path> [<update>]");
1502 just_cloned = git_config_int("just_cloned", argv[1]);
1503 path = argv[2];
1505 if (argc == 4)
1506 update = argv[3];
1508 determine_submodule_update_strategy(the_repository,
1509 just_cloned, path, update,
1510 &update_strategy);
1511 fputs(submodule_strategy_to_string(&update_strategy), stdout);
1513 return 0;
1516 struct update_clone_data {
1517 const struct submodule *sub;
1518 struct object_id oid;
1519 unsigned just_cloned;
1522 struct submodule_update_clone {
1523 /* index into 'list', the list of submodules to look into for cloning */
1524 int current;
1525 struct module_list list;
1526 unsigned warn_if_uninitialized : 1;
1528 /* update parameter passed via commandline */
1529 struct submodule_update_strategy update;
1531 /* configuration parameters which are passed on to the children */
1532 int progress;
1533 int quiet;
1534 int recommend_shallow;
1535 struct string_list references;
1536 int dissociate;
1537 const char *depth;
1538 const char *recursive_prefix;
1539 const char *prefix;
1541 /* to be consumed by git-submodule.sh */
1542 struct update_clone_data *update_clone;
1543 int update_clone_nr; int update_clone_alloc;
1545 /* If we want to stop as fast as possible and return an error */
1546 unsigned quickstop : 1;
1548 /* failed clones to be retried again */
1549 const struct cache_entry **failed_clones;
1550 int failed_clones_nr, failed_clones_alloc;
1552 int max_jobs;
1554 #define SUBMODULE_UPDATE_CLONE_INIT {0, MODULE_LIST_INIT, 0, \
1555 SUBMODULE_UPDATE_STRATEGY_INIT, 0, 0, -1, STRING_LIST_INIT_DUP, 0, \
1556 NULL, NULL, NULL, \
1557 NULL, 0, 0, 0, NULL, 0, 0, 1}
1560 static void next_submodule_warn_missing(struct submodule_update_clone *suc,
1561 struct strbuf *out, const char *displaypath)
1564 * Only mention uninitialized submodules when their
1565 * paths have been specified.
1567 if (suc->warn_if_uninitialized) {
1568 strbuf_addf(out,
1569 _("Submodule path '%s' not initialized"),
1570 displaypath);
1571 strbuf_addch(out, '\n');
1572 strbuf_addstr(out,
1573 _("Maybe you want to use 'update --init'?"));
1574 strbuf_addch(out, '\n');
1579 * Determine whether 'ce' needs to be cloned. If so, prepare the 'child' to
1580 * run the clone. Returns 1 if 'ce' needs to be cloned, 0 otherwise.
1582 static int prepare_to_clone_next_submodule(const struct cache_entry *ce,
1583 struct child_process *child,
1584 struct submodule_update_clone *suc,
1585 struct strbuf *out)
1587 const struct submodule *sub = NULL;
1588 const char *url = NULL;
1589 const char *update_string;
1590 enum submodule_update_type update_type;
1591 char *key;
1592 struct strbuf displaypath_sb = STRBUF_INIT;
1593 struct strbuf sb = STRBUF_INIT;
1594 const char *displaypath = NULL;
1595 int needs_cloning = 0;
1596 int need_free_url = 0;
1598 if (ce_stage(ce)) {
1599 if (suc->recursive_prefix)
1600 strbuf_addf(&sb, "%s/%s", suc->recursive_prefix, ce->name);
1601 else
1602 strbuf_addstr(&sb, ce->name);
1603 strbuf_addf(out, _("Skipping unmerged submodule %s"), sb.buf);
1604 strbuf_addch(out, '\n');
1605 goto cleanup;
1608 sub = submodule_from_path(the_repository, &null_oid, ce->name);
1610 if (suc->recursive_prefix)
1611 displaypath = relative_path(suc->recursive_prefix,
1612 ce->name, &displaypath_sb);
1613 else
1614 displaypath = ce->name;
1616 if (!sub) {
1617 next_submodule_warn_missing(suc, out, displaypath);
1618 goto cleanup;
1621 key = xstrfmt("submodule.%s.update", sub->name);
1622 if (!repo_config_get_string_const(the_repository, key, &update_string)) {
1623 update_type = parse_submodule_update_type(update_string);
1624 } else {
1625 update_type = sub->update_strategy.type;
1627 free(key);
1629 if (suc->update.type == SM_UPDATE_NONE
1630 || (suc->update.type == SM_UPDATE_UNSPECIFIED
1631 && update_type == SM_UPDATE_NONE)) {
1632 strbuf_addf(out, _("Skipping submodule '%s'"), displaypath);
1633 strbuf_addch(out, '\n');
1634 goto cleanup;
1637 /* Check if the submodule has been initialized. */
1638 if (!is_submodule_active(the_repository, ce->name)) {
1639 next_submodule_warn_missing(suc, out, displaypath);
1640 goto cleanup;
1643 strbuf_reset(&sb);
1644 strbuf_addf(&sb, "submodule.%s.url", sub->name);
1645 if (repo_config_get_string_const(the_repository, sb.buf, &url)) {
1646 if (starts_with_dot_slash(sub->url) ||
1647 starts_with_dot_dot_slash(sub->url)) {
1648 url = compute_submodule_clone_url(sub->url);
1649 need_free_url = 1;
1650 } else
1651 url = sub->url;
1654 strbuf_reset(&sb);
1655 strbuf_addf(&sb, "%s/.git", ce->name);
1656 needs_cloning = !file_exists(sb.buf);
1658 ALLOC_GROW(suc->update_clone, suc->update_clone_nr + 1,
1659 suc->update_clone_alloc);
1660 oidcpy(&suc->update_clone[suc->update_clone_nr].oid, &ce->oid);
1661 suc->update_clone[suc->update_clone_nr].just_cloned = needs_cloning;
1662 suc->update_clone[suc->update_clone_nr].sub = sub;
1663 suc->update_clone_nr++;
1665 if (!needs_cloning)
1666 goto cleanup;
1668 child->git_cmd = 1;
1669 child->no_stdin = 1;
1670 child->stdout_to_stderr = 1;
1671 child->err = -1;
1672 argv_array_push(&child->args, "submodule--helper");
1673 argv_array_push(&child->args, "clone");
1674 if (suc->progress)
1675 argv_array_push(&child->args, "--progress");
1676 if (suc->quiet)
1677 argv_array_push(&child->args, "--quiet");
1678 if (suc->prefix)
1679 argv_array_pushl(&child->args, "--prefix", suc->prefix, NULL);
1680 if (suc->recommend_shallow && sub->recommend_shallow == 1)
1681 argv_array_push(&child->args, "--depth=1");
1682 argv_array_pushl(&child->args, "--path", sub->path, NULL);
1683 argv_array_pushl(&child->args, "--name", sub->name, NULL);
1684 argv_array_pushl(&child->args, "--url", url, NULL);
1685 if (suc->references.nr) {
1686 struct string_list_item *item;
1687 for_each_string_list_item(item, &suc->references)
1688 argv_array_pushl(&child->args, "--reference", item->string, NULL);
1690 if (suc->dissociate)
1691 argv_array_push(&child->args, "--dissociate");
1692 if (suc->depth)
1693 argv_array_push(&child->args, suc->depth);
1695 cleanup:
1696 strbuf_reset(&displaypath_sb);
1697 strbuf_reset(&sb);
1698 if (need_free_url)
1699 free((void*)url);
1701 return needs_cloning;
1704 static int update_clone_get_next_task(struct child_process *child,
1705 struct strbuf *err,
1706 void *suc_cb,
1707 void **idx_task_cb)
1709 struct submodule_update_clone *suc = suc_cb;
1710 const struct cache_entry *ce;
1711 int index;
1713 for (; suc->current < suc->list.nr; suc->current++) {
1714 ce = suc->list.entries[suc->current];
1715 if (prepare_to_clone_next_submodule(ce, child, suc, err)) {
1716 int *p = xmalloc(sizeof(*p));
1717 *p = suc->current;
1718 *idx_task_cb = p;
1719 suc->current++;
1720 return 1;
1725 * The loop above tried cloning each submodule once, now try the
1726 * stragglers again, which we can imagine as an extension of the
1727 * entry list.
1729 index = suc->current - suc->list.nr;
1730 if (index < suc->failed_clones_nr) {
1731 int *p;
1732 ce = suc->failed_clones[index];
1733 if (!prepare_to_clone_next_submodule(ce, child, suc, err)) {
1734 suc->current ++;
1735 strbuf_addstr(err, "BUG: submodule considered for "
1736 "cloning, doesn't need cloning "
1737 "any more?\n");
1738 return 0;
1740 p = xmalloc(sizeof(*p));
1741 *p = suc->current;
1742 *idx_task_cb = p;
1743 suc->current ++;
1744 return 1;
1747 return 0;
1750 static int update_clone_start_failure(struct strbuf *err,
1751 void *suc_cb,
1752 void *idx_task_cb)
1754 struct submodule_update_clone *suc = suc_cb;
1755 suc->quickstop = 1;
1756 return 1;
1759 static int update_clone_task_finished(int result,
1760 struct strbuf *err,
1761 void *suc_cb,
1762 void *idx_task_cb)
1764 const struct cache_entry *ce;
1765 struct submodule_update_clone *suc = suc_cb;
1767 int *idxP = idx_task_cb;
1768 int idx = *idxP;
1769 free(idxP);
1771 if (!result)
1772 return 0;
1774 if (idx < suc->list.nr) {
1775 ce = suc->list.entries[idx];
1776 strbuf_addf(err, _("Failed to clone '%s'. Retry scheduled"),
1777 ce->name);
1778 strbuf_addch(err, '\n');
1779 ALLOC_GROW(suc->failed_clones,
1780 suc->failed_clones_nr + 1,
1781 suc->failed_clones_alloc);
1782 suc->failed_clones[suc->failed_clones_nr++] = ce;
1783 return 0;
1784 } else {
1785 idx -= suc->list.nr;
1786 ce = suc->failed_clones[idx];
1787 strbuf_addf(err, _("Failed to clone '%s' a second time, aborting"),
1788 ce->name);
1789 strbuf_addch(err, '\n');
1790 suc->quickstop = 1;
1791 return 1;
1794 return 0;
1797 static int git_update_clone_config(const char *var, const char *value,
1798 void *cb)
1800 int *max_jobs = cb;
1801 if (!strcmp(var, "submodule.fetchjobs"))
1802 *max_jobs = parse_submodule_fetchjobs(var, value);
1803 return 0;
1806 static void update_submodule(struct update_clone_data *ucd)
1808 fprintf(stdout, "dummy %s %d\t%s\n",
1809 oid_to_hex(&ucd->oid),
1810 ucd->just_cloned,
1811 ucd->sub->path);
1814 static int update_submodules(struct submodule_update_clone *suc)
1816 int i;
1818 run_processes_parallel(suc->max_jobs,
1819 update_clone_get_next_task,
1820 update_clone_start_failure,
1821 update_clone_task_finished,
1822 suc);
1825 * We saved the output and put it out all at once now.
1826 * That means:
1827 * - the listener does not have to interleave their (checkout)
1828 * work with our fetching. The writes involved in a
1829 * checkout involve more straightforward sequential I/O.
1830 * - the listener can avoid doing any work if fetching failed.
1832 if (suc->quickstop)
1833 return 1;
1835 for (i = 0; i < suc->update_clone_nr; i++)
1836 update_submodule(&suc->update_clone[i]);
1838 return 0;
1841 static int update_clone(int argc, const char **argv, const char *prefix)
1843 const char *update = NULL;
1844 struct pathspec pathspec;
1845 struct submodule_update_clone suc = SUBMODULE_UPDATE_CLONE_INIT;
1847 struct option module_update_clone_options[] = {
1848 OPT_STRING(0, "prefix", &prefix,
1849 N_("path"),
1850 N_("path into the working tree")),
1851 OPT_STRING(0, "recursive-prefix", &suc.recursive_prefix,
1852 N_("path"),
1853 N_("path into the working tree, across nested "
1854 "submodule boundaries")),
1855 OPT_STRING(0, "update", &update,
1856 N_("string"),
1857 N_("rebase, merge, checkout or none")),
1858 OPT_STRING_LIST(0, "reference", &suc.references, N_("repo"),
1859 N_("reference repository")),
1860 OPT_BOOL(0, "dissociate", &suc.dissociate,
1861 N_("use --reference only while cloning")),
1862 OPT_STRING(0, "depth", &suc.depth, "<depth>",
1863 N_("Create a shallow clone truncated to the "
1864 "specified number of revisions")),
1865 OPT_INTEGER('j', "jobs", &suc.max_jobs,
1866 N_("parallel jobs")),
1867 OPT_BOOL(0, "recommend-shallow", &suc.recommend_shallow,
1868 N_("whether the initial clone should follow the shallow recommendation")),
1869 OPT__QUIET(&suc.quiet, N_("don't print cloning progress")),
1870 OPT_BOOL(0, "progress", &suc.progress,
1871 N_("force cloning progress")),
1872 OPT_END()
1875 const char *const git_submodule_helper_usage[] = {
1876 N_("git submodule--helper update_clone [--prefix=<path>] [<path>...]"),
1877 NULL
1879 suc.prefix = prefix;
1881 update_clone_config_from_gitmodules(&suc.max_jobs);
1882 git_config(git_update_clone_config, &suc.max_jobs);
1884 argc = parse_options(argc, argv, prefix, module_update_clone_options,
1885 git_submodule_helper_usage, 0);
1887 if (update)
1888 if (parse_submodule_update_strategy(update, &suc.update) < 0)
1889 die(_("bad value for update parameter"));
1891 if (module_list_compute(argc, argv, prefix, &pathspec, &suc.list) < 0)
1892 return 1;
1894 if (pathspec.nr)
1895 suc.warn_if_uninitialized = 1;
1897 return update_submodules(&suc);
1900 static int resolve_relative_path(int argc, const char **argv, const char *prefix)
1902 struct strbuf sb = STRBUF_INIT;
1903 if (argc != 3)
1904 die("submodule--helper relative-path takes exactly 2 arguments, got %d", argc);
1906 printf("%s", relative_path(argv[1], argv[2], &sb));
1907 strbuf_release(&sb);
1908 return 0;
1911 static const char *remote_submodule_branch(const char *path)
1913 const struct submodule *sub;
1914 const char *branch = NULL;
1915 char *key;
1917 sub = submodule_from_path(the_repository, &null_oid, path);
1918 if (!sub)
1919 return NULL;
1921 key = xstrfmt("submodule.%s.branch", sub->name);
1922 if (repo_config_get_string_const(the_repository, key, &branch))
1923 branch = sub->branch;
1924 free(key);
1926 if (!branch)
1927 return "master";
1929 if (!strcmp(branch, ".")) {
1930 const char *refname = resolve_ref_unsafe("HEAD", 0, NULL, NULL);
1932 if (!refname)
1933 die(_("No such ref: %s"), "HEAD");
1935 /* detached HEAD */
1936 if (!strcmp(refname, "HEAD"))
1937 die(_("Submodule (%s) branch configured to inherit "
1938 "branch from superproject, but the superproject "
1939 "is not on any branch"), sub->name);
1941 if (!skip_prefix(refname, "refs/heads/", &refname))
1942 die(_("Expecting a full ref name, got %s"), refname);
1943 return refname;
1946 return branch;
1949 static int resolve_remote_submodule_branch(int argc, const char **argv,
1950 const char *prefix)
1952 const char *ret;
1953 struct strbuf sb = STRBUF_INIT;
1954 if (argc != 2)
1955 die("submodule--helper remote-branch takes exactly one arguments, got %d", argc);
1957 ret = remote_submodule_branch(argv[1]);
1958 if (!ret)
1959 die("submodule %s doesn't exist", argv[1]);
1961 printf("%s", ret);
1962 strbuf_release(&sb);
1963 return 0;
1966 static int push_check(int argc, const char **argv, const char *prefix)
1968 struct remote *remote;
1969 const char *superproject_head;
1970 char *head;
1971 int detached_head = 0;
1972 struct object_id head_oid;
1974 if (argc < 3)
1975 die("submodule--helper push-check requires at least 2 arguments");
1978 * superproject's resolved head ref.
1979 * if HEAD then the superproject is in a detached head state, otherwise
1980 * it will be the resolved head ref.
1982 superproject_head = argv[1];
1983 argv++;
1984 argc--;
1985 /* Get the submodule's head ref and determine if it is detached */
1986 head = resolve_refdup("HEAD", 0, &head_oid, NULL);
1987 if (!head)
1988 die(_("Failed to resolve HEAD as a valid ref."));
1989 if (!strcmp(head, "HEAD"))
1990 detached_head = 1;
1993 * The remote must be configured.
1994 * This is to avoid pushing to the exact same URL as the parent.
1996 remote = pushremote_get(argv[1]);
1997 if (!remote || remote->origin == REMOTE_UNCONFIGURED)
1998 die("remote '%s' not configured", argv[1]);
2000 /* Check the refspec */
2001 if (argc > 2) {
2002 int i;
2003 struct ref *local_refs = get_local_heads();
2004 struct refspec refspec = REFSPEC_INIT_PUSH;
2006 refspec_appendn(&refspec, argv + 2, argc - 2);
2008 for (i = 0; i < refspec.nr; i++) {
2009 const struct refspec_item *rs = &refspec.items[i];
2011 if (rs->pattern || rs->matching)
2012 continue;
2014 /* LHS must match a single ref */
2015 switch (count_refspec_match(rs->src, local_refs, NULL)) {
2016 case 1:
2017 break;
2018 case 0:
2020 * If LHS matches 'HEAD' then we need to ensure
2021 * that it matches the same named branch
2022 * checked out in the superproject.
2024 if (!strcmp(rs->src, "HEAD")) {
2025 if (!detached_head &&
2026 !strcmp(head, superproject_head))
2027 break;
2028 die("HEAD does not match the named branch in the superproject");
2030 /* fallthrough */
2031 default:
2032 die("src refspec '%s' must name a ref",
2033 rs->src);
2036 refspec_clear(&refspec);
2038 free(head);
2040 return 0;
2043 static int ensure_core_worktree(int argc, const char **argv, const char *prefix)
2045 const struct submodule *sub;
2046 const char *path;
2047 char *cw;
2048 struct repository subrepo;
2050 if (argc != 2)
2051 BUG("submodule--helper ensure-core-worktree <path>");
2053 path = argv[1];
2055 sub = submodule_from_path(the_repository, &null_oid, path);
2056 if (!sub)
2057 BUG("We could get the submodule handle before?");
2059 if (repo_submodule_init(&subrepo, the_repository, path))
2060 die(_("could not get a repository handle for submodule '%s'"), path);
2062 if (!repo_config_get_string(&subrepo, "core.worktree", &cw)) {
2063 char *cfg_file, *abs_path;
2064 const char *rel_path;
2065 struct strbuf sb = STRBUF_INIT;
2067 cfg_file = repo_git_path(&subrepo, "config");
2069 abs_path = absolute_pathdup(path);
2070 rel_path = relative_path(abs_path, subrepo.gitdir, &sb);
2072 git_config_set_in_file(cfg_file, "core.worktree", rel_path);
2074 free(cfg_file);
2075 free(abs_path);
2076 strbuf_release(&sb);
2079 return 0;
2082 static int absorb_git_dirs(int argc, const char **argv, const char *prefix)
2084 int i;
2085 struct pathspec pathspec;
2086 struct module_list list = MODULE_LIST_INIT;
2087 unsigned flags = ABSORB_GITDIR_RECURSE_SUBMODULES;
2089 struct option embed_gitdir_options[] = {
2090 OPT_STRING(0, "prefix", &prefix,
2091 N_("path"),
2092 N_("path into the working tree")),
2093 OPT_BIT(0, "--recursive", &flags, N_("recurse into submodules"),
2094 ABSORB_GITDIR_RECURSE_SUBMODULES),
2095 OPT_END()
2098 const char *const git_submodule_helper_usage[] = {
2099 N_("git submodule--helper embed-git-dir [<path>...]"),
2100 NULL
2103 argc = parse_options(argc, argv, prefix, embed_gitdir_options,
2104 git_submodule_helper_usage, 0);
2106 if (module_list_compute(argc, argv, prefix, &pathspec, &list) < 0)
2107 return 1;
2109 for (i = 0; i < list.nr; i++)
2110 absorb_git_dir_into_superproject(prefix,
2111 list.entries[i]->name, flags);
2113 return 0;
2116 static int is_active(int argc, const char **argv, const char *prefix)
2118 if (argc != 2)
2119 die("submodule--helper is-active takes exactly 1 argument");
2121 return !is_submodule_active(the_repository, argv[1]);
2125 * Exit non-zero if any of the submodule names given on the command line is
2126 * invalid. If no names are given, filter stdin to print only valid names
2127 * (which is primarily intended for testing).
2129 static int check_name(int argc, const char **argv, const char *prefix)
2131 if (argc > 1) {
2132 while (*++argv) {
2133 if (check_submodule_name(*argv) < 0)
2134 return 1;
2136 } else {
2137 struct strbuf buf = STRBUF_INIT;
2138 while (strbuf_getline(&buf, stdin) != EOF) {
2139 if (!check_submodule_name(buf.buf))
2140 printf("%s\n", buf.buf);
2142 strbuf_release(&buf);
2144 return 0;
2147 static int module_config(int argc, const char **argv, const char *prefix)
2149 enum {
2150 CHECK_WRITEABLE = 1
2151 } command = 0;
2153 struct option module_config_options[] = {
2154 OPT_CMDMODE(0, "check-writeable", &command,
2155 N_("check if it is safe to write to the .gitmodules file"),
2156 CHECK_WRITEABLE),
2157 OPT_END()
2159 const char *const git_submodule_helper_usage[] = {
2160 N_("git submodule--helper config name [value]"),
2161 N_("git submodule--helper config --check-writeable"),
2162 NULL
2165 argc = parse_options(argc, argv, prefix, module_config_options,
2166 git_submodule_helper_usage, PARSE_OPT_KEEP_ARGV0);
2168 if (argc == 1 && command == CHECK_WRITEABLE)
2169 return is_writing_gitmodules_ok() ? 0 : -1;
2171 /* Equivalent to ACTION_GET in builtin/config.c */
2172 if (argc == 2)
2173 return print_config_from_gitmodules(the_repository, argv[1]);
2175 /* Equivalent to ACTION_SET in builtin/config.c */
2176 if (argc == 3) {
2177 if (!is_writing_gitmodules_ok())
2178 die(_("please make sure that the .gitmodules file is in the working tree"));
2180 return config_set_in_gitmodules_file_gently(argv[1], argv[2]);
2183 usage_with_options(git_submodule_helper_usage, module_config_options);
2186 #define SUPPORT_SUPER_PREFIX (1<<0)
2188 struct cmd_struct {
2189 const char *cmd;
2190 int (*fn)(int, const char **, const char *);
2191 unsigned option;
2194 static struct cmd_struct commands[] = {
2195 {"list", module_list, 0},
2196 {"name", module_name, 0},
2197 {"clone", module_clone, 0},
2198 {"update-module-mode", module_update_module_mode, 0},
2199 {"update-clone", update_clone, 0},
2200 {"ensure-core-worktree", ensure_core_worktree, 0},
2201 {"relative-path", resolve_relative_path, 0},
2202 {"resolve-relative-url", resolve_relative_url, 0},
2203 {"resolve-relative-url-test", resolve_relative_url_test, 0},
2204 {"foreach", module_foreach, SUPPORT_SUPER_PREFIX},
2205 {"init", module_init, SUPPORT_SUPER_PREFIX},
2206 {"status", module_status, SUPPORT_SUPER_PREFIX},
2207 {"print-default-remote", print_default_remote, 0},
2208 {"sync", module_sync, SUPPORT_SUPER_PREFIX},
2209 {"deinit", module_deinit, 0},
2210 {"remote-branch", resolve_remote_submodule_branch, 0},
2211 {"push-check", push_check, 0},
2212 {"absorb-git-dirs", absorb_git_dirs, SUPPORT_SUPER_PREFIX},
2213 {"is-active", is_active, 0},
2214 {"check-name", check_name, 0},
2215 {"config", module_config, 0},
2218 int cmd_submodule__helper(int argc, const char **argv, const char *prefix)
2220 int i;
2221 if (argc < 2 || !strcmp(argv[1], "-h"))
2222 usage("git submodule--helper <command>");
2224 for (i = 0; i < ARRAY_SIZE(commands); i++) {
2225 if (!strcmp(argv[1], commands[i].cmd)) {
2226 if (get_super_prefix() &&
2227 !(commands[i].option & SUPPORT_SUPER_PREFIX))
2228 die(_("%s doesn't support --super-prefix"),
2229 commands[i].cmd);
2230 return commands[i].fn(argc - 1, argv + 1, prefix);
2234 die(_("'%s' is not a valid submodule--helper "
2235 "subcommand"), argv[1]);