Merge branch 'sg/t4051-fix'
[git.git] / builtin / submodule--helper.c
blob2bcc70fdfe2608ccbbab02b6f593dd81781ada41
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 struct init_cb {
588 const char *prefix;
589 unsigned int flags;
592 #define INIT_CB_INIT { NULL, 0 }
594 static void init_submodule(const char *path, const char *prefix,
595 unsigned int flags)
597 const struct submodule *sub;
598 struct strbuf sb = STRBUF_INIT;
599 char *upd = NULL, *url = NULL, *displaypath;
601 displaypath = get_submodule_displaypath(path, prefix);
603 sub = submodule_from_path(the_repository, &null_oid, path);
605 if (!sub)
606 die(_("No url found for submodule path '%s' in .gitmodules"),
607 displaypath);
610 * NEEDSWORK: In a multi-working-tree world, this needs to be
611 * set in the per-worktree config.
613 * Set active flag for the submodule being initialized
615 if (!is_submodule_active(the_repository, path)) {
616 strbuf_addf(&sb, "submodule.%s.active", sub->name);
617 git_config_set_gently(sb.buf, "true");
618 strbuf_reset(&sb);
622 * Copy url setting when it is not set yet.
623 * To look up the url in .git/config, we must not fall back to
624 * .gitmodules, so look it up directly.
626 strbuf_addf(&sb, "submodule.%s.url", sub->name);
627 if (git_config_get_string(sb.buf, &url)) {
628 if (!sub->url)
629 die(_("No url found for submodule path '%s' in .gitmodules"),
630 displaypath);
632 url = xstrdup(sub->url);
634 /* Possibly a url relative to parent */
635 if (starts_with_dot_dot_slash(url) ||
636 starts_with_dot_slash(url)) {
637 char *remoteurl, *relurl;
638 char *remote = get_default_remote();
639 struct strbuf remotesb = STRBUF_INIT;
640 strbuf_addf(&remotesb, "remote.%s.url", remote);
641 free(remote);
643 if (git_config_get_string(remotesb.buf, &remoteurl)) {
644 warning(_("could not lookup configuration '%s'. Assuming this repository is its own authoritative upstream."), remotesb.buf);
645 remoteurl = xgetcwd();
647 relurl = relative_url(remoteurl, url, NULL);
648 strbuf_release(&remotesb);
649 free(remoteurl);
650 free(url);
651 url = relurl;
654 if (git_config_set_gently(sb.buf, url))
655 die(_("Failed to register url for submodule path '%s'"),
656 displaypath);
657 if (!(flags & OPT_QUIET))
658 fprintf(stderr,
659 _("Submodule '%s' (%s) registered for path '%s'\n"),
660 sub->name, url, displaypath);
662 strbuf_reset(&sb);
664 /* Copy "update" setting when it is not set yet */
665 strbuf_addf(&sb, "submodule.%s.update", sub->name);
666 if (git_config_get_string(sb.buf, &upd) &&
667 sub->update_strategy.type != SM_UPDATE_UNSPECIFIED) {
668 if (sub->update_strategy.type == SM_UPDATE_COMMAND) {
669 fprintf(stderr, _("warning: command update mode suggested for submodule '%s'\n"),
670 sub->name);
671 upd = xstrdup("none");
672 } else
673 upd = xstrdup(submodule_strategy_to_string(&sub->update_strategy));
675 if (git_config_set_gently(sb.buf, upd))
676 die(_("Failed to register update mode for submodule path '%s'"), displaypath);
678 strbuf_release(&sb);
679 free(displaypath);
680 free(url);
681 free(upd);
684 static void init_submodule_cb(const struct cache_entry *list_item, void *cb_data)
686 struct init_cb *info = cb_data;
687 init_submodule(list_item->name, info->prefix, info->flags);
690 static int module_init(int argc, const char **argv, const char *prefix)
692 struct init_cb info = INIT_CB_INIT;
693 struct pathspec pathspec;
694 struct module_list list = MODULE_LIST_INIT;
695 int quiet = 0;
697 struct option module_init_options[] = {
698 OPT__QUIET(&quiet, N_("Suppress output for initializing a submodule")),
699 OPT_END()
702 const char *const git_submodule_helper_usage[] = {
703 N_("git submodule--helper init [<path>]"),
704 NULL
707 argc = parse_options(argc, argv, prefix, module_init_options,
708 git_submodule_helper_usage, 0);
710 if (module_list_compute(argc, argv, prefix, &pathspec, &list) < 0)
711 return 1;
714 * If there are no path args and submodule.active is set then,
715 * by default, only initialize 'active' modules.
717 if (!argc && git_config_get_value_multi("submodule.active"))
718 module_list_active(&list);
720 info.prefix = prefix;
721 if (quiet)
722 info.flags |= OPT_QUIET;
724 for_each_listed_submodule(&list, init_submodule_cb, &info);
726 return 0;
729 struct status_cb {
730 const char *prefix;
731 unsigned int flags;
734 #define STATUS_CB_INIT { NULL, 0 }
736 static void print_status(unsigned int flags, char state, const char *path,
737 const struct object_id *oid, const char *displaypath)
739 if (flags & OPT_QUIET)
740 return;
742 printf("%c%s %s", state, oid_to_hex(oid), displaypath);
744 if (state == ' ' || state == '+') {
745 const char *name = compute_rev_name(path, oid_to_hex(oid));
747 if (name)
748 printf(" (%s)", name);
751 printf("\n");
754 static int handle_submodule_head_ref(const char *refname,
755 const struct object_id *oid, int flags,
756 void *cb_data)
758 struct object_id *output = cb_data;
759 if (oid)
760 oidcpy(output, oid);
762 return 0;
765 static void status_submodule(const char *path, const struct object_id *ce_oid,
766 unsigned int ce_flags, const char *prefix,
767 unsigned int flags)
769 char *displaypath;
770 struct argv_array diff_files_args = ARGV_ARRAY_INIT;
771 struct rev_info rev;
772 int diff_files_result;
774 if (!submodule_from_path(the_repository, &null_oid, path))
775 die(_("no submodule mapping found in .gitmodules for path '%s'"),
776 path);
778 displaypath = get_submodule_displaypath(path, prefix);
780 if ((CE_STAGEMASK & ce_flags) >> CE_STAGESHIFT) {
781 print_status(flags, 'U', path, &null_oid, displaypath);
782 goto cleanup;
785 if (!is_submodule_active(the_repository, path)) {
786 print_status(flags, '-', path, ce_oid, displaypath);
787 goto cleanup;
790 argv_array_pushl(&diff_files_args, "diff-files",
791 "--ignore-submodules=dirty", "--quiet", "--",
792 path, NULL);
794 git_config(git_diff_basic_config, NULL);
795 init_revisions(&rev, prefix);
796 rev.abbrev = 0;
797 diff_files_args.argc = setup_revisions(diff_files_args.argc,
798 diff_files_args.argv,
799 &rev, NULL);
800 diff_files_result = run_diff_files(&rev, 0);
802 if (!diff_result_code(&rev.diffopt, diff_files_result)) {
803 print_status(flags, ' ', path, ce_oid,
804 displaypath);
805 } else if (!(flags & OPT_CACHED)) {
806 struct object_id oid;
807 struct ref_store *refs = get_submodule_ref_store(path);
809 if (!refs) {
810 print_status(flags, '-', path, ce_oid, displaypath);
811 goto cleanup;
813 if (refs_head_ref(refs, handle_submodule_head_ref, &oid))
814 die(_("could not resolve HEAD ref inside the "
815 "submodule '%s'"), path);
817 print_status(flags, '+', path, &oid, displaypath);
818 } else {
819 print_status(flags, '+', path, ce_oid, displaypath);
822 if (flags & OPT_RECURSIVE) {
823 struct child_process cpr = CHILD_PROCESS_INIT;
825 cpr.git_cmd = 1;
826 cpr.dir = path;
827 prepare_submodule_repo_env(&cpr.env_array);
829 argv_array_push(&cpr.args, "--super-prefix");
830 argv_array_pushf(&cpr.args, "%s/", displaypath);
831 argv_array_pushl(&cpr.args, "submodule--helper", "status",
832 "--recursive", NULL);
834 if (flags & OPT_CACHED)
835 argv_array_push(&cpr.args, "--cached");
837 if (flags & OPT_QUIET)
838 argv_array_push(&cpr.args, "--quiet");
840 if (run_command(&cpr))
841 die(_("failed to recurse into submodule '%s'"), path);
844 cleanup:
845 argv_array_clear(&diff_files_args);
846 free(displaypath);
849 static void status_submodule_cb(const struct cache_entry *list_item,
850 void *cb_data)
852 struct status_cb *info = cb_data;
853 status_submodule(list_item->name, &list_item->oid, list_item->ce_flags,
854 info->prefix, info->flags);
857 static int module_status(int argc, const char **argv, const char *prefix)
859 struct status_cb info = STATUS_CB_INIT;
860 struct pathspec pathspec;
861 struct module_list list = MODULE_LIST_INIT;
862 int quiet = 0;
864 struct option module_status_options[] = {
865 OPT__QUIET(&quiet, N_("Suppress submodule status output")),
866 OPT_BIT(0, "cached", &info.flags, N_("Use commit stored in the index instead of the one stored in the submodule HEAD"), OPT_CACHED),
867 OPT_BIT(0, "recursive", &info.flags, N_("recurse into nested submodules"), OPT_RECURSIVE),
868 OPT_END()
871 const char *const git_submodule_helper_usage[] = {
872 N_("git submodule status [--quiet] [--cached] [--recursive] [<path>...]"),
873 NULL
876 argc = parse_options(argc, argv, prefix, module_status_options,
877 git_submodule_helper_usage, 0);
879 if (module_list_compute(argc, argv, prefix, &pathspec, &list) < 0)
880 return 1;
882 info.prefix = prefix;
883 if (quiet)
884 info.flags |= OPT_QUIET;
886 for_each_listed_submodule(&list, status_submodule_cb, &info);
888 return 0;
891 static int module_name(int argc, const char **argv, const char *prefix)
893 const struct submodule *sub;
895 if (argc != 2)
896 usage(_("git submodule--helper name <path>"));
898 sub = submodule_from_path(the_repository, &null_oid, argv[1]);
900 if (!sub)
901 die(_("no submodule mapping found in .gitmodules for path '%s'"),
902 argv[1]);
904 printf("%s\n", sub->name);
906 return 0;
909 struct sync_cb {
910 const char *prefix;
911 unsigned int flags;
914 #define SYNC_CB_INIT { NULL, 0 }
916 static void sync_submodule(const char *path, const char *prefix,
917 unsigned int flags)
919 const struct submodule *sub;
920 char *remote_key = NULL;
921 char *sub_origin_url, *super_config_url, *displaypath;
922 struct strbuf sb = STRBUF_INIT;
923 struct child_process cp = CHILD_PROCESS_INIT;
924 char *sub_config_path = NULL;
926 if (!is_submodule_active(the_repository, path))
927 return;
929 sub = submodule_from_path(the_repository, &null_oid, path);
931 if (sub && sub->url) {
932 if (starts_with_dot_dot_slash(sub->url) ||
933 starts_with_dot_slash(sub->url)) {
934 char *remote_url, *up_path;
935 char *remote = get_default_remote();
936 strbuf_addf(&sb, "remote.%s.url", remote);
938 if (git_config_get_string(sb.buf, &remote_url))
939 remote_url = xgetcwd();
941 up_path = get_up_path(path);
942 sub_origin_url = relative_url(remote_url, sub->url, up_path);
943 super_config_url = relative_url(remote_url, sub->url, NULL);
945 free(remote);
946 free(up_path);
947 free(remote_url);
948 } else {
949 sub_origin_url = xstrdup(sub->url);
950 super_config_url = xstrdup(sub->url);
952 } else {
953 sub_origin_url = xstrdup("");
954 super_config_url = xstrdup("");
957 displaypath = get_submodule_displaypath(path, prefix);
959 if (!(flags & OPT_QUIET))
960 printf(_("Synchronizing submodule url for '%s'\n"),
961 displaypath);
963 strbuf_reset(&sb);
964 strbuf_addf(&sb, "submodule.%s.url", sub->name);
965 if (git_config_set_gently(sb.buf, super_config_url))
966 die(_("failed to register url for submodule path '%s'"),
967 displaypath);
969 if (!is_submodule_populated_gently(path, NULL))
970 goto cleanup;
972 prepare_submodule_repo_env(&cp.env_array);
973 cp.git_cmd = 1;
974 cp.dir = path;
975 argv_array_pushl(&cp.args, "submodule--helper",
976 "print-default-remote", NULL);
978 strbuf_reset(&sb);
979 if (capture_command(&cp, &sb, 0))
980 die(_("failed to get the default remote for submodule '%s'"),
981 path);
983 strbuf_strip_suffix(&sb, "\n");
984 remote_key = xstrfmt("remote.%s.url", sb.buf);
986 strbuf_reset(&sb);
987 submodule_to_gitdir(&sb, path);
988 strbuf_addstr(&sb, "/config");
990 if (git_config_set_in_file_gently(sb.buf, remote_key, sub_origin_url))
991 die(_("failed to update remote for submodule '%s'"),
992 path);
994 if (flags & OPT_RECURSIVE) {
995 struct child_process cpr = CHILD_PROCESS_INIT;
997 cpr.git_cmd = 1;
998 cpr.dir = path;
999 prepare_submodule_repo_env(&cpr.env_array);
1001 argv_array_push(&cpr.args, "--super-prefix");
1002 argv_array_pushf(&cpr.args, "%s/", displaypath);
1003 argv_array_pushl(&cpr.args, "submodule--helper", "sync",
1004 "--recursive", NULL);
1006 if (flags & OPT_QUIET)
1007 argv_array_push(&cpr.args, "--quiet");
1009 if (run_command(&cpr))
1010 die(_("failed to recurse into submodule '%s'"),
1011 path);
1014 cleanup:
1015 free(super_config_url);
1016 free(sub_origin_url);
1017 strbuf_release(&sb);
1018 free(remote_key);
1019 free(displaypath);
1020 free(sub_config_path);
1023 static void sync_submodule_cb(const struct cache_entry *list_item, void *cb_data)
1025 struct sync_cb *info = cb_data;
1026 sync_submodule(list_item->name, info->prefix, info->flags);
1029 static int module_sync(int argc, const char **argv, const char *prefix)
1031 struct sync_cb info = SYNC_CB_INIT;
1032 struct pathspec pathspec;
1033 struct module_list list = MODULE_LIST_INIT;
1034 int quiet = 0;
1035 int recursive = 0;
1037 struct option module_sync_options[] = {
1038 OPT__QUIET(&quiet, N_("Suppress output of synchronizing submodule url")),
1039 OPT_BOOL(0, "recursive", &recursive,
1040 N_("Recurse into nested submodules")),
1041 OPT_END()
1044 const char *const git_submodule_helper_usage[] = {
1045 N_("git submodule--helper sync [--quiet] [--recursive] [<path>]"),
1046 NULL
1049 argc = parse_options(argc, argv, prefix, module_sync_options,
1050 git_submodule_helper_usage, 0);
1052 if (module_list_compute(argc, argv, prefix, &pathspec, &list) < 0)
1053 return 1;
1055 info.prefix = prefix;
1056 if (quiet)
1057 info.flags |= OPT_QUIET;
1058 if (recursive)
1059 info.flags |= OPT_RECURSIVE;
1061 for_each_listed_submodule(&list, sync_submodule_cb, &info);
1063 return 0;
1066 struct deinit_cb {
1067 const char *prefix;
1068 unsigned int flags;
1070 #define DEINIT_CB_INIT { NULL, 0 }
1072 static void deinit_submodule(const char *path, const char *prefix,
1073 unsigned int flags)
1075 const struct submodule *sub;
1076 char *displaypath = NULL;
1077 struct child_process cp_config = CHILD_PROCESS_INIT;
1078 struct strbuf sb_config = STRBUF_INIT;
1079 char *sub_git_dir = xstrfmt("%s/.git", path);
1081 sub = submodule_from_path(the_repository, &null_oid, path);
1083 if (!sub || !sub->name)
1084 goto cleanup;
1086 displaypath = get_submodule_displaypath(path, prefix);
1088 /* remove the submodule work tree (unless the user already did it) */
1089 if (is_directory(path)) {
1090 struct strbuf sb_rm = STRBUF_INIT;
1091 const char *format;
1094 * protect submodules containing a .git directory
1095 * NEEDSWORK: instead of dying, automatically call
1096 * absorbgitdirs and (possibly) warn.
1098 if (is_directory(sub_git_dir))
1099 die(_("Submodule work tree '%s' contains a .git "
1100 "directory (use 'rm -rf' if you really want "
1101 "to remove it including all of its history)"),
1102 displaypath);
1104 if (!(flags & OPT_FORCE)) {
1105 struct child_process cp_rm = CHILD_PROCESS_INIT;
1106 cp_rm.git_cmd = 1;
1107 argv_array_pushl(&cp_rm.args, "rm", "-qn",
1108 path, NULL);
1110 if (run_command(&cp_rm))
1111 die(_("Submodule work tree '%s' contains local "
1112 "modifications; use '-f' to discard them"),
1113 displaypath);
1116 strbuf_addstr(&sb_rm, path);
1118 if (!remove_dir_recursively(&sb_rm, 0))
1119 format = _("Cleared directory '%s'\n");
1120 else
1121 format = _("Could not remove submodule work tree '%s'\n");
1123 if (!(flags & OPT_QUIET))
1124 printf(format, displaypath);
1126 submodule_unset_core_worktree(sub);
1128 strbuf_release(&sb_rm);
1131 if (mkdir(path, 0777))
1132 printf(_("could not create empty submodule directory %s"),
1133 displaypath);
1135 cp_config.git_cmd = 1;
1136 argv_array_pushl(&cp_config.args, "config", "--get-regexp", NULL);
1137 argv_array_pushf(&cp_config.args, "submodule.%s\\.", sub->name);
1139 /* remove the .git/config entries (unless the user already did it) */
1140 if (!capture_command(&cp_config, &sb_config, 0) && sb_config.len) {
1141 char *sub_key = xstrfmt("submodule.%s", sub->name);
1143 * remove the whole section so we have a clean state when
1144 * the user later decides to init this submodule again
1146 git_config_rename_section_in_file(NULL, sub_key, NULL);
1147 if (!(flags & OPT_QUIET))
1148 printf(_("Submodule '%s' (%s) unregistered for path '%s'\n"),
1149 sub->name, sub->url, displaypath);
1150 free(sub_key);
1153 cleanup:
1154 free(displaypath);
1155 free(sub_git_dir);
1156 strbuf_release(&sb_config);
1159 static void deinit_submodule_cb(const struct cache_entry *list_item,
1160 void *cb_data)
1162 struct deinit_cb *info = cb_data;
1163 deinit_submodule(list_item->name, info->prefix, info->flags);
1166 static int module_deinit(int argc, const char **argv, const char *prefix)
1168 struct deinit_cb info = DEINIT_CB_INIT;
1169 struct pathspec pathspec;
1170 struct module_list list = MODULE_LIST_INIT;
1171 int quiet = 0;
1172 int force = 0;
1173 int all = 0;
1175 struct option module_deinit_options[] = {
1176 OPT__QUIET(&quiet, N_("Suppress submodule status output")),
1177 OPT__FORCE(&force, N_("Remove submodule working trees even if they contain local changes"), 0),
1178 OPT_BOOL(0, "all", &all, N_("Unregister all submodules")),
1179 OPT_END()
1182 const char *const git_submodule_helper_usage[] = {
1183 N_("git submodule deinit [--quiet] [-f | --force] [--all | [--] [<path>...]]"),
1184 NULL
1187 argc = parse_options(argc, argv, prefix, module_deinit_options,
1188 git_submodule_helper_usage, 0);
1190 if (all && argc) {
1191 error("pathspec and --all are incompatible");
1192 usage_with_options(git_submodule_helper_usage,
1193 module_deinit_options);
1196 if (!argc && !all)
1197 die(_("Use '--all' if you really want to deinitialize all submodules"));
1199 if (module_list_compute(argc, argv, prefix, &pathspec, &list) < 0)
1200 return 1;
1202 info.prefix = prefix;
1203 if (quiet)
1204 info.flags |= OPT_QUIET;
1205 if (force)
1206 info.flags |= OPT_FORCE;
1208 for_each_listed_submodule(&list, deinit_submodule_cb, &info);
1210 return 0;
1213 static int clone_submodule(const char *path, const char *gitdir, const char *url,
1214 const char *depth, struct string_list *reference, int dissociate,
1215 int quiet, int progress)
1217 struct child_process cp = CHILD_PROCESS_INIT;
1219 argv_array_push(&cp.args, "clone");
1220 argv_array_push(&cp.args, "--no-checkout");
1221 if (quiet)
1222 argv_array_push(&cp.args, "--quiet");
1223 if (progress)
1224 argv_array_push(&cp.args, "--progress");
1225 if (depth && *depth)
1226 argv_array_pushl(&cp.args, "--depth", depth, NULL);
1227 if (reference->nr) {
1228 struct string_list_item *item;
1229 for_each_string_list_item(item, reference)
1230 argv_array_pushl(&cp.args, "--reference",
1231 item->string, NULL);
1233 if (dissociate)
1234 argv_array_push(&cp.args, "--dissociate");
1235 if (gitdir && *gitdir)
1236 argv_array_pushl(&cp.args, "--separate-git-dir", gitdir, NULL);
1238 argv_array_push(&cp.args, url);
1239 argv_array_push(&cp.args, path);
1241 cp.git_cmd = 1;
1242 prepare_submodule_repo_env(&cp.env_array);
1243 cp.no_stdin = 1;
1245 return run_command(&cp);
1248 struct submodule_alternate_setup {
1249 const char *submodule_name;
1250 enum SUBMODULE_ALTERNATE_ERROR_MODE {
1251 SUBMODULE_ALTERNATE_ERROR_DIE,
1252 SUBMODULE_ALTERNATE_ERROR_INFO,
1253 SUBMODULE_ALTERNATE_ERROR_IGNORE
1254 } error_mode;
1255 struct string_list *reference;
1257 #define SUBMODULE_ALTERNATE_SETUP_INIT { NULL, \
1258 SUBMODULE_ALTERNATE_ERROR_IGNORE, NULL }
1260 static int add_possible_reference_from_superproject(
1261 struct alternate_object_database *alt, void *sas_cb)
1263 struct submodule_alternate_setup *sas = sas_cb;
1266 * If the alternate object store is another repository, try the
1267 * standard layout with .git/(modules/<name>)+/objects
1269 if (ends_with(alt->path, "/objects")) {
1270 char *sm_alternate;
1271 struct strbuf sb = STRBUF_INIT;
1272 struct strbuf err = STRBUF_INIT;
1273 strbuf_add(&sb, alt->path, strlen(alt->path) - strlen("objects"));
1276 * We need to end the new path with '/' to mark it as a dir,
1277 * otherwise a submodule name containing '/' will be broken
1278 * as the last part of a missing submodule reference would
1279 * be taken as a file name.
1281 strbuf_addf(&sb, "modules/%s/", sas->submodule_name);
1283 sm_alternate = compute_alternate_path(sb.buf, &err);
1284 if (sm_alternate) {
1285 string_list_append(sas->reference, xstrdup(sb.buf));
1286 free(sm_alternate);
1287 } else {
1288 switch (sas->error_mode) {
1289 case SUBMODULE_ALTERNATE_ERROR_DIE:
1290 die(_("submodule '%s' cannot add alternate: %s"),
1291 sas->submodule_name, err.buf);
1292 case SUBMODULE_ALTERNATE_ERROR_INFO:
1293 fprintf(stderr, _("submodule '%s' cannot add alternate: %s"),
1294 sas->submodule_name, err.buf);
1295 case SUBMODULE_ALTERNATE_ERROR_IGNORE:
1296 ; /* nothing */
1299 strbuf_release(&sb);
1302 return 0;
1305 static void prepare_possible_alternates(const char *sm_name,
1306 struct string_list *reference)
1308 char *sm_alternate = NULL, *error_strategy = NULL;
1309 struct submodule_alternate_setup sas = SUBMODULE_ALTERNATE_SETUP_INIT;
1311 git_config_get_string("submodule.alternateLocation", &sm_alternate);
1312 if (!sm_alternate)
1313 return;
1315 git_config_get_string("submodule.alternateErrorStrategy", &error_strategy);
1317 if (!error_strategy)
1318 error_strategy = xstrdup("die");
1320 sas.submodule_name = sm_name;
1321 sas.reference = reference;
1322 if (!strcmp(error_strategy, "die"))
1323 sas.error_mode = SUBMODULE_ALTERNATE_ERROR_DIE;
1324 else if (!strcmp(error_strategy, "info"))
1325 sas.error_mode = SUBMODULE_ALTERNATE_ERROR_INFO;
1326 else if (!strcmp(error_strategy, "ignore"))
1327 sas.error_mode = SUBMODULE_ALTERNATE_ERROR_IGNORE;
1328 else
1329 die(_("Value '%s' for submodule.alternateErrorStrategy is not recognized"), error_strategy);
1331 if (!strcmp(sm_alternate, "superproject"))
1332 foreach_alt_odb(add_possible_reference_from_superproject, &sas);
1333 else if (!strcmp(sm_alternate, "no"))
1334 ; /* do nothing */
1335 else
1336 die(_("Value '%s' for submodule.alternateLocation is not recognized"), sm_alternate);
1338 free(sm_alternate);
1339 free(error_strategy);
1342 static int module_clone(int argc, const char **argv, const char *prefix)
1344 const char *name = NULL, *url = NULL, *depth = NULL;
1345 int quiet = 0;
1346 int progress = 0;
1347 char *p, *path = NULL, *sm_gitdir;
1348 struct strbuf sb = STRBUF_INIT;
1349 struct string_list reference = STRING_LIST_INIT_NODUP;
1350 int dissociate = 0;
1351 char *sm_alternate = NULL, *error_strategy = NULL;
1353 struct option module_clone_options[] = {
1354 OPT_STRING(0, "prefix", &prefix,
1355 N_("path"),
1356 N_("alternative anchor for relative paths")),
1357 OPT_STRING(0, "path", &path,
1358 N_("path"),
1359 N_("where the new submodule will be cloned to")),
1360 OPT_STRING(0, "name", &name,
1361 N_("string"),
1362 N_("name of the new submodule")),
1363 OPT_STRING(0, "url", &url,
1364 N_("string"),
1365 N_("url where to clone the submodule from")),
1366 OPT_STRING_LIST(0, "reference", &reference,
1367 N_("repo"),
1368 N_("reference repository")),
1369 OPT_BOOL(0, "dissociate", &dissociate,
1370 N_("use --reference only while cloning")),
1371 OPT_STRING(0, "depth", &depth,
1372 N_("string"),
1373 N_("depth for shallow clones")),
1374 OPT__QUIET(&quiet, "Suppress output for cloning a submodule"),
1375 OPT_BOOL(0, "progress", &progress,
1376 N_("force cloning progress")),
1377 OPT_END()
1380 const char *const git_submodule_helper_usage[] = {
1381 N_("git submodule--helper clone [--prefix=<path>] [--quiet] "
1382 "[--reference <repository>] [--name <name>] [--depth <depth>] "
1383 "--url <url> --path <path>"),
1384 NULL
1387 argc = parse_options(argc, argv, prefix, module_clone_options,
1388 git_submodule_helper_usage, 0);
1390 if (argc || !url || !path || !*path)
1391 usage_with_options(git_submodule_helper_usage,
1392 module_clone_options);
1394 strbuf_addf(&sb, "%s/modules/%s", get_git_dir(), name);
1395 sm_gitdir = absolute_pathdup(sb.buf);
1396 strbuf_reset(&sb);
1398 if (!is_absolute_path(path)) {
1399 strbuf_addf(&sb, "%s/%s", get_git_work_tree(), path);
1400 path = strbuf_detach(&sb, NULL);
1401 } else
1402 path = xstrdup(path);
1404 if (!file_exists(sm_gitdir)) {
1405 if (safe_create_leading_directories_const(sm_gitdir) < 0)
1406 die(_("could not create directory '%s'"), sm_gitdir);
1408 prepare_possible_alternates(name, &reference);
1410 if (clone_submodule(path, sm_gitdir, url, depth, &reference, dissociate,
1411 quiet, progress))
1412 die(_("clone of '%s' into submodule path '%s' failed"),
1413 url, path);
1414 } else {
1415 if (safe_create_leading_directories_const(path) < 0)
1416 die(_("could not create directory '%s'"), path);
1417 strbuf_addf(&sb, "%s/index", sm_gitdir);
1418 unlink_or_warn(sb.buf);
1419 strbuf_reset(&sb);
1422 connect_work_tree_and_git_dir(path, sm_gitdir, 0);
1424 p = git_pathdup_submodule(path, "config");
1425 if (!p)
1426 die(_("could not get submodule directory for '%s'"), path);
1428 /* setup alternateLocation and alternateErrorStrategy in the cloned submodule if needed */
1429 git_config_get_string("submodule.alternateLocation", &sm_alternate);
1430 if (sm_alternate)
1431 git_config_set_in_file(p, "submodule.alternateLocation",
1432 sm_alternate);
1433 git_config_get_string("submodule.alternateErrorStrategy", &error_strategy);
1434 if (error_strategy)
1435 git_config_set_in_file(p, "submodule.alternateErrorStrategy",
1436 error_strategy);
1438 free(sm_alternate);
1439 free(error_strategy);
1441 strbuf_release(&sb);
1442 free(sm_gitdir);
1443 free(path);
1444 free(p);
1445 return 0;
1448 struct submodule_update_clone {
1449 /* index into 'list', the list of submodules to look into for cloning */
1450 int current;
1451 struct module_list list;
1452 unsigned warn_if_uninitialized : 1;
1454 /* update parameter passed via commandline */
1455 struct submodule_update_strategy update;
1457 /* configuration parameters which are passed on to the children */
1458 int progress;
1459 int quiet;
1460 int recommend_shallow;
1461 struct string_list references;
1462 int dissociate;
1463 const char *depth;
1464 const char *recursive_prefix;
1465 const char *prefix;
1467 /* Machine-readable status lines to be consumed by git-submodule.sh */
1468 struct string_list projectlines;
1470 /* If we want to stop as fast as possible and return an error */
1471 unsigned quickstop : 1;
1473 /* failed clones to be retried again */
1474 const struct cache_entry **failed_clones;
1475 int failed_clones_nr, failed_clones_alloc;
1477 #define SUBMODULE_UPDATE_CLONE_INIT {0, MODULE_LIST_INIT, 0, \
1478 SUBMODULE_UPDATE_STRATEGY_INIT, 0, 0, -1, STRING_LIST_INIT_DUP, 0, \
1479 NULL, NULL, NULL, \
1480 STRING_LIST_INIT_DUP, 0, NULL, 0, 0}
1483 static void next_submodule_warn_missing(struct submodule_update_clone *suc,
1484 struct strbuf *out, const char *displaypath)
1487 * Only mention uninitialized submodules when their
1488 * paths have been specified.
1490 if (suc->warn_if_uninitialized) {
1491 strbuf_addf(out,
1492 _("Submodule path '%s' not initialized"),
1493 displaypath);
1494 strbuf_addch(out, '\n');
1495 strbuf_addstr(out,
1496 _("Maybe you want to use 'update --init'?"));
1497 strbuf_addch(out, '\n');
1502 * Determine whether 'ce' needs to be cloned. If so, prepare the 'child' to
1503 * run the clone. Returns 1 if 'ce' needs to be cloned, 0 otherwise.
1505 static int prepare_to_clone_next_submodule(const struct cache_entry *ce,
1506 struct child_process *child,
1507 struct submodule_update_clone *suc,
1508 struct strbuf *out)
1510 const struct submodule *sub = NULL;
1511 const char *url = NULL;
1512 const char *update_string;
1513 enum submodule_update_type update_type;
1514 char *key;
1515 struct strbuf displaypath_sb = STRBUF_INIT;
1516 struct strbuf sb = STRBUF_INIT;
1517 const char *displaypath = NULL;
1518 int needs_cloning = 0;
1520 if (ce_stage(ce)) {
1521 if (suc->recursive_prefix)
1522 strbuf_addf(&sb, "%s/%s", suc->recursive_prefix, ce->name);
1523 else
1524 strbuf_addstr(&sb, ce->name);
1525 strbuf_addf(out, _("Skipping unmerged submodule %s"), sb.buf);
1526 strbuf_addch(out, '\n');
1527 goto cleanup;
1530 sub = submodule_from_path(the_repository, &null_oid, ce->name);
1532 if (suc->recursive_prefix)
1533 displaypath = relative_path(suc->recursive_prefix,
1534 ce->name, &displaypath_sb);
1535 else
1536 displaypath = ce->name;
1538 if (!sub) {
1539 next_submodule_warn_missing(suc, out, displaypath);
1540 goto cleanup;
1543 key = xstrfmt("submodule.%s.update", sub->name);
1544 if (!repo_config_get_string_const(the_repository, key, &update_string)) {
1545 update_type = parse_submodule_update_type(update_string);
1546 } else {
1547 update_type = sub->update_strategy.type;
1549 free(key);
1551 if (suc->update.type == SM_UPDATE_NONE
1552 || (suc->update.type == SM_UPDATE_UNSPECIFIED
1553 && update_type == SM_UPDATE_NONE)) {
1554 strbuf_addf(out, _("Skipping submodule '%s'"), displaypath);
1555 strbuf_addch(out, '\n');
1556 goto cleanup;
1559 /* Check if the submodule has been initialized. */
1560 if (!is_submodule_active(the_repository, ce->name)) {
1561 next_submodule_warn_missing(suc, out, displaypath);
1562 goto cleanup;
1565 strbuf_reset(&sb);
1566 strbuf_addf(&sb, "submodule.%s.url", sub->name);
1567 if (repo_config_get_string_const(the_repository, sb.buf, &url))
1568 url = sub->url;
1570 strbuf_reset(&sb);
1571 strbuf_addf(&sb, "%s/.git", ce->name);
1572 needs_cloning = !file_exists(sb.buf);
1574 strbuf_reset(&sb);
1575 strbuf_addf(&sb, "%06o %s %d %d\t%s\n", ce->ce_mode,
1576 oid_to_hex(&ce->oid), ce_stage(ce),
1577 needs_cloning, ce->name);
1578 string_list_append(&suc->projectlines, sb.buf);
1580 if (!needs_cloning)
1581 goto cleanup;
1583 child->git_cmd = 1;
1584 child->no_stdin = 1;
1585 child->stdout_to_stderr = 1;
1586 child->err = -1;
1587 argv_array_push(&child->args, "submodule--helper");
1588 argv_array_push(&child->args, "clone");
1589 if (suc->progress)
1590 argv_array_push(&child->args, "--progress");
1591 if (suc->quiet)
1592 argv_array_push(&child->args, "--quiet");
1593 if (suc->prefix)
1594 argv_array_pushl(&child->args, "--prefix", suc->prefix, NULL);
1595 if (suc->recommend_shallow && sub->recommend_shallow == 1)
1596 argv_array_push(&child->args, "--depth=1");
1597 argv_array_pushl(&child->args, "--path", sub->path, NULL);
1598 argv_array_pushl(&child->args, "--name", sub->name, NULL);
1599 argv_array_pushl(&child->args, "--url", url, NULL);
1600 if (suc->references.nr) {
1601 struct string_list_item *item;
1602 for_each_string_list_item(item, &suc->references)
1603 argv_array_pushl(&child->args, "--reference", item->string, NULL);
1605 if (suc->dissociate)
1606 argv_array_push(&child->args, "--dissociate");
1607 if (suc->depth)
1608 argv_array_push(&child->args, suc->depth);
1610 cleanup:
1611 strbuf_reset(&displaypath_sb);
1612 strbuf_reset(&sb);
1614 return needs_cloning;
1617 static int update_clone_get_next_task(struct child_process *child,
1618 struct strbuf *err,
1619 void *suc_cb,
1620 void **idx_task_cb)
1622 struct submodule_update_clone *suc = suc_cb;
1623 const struct cache_entry *ce;
1624 int index;
1626 for (; suc->current < suc->list.nr; suc->current++) {
1627 ce = suc->list.entries[suc->current];
1628 if (prepare_to_clone_next_submodule(ce, child, suc, err)) {
1629 int *p = xmalloc(sizeof(*p));
1630 *p = suc->current;
1631 *idx_task_cb = p;
1632 suc->current++;
1633 return 1;
1638 * The loop above tried cloning each submodule once, now try the
1639 * stragglers again, which we can imagine as an extension of the
1640 * entry list.
1642 index = suc->current - suc->list.nr;
1643 if (index < suc->failed_clones_nr) {
1644 int *p;
1645 ce = suc->failed_clones[index];
1646 if (!prepare_to_clone_next_submodule(ce, child, suc, err)) {
1647 suc->current ++;
1648 strbuf_addstr(err, "BUG: submodule considered for "
1649 "cloning, doesn't need cloning "
1650 "any more?\n");
1651 return 0;
1653 p = xmalloc(sizeof(*p));
1654 *p = suc->current;
1655 *idx_task_cb = p;
1656 suc->current ++;
1657 return 1;
1660 return 0;
1663 static int update_clone_start_failure(struct strbuf *err,
1664 void *suc_cb,
1665 void *idx_task_cb)
1667 struct submodule_update_clone *suc = suc_cb;
1668 suc->quickstop = 1;
1669 return 1;
1672 static int update_clone_task_finished(int result,
1673 struct strbuf *err,
1674 void *suc_cb,
1675 void *idx_task_cb)
1677 const struct cache_entry *ce;
1678 struct submodule_update_clone *suc = suc_cb;
1680 int *idxP = idx_task_cb;
1681 int idx = *idxP;
1682 free(idxP);
1684 if (!result)
1685 return 0;
1687 if (idx < suc->list.nr) {
1688 ce = suc->list.entries[idx];
1689 strbuf_addf(err, _("Failed to clone '%s'. Retry scheduled"),
1690 ce->name);
1691 strbuf_addch(err, '\n');
1692 ALLOC_GROW(suc->failed_clones,
1693 suc->failed_clones_nr + 1,
1694 suc->failed_clones_alloc);
1695 suc->failed_clones[suc->failed_clones_nr++] = ce;
1696 return 0;
1697 } else {
1698 idx -= suc->list.nr;
1699 ce = suc->failed_clones[idx];
1700 strbuf_addf(err, _("Failed to clone '%s' a second time, aborting"),
1701 ce->name);
1702 strbuf_addch(err, '\n');
1703 suc->quickstop = 1;
1704 return 1;
1707 return 0;
1710 static int git_update_clone_config(const char *var, const char *value,
1711 void *cb)
1713 int *max_jobs = cb;
1714 if (!strcmp(var, "submodule.fetchjobs"))
1715 *max_jobs = parse_submodule_fetchjobs(var, value);
1716 return 0;
1719 static int update_clone(int argc, const char **argv, const char *prefix)
1721 const char *update = NULL;
1722 int max_jobs = 1;
1723 struct string_list_item *item;
1724 struct pathspec pathspec;
1725 struct submodule_update_clone suc = SUBMODULE_UPDATE_CLONE_INIT;
1727 struct option module_update_clone_options[] = {
1728 OPT_STRING(0, "prefix", &prefix,
1729 N_("path"),
1730 N_("path into the working tree")),
1731 OPT_STRING(0, "recursive-prefix", &suc.recursive_prefix,
1732 N_("path"),
1733 N_("path into the working tree, across nested "
1734 "submodule boundaries")),
1735 OPT_STRING(0, "update", &update,
1736 N_("string"),
1737 N_("rebase, merge, checkout or none")),
1738 OPT_STRING_LIST(0, "reference", &suc.references, N_("repo"),
1739 N_("reference repository")),
1740 OPT_BOOL(0, "dissociate", &suc.dissociate,
1741 N_("use --reference only while cloning")),
1742 OPT_STRING(0, "depth", &suc.depth, "<depth>",
1743 N_("Create a shallow clone truncated to the "
1744 "specified number of revisions")),
1745 OPT_INTEGER('j', "jobs", &max_jobs,
1746 N_("parallel jobs")),
1747 OPT_BOOL(0, "recommend-shallow", &suc.recommend_shallow,
1748 N_("whether the initial clone should follow the shallow recommendation")),
1749 OPT__QUIET(&suc.quiet, N_("don't print cloning progress")),
1750 OPT_BOOL(0, "progress", &suc.progress,
1751 N_("force cloning progress")),
1752 OPT_END()
1755 const char *const git_submodule_helper_usage[] = {
1756 N_("git submodule--helper update_clone [--prefix=<path>] [<path>...]"),
1757 NULL
1759 suc.prefix = prefix;
1761 update_clone_config_from_gitmodules(&max_jobs);
1762 git_config(git_update_clone_config, &max_jobs);
1764 argc = parse_options(argc, argv, prefix, module_update_clone_options,
1765 git_submodule_helper_usage, 0);
1767 if (update)
1768 if (parse_submodule_update_strategy(update, &suc.update) < 0)
1769 die(_("bad value for update parameter"));
1771 if (module_list_compute(argc, argv, prefix, &pathspec, &suc.list) < 0)
1772 return 1;
1774 if (pathspec.nr)
1775 suc.warn_if_uninitialized = 1;
1777 run_processes_parallel(max_jobs,
1778 update_clone_get_next_task,
1779 update_clone_start_failure,
1780 update_clone_task_finished,
1781 &suc);
1784 * We saved the output and put it out all at once now.
1785 * That means:
1786 * - the listener does not have to interleave their (checkout)
1787 * work with our fetching. The writes involved in a
1788 * checkout involve more straightforward sequential I/O.
1789 * - the listener can avoid doing any work if fetching failed.
1791 if (suc.quickstop)
1792 return 1;
1794 for_each_string_list_item(item, &suc.projectlines)
1795 fprintf(stdout, "%s", item->string);
1797 return 0;
1800 static int resolve_relative_path(int argc, const char **argv, const char *prefix)
1802 struct strbuf sb = STRBUF_INIT;
1803 if (argc != 3)
1804 die("submodule--helper relative-path takes exactly 2 arguments, got %d", argc);
1806 printf("%s", relative_path(argv[1], argv[2], &sb));
1807 strbuf_release(&sb);
1808 return 0;
1811 static const char *remote_submodule_branch(const char *path)
1813 const struct submodule *sub;
1814 const char *branch = NULL;
1815 char *key;
1817 sub = submodule_from_path(the_repository, &null_oid, path);
1818 if (!sub)
1819 return NULL;
1821 key = xstrfmt("submodule.%s.branch", sub->name);
1822 if (repo_config_get_string_const(the_repository, key, &branch))
1823 branch = sub->branch;
1824 free(key);
1826 if (!branch)
1827 return "master";
1829 if (!strcmp(branch, ".")) {
1830 const char *refname = resolve_ref_unsafe("HEAD", 0, NULL, NULL);
1832 if (!refname)
1833 die(_("No such ref: %s"), "HEAD");
1835 /* detached HEAD */
1836 if (!strcmp(refname, "HEAD"))
1837 die(_("Submodule (%s) branch configured to inherit "
1838 "branch from superproject, but the superproject "
1839 "is not on any branch"), sub->name);
1841 if (!skip_prefix(refname, "refs/heads/", &refname))
1842 die(_("Expecting a full ref name, got %s"), refname);
1843 return refname;
1846 return branch;
1849 static int resolve_remote_submodule_branch(int argc, const char **argv,
1850 const char *prefix)
1852 const char *ret;
1853 struct strbuf sb = STRBUF_INIT;
1854 if (argc != 2)
1855 die("submodule--helper remote-branch takes exactly one arguments, got %d", argc);
1857 ret = remote_submodule_branch(argv[1]);
1858 if (!ret)
1859 die("submodule %s doesn't exist", argv[1]);
1861 printf("%s", ret);
1862 strbuf_release(&sb);
1863 return 0;
1866 static int push_check(int argc, const char **argv, const char *prefix)
1868 struct remote *remote;
1869 const char *superproject_head;
1870 char *head;
1871 int detached_head = 0;
1872 struct object_id head_oid;
1874 if (argc < 3)
1875 die("submodule--helper push-check requires at least 2 arguments");
1878 * superproject's resolved head ref.
1879 * if HEAD then the superproject is in a detached head state, otherwise
1880 * it will be the resolved head ref.
1882 superproject_head = argv[1];
1883 argv++;
1884 argc--;
1885 /* Get the submodule's head ref and determine if it is detached */
1886 head = resolve_refdup("HEAD", 0, &head_oid, NULL);
1887 if (!head)
1888 die(_("Failed to resolve HEAD as a valid ref."));
1889 if (!strcmp(head, "HEAD"))
1890 detached_head = 1;
1893 * The remote must be configured.
1894 * This is to avoid pushing to the exact same URL as the parent.
1896 remote = pushremote_get(argv[1]);
1897 if (!remote || remote->origin == REMOTE_UNCONFIGURED)
1898 die("remote '%s' not configured", argv[1]);
1900 /* Check the refspec */
1901 if (argc > 2) {
1902 int i;
1903 struct ref *local_refs = get_local_heads();
1904 struct refspec refspec = REFSPEC_INIT_PUSH;
1906 refspec_appendn(&refspec, argv + 2, argc - 2);
1908 for (i = 0; i < refspec.nr; i++) {
1909 const struct refspec_item *rs = &refspec.items[i];
1911 if (rs->pattern || rs->matching)
1912 continue;
1914 /* LHS must match a single ref */
1915 switch (count_refspec_match(rs->src, local_refs, NULL)) {
1916 case 1:
1917 break;
1918 case 0:
1920 * If LHS matches 'HEAD' then we need to ensure
1921 * that it matches the same named branch
1922 * checked out in the superproject.
1924 if (!strcmp(rs->src, "HEAD")) {
1925 if (!detached_head &&
1926 !strcmp(head, superproject_head))
1927 break;
1928 die("HEAD does not match the named branch in the superproject");
1930 /* fallthrough */
1931 default:
1932 die("src refspec '%s' must name a ref",
1933 rs->src);
1936 refspec_clear(&refspec);
1938 free(head);
1940 return 0;
1943 static int absorb_git_dirs(int argc, const char **argv, const char *prefix)
1945 int i;
1946 struct pathspec pathspec;
1947 struct module_list list = MODULE_LIST_INIT;
1948 unsigned flags = ABSORB_GITDIR_RECURSE_SUBMODULES;
1950 struct option embed_gitdir_options[] = {
1951 OPT_STRING(0, "prefix", &prefix,
1952 N_("path"),
1953 N_("path into the working tree")),
1954 OPT_BIT(0, "--recursive", &flags, N_("recurse into submodules"),
1955 ABSORB_GITDIR_RECURSE_SUBMODULES),
1956 OPT_END()
1959 const char *const git_submodule_helper_usage[] = {
1960 N_("git submodule--helper embed-git-dir [<path>...]"),
1961 NULL
1964 argc = parse_options(argc, argv, prefix, embed_gitdir_options,
1965 git_submodule_helper_usage, 0);
1967 if (module_list_compute(argc, argv, prefix, &pathspec, &list) < 0)
1968 return 1;
1970 for (i = 0; i < list.nr; i++)
1971 absorb_git_dir_into_superproject(prefix,
1972 list.entries[i]->name, flags);
1974 return 0;
1977 static int is_active(int argc, const char **argv, const char *prefix)
1979 if (argc != 2)
1980 die("submodule--helper is-active takes exactly 1 argument");
1982 return !is_submodule_active(the_repository, argv[1]);
1986 * Exit non-zero if any of the submodule names given on the command line is
1987 * invalid. If no names are given, filter stdin to print only valid names
1988 * (which is primarily intended for testing).
1990 static int check_name(int argc, const char **argv, const char *prefix)
1992 if (argc > 1) {
1993 while (*++argv) {
1994 if (check_submodule_name(*argv) < 0)
1995 return 1;
1997 } else {
1998 struct strbuf buf = STRBUF_INIT;
1999 while (strbuf_getline(&buf, stdin) != EOF) {
2000 if (!check_submodule_name(buf.buf))
2001 printf("%s\n", buf.buf);
2003 strbuf_release(&buf);
2005 return 0;
2008 static int connect_gitdir_workingtree(int argc, const char **argv, const char *prefix)
2010 struct strbuf sb = STRBUF_INIT;
2011 const char *name, *path;
2012 char *sm_gitdir;
2014 if (argc != 3)
2015 BUG("submodule--helper connect-gitdir-workingtree <name> <path>");
2017 name = argv[1];
2018 path = argv[2];
2020 strbuf_addf(&sb, "%s/modules/%s", get_git_dir(), name);
2021 sm_gitdir = absolute_pathdup(sb.buf);
2023 connect_work_tree_and_git_dir(path, sm_gitdir, 0);
2025 strbuf_release(&sb);
2026 free(sm_gitdir);
2028 return 0;
2031 #define SUPPORT_SUPER_PREFIX (1<<0)
2033 struct cmd_struct {
2034 const char *cmd;
2035 int (*fn)(int, const char **, const char *);
2036 unsigned option;
2039 static struct cmd_struct commands[] = {
2040 {"list", module_list, 0},
2041 {"name", module_name, 0},
2042 {"clone", module_clone, 0},
2043 {"update-clone", update_clone, 0},
2044 {"connect-gitdir-workingtree", connect_gitdir_workingtree, 0},
2045 {"relative-path", resolve_relative_path, 0},
2046 {"resolve-relative-url", resolve_relative_url, 0},
2047 {"resolve-relative-url-test", resolve_relative_url_test, 0},
2048 {"foreach", module_foreach, SUPPORT_SUPER_PREFIX},
2049 {"init", module_init, SUPPORT_SUPER_PREFIX},
2050 {"status", module_status, SUPPORT_SUPER_PREFIX},
2051 {"print-default-remote", print_default_remote, 0},
2052 {"sync", module_sync, SUPPORT_SUPER_PREFIX},
2053 {"deinit", module_deinit, 0},
2054 {"remote-branch", resolve_remote_submodule_branch, 0},
2055 {"push-check", push_check, 0},
2056 {"absorb-git-dirs", absorb_git_dirs, SUPPORT_SUPER_PREFIX},
2057 {"is-active", is_active, 0},
2058 {"check-name", check_name, 0},
2061 int cmd_submodule__helper(int argc, const char **argv, const char *prefix)
2063 int i;
2064 if (argc < 2 || !strcmp(argv[1], "-h"))
2065 usage("git submodule--helper <command>");
2067 for (i = 0; i < ARRAY_SIZE(commands); i++) {
2068 if (!strcmp(argv[1], commands[i].cmd)) {
2069 if (get_super_prefix() &&
2070 !(commands[i].option & SUPPORT_SUPER_PREFIX))
2071 die(_("%s doesn't support --super-prefix"),
2072 commands[i].cmd);
2073 return commands[i].fn(argc - 1, argv + 1, prefix);
2077 die(_("'%s' is not a valid submodule--helper "
2078 "subcommand"), argv[1]);