sha1-name.c: remove the_repo from get_oid_1()
[git/raj.git] / builtin / submodule--helper.c
blob6bcc4f1bd773b38f5895d3404419e362ded63d2a
1 #define USE_THE_INDEX_COMPATIBILITY_MACROS
2 #include "builtin.h"
3 #include "repository.h"
4 #include "cache.h"
5 #include "config.h"
6 #include "parse-options.h"
7 #include "quote.h"
8 #include "pathspec.h"
9 #include "dir.h"
10 #include "submodule.h"
11 #include "submodule-config.h"
12 #include "string-list.h"
13 #include "run-command.h"
14 #include "remote.h"
15 #include "refs.h"
16 #include "refspec.h"
17 #include "connect.h"
18 #include "revision.h"
19 #include "diffcore.h"
20 #include "diff.h"
21 #include "object-store.h"
23 #define OPT_QUIET (1 << 0)
24 #define OPT_CACHED (1 << 1)
25 #define OPT_RECURSIVE (1 << 2)
26 #define OPT_FORCE (1 << 3)
28 typedef void (*each_submodule_fn)(const struct cache_entry *list_item,
29 void *cb_data);
31 static char *get_default_remote(void)
33 char *dest = NULL, *ret;
34 struct strbuf sb = STRBUF_INIT;
35 const char *refname = resolve_ref_unsafe("HEAD", 0, NULL, NULL);
37 if (!refname)
38 die(_("No such ref: %s"), "HEAD");
40 /* detached HEAD */
41 if (!strcmp(refname, "HEAD"))
42 return xstrdup("origin");
44 if (!skip_prefix(refname, "refs/heads/", &refname))
45 die(_("Expecting a full ref name, got %s"), refname);
47 strbuf_addf(&sb, "branch.%s.remote", refname);
48 if (git_config_get_string(sb.buf, &dest))
49 ret = xstrdup("origin");
50 else
51 ret = dest;
53 strbuf_release(&sb);
54 return ret;
57 static int print_default_remote(int argc, const char **argv, const char *prefix)
59 char *remote;
61 if (argc != 1)
62 die(_("submodule--helper print-default-remote takes no arguments"));
64 remote = get_default_remote();
65 if (remote)
66 printf("%s\n", remote);
68 free(remote);
69 return 0;
72 static int starts_with_dot_slash(const char *str)
74 return str[0] == '.' && is_dir_sep(str[1]);
77 static int starts_with_dot_dot_slash(const char *str)
79 return str[0] == '.' && str[1] == '.' && is_dir_sep(str[2]);
83 * Returns 1 if it was the last chop before ':'.
85 static int chop_last_dir(char **remoteurl, int is_relative)
87 char *rfind = find_last_dir_sep(*remoteurl);
88 if (rfind) {
89 *rfind = '\0';
90 return 0;
93 rfind = strrchr(*remoteurl, ':');
94 if (rfind) {
95 *rfind = '\0';
96 return 1;
99 if (is_relative || !strcmp(".", *remoteurl))
100 die(_("cannot strip one component off url '%s'"),
101 *remoteurl);
103 free(*remoteurl);
104 *remoteurl = xstrdup(".");
105 return 0;
109 * The `url` argument is the URL that navigates to the submodule origin
110 * repo. When relative, this URL is relative to the superproject origin
111 * URL repo. The `up_path` argument, if specified, is the relative
112 * path that navigates from the submodule working tree to the superproject
113 * working tree. Returns the origin URL of the submodule.
115 * Return either an absolute URL or filesystem path (if the superproject
116 * origin URL is an absolute URL or filesystem path, respectively) or a
117 * relative file system path (if the superproject origin URL is a relative
118 * file system path).
120 * When the output is a relative file system path, the path is either
121 * relative to the submodule working tree, if up_path is specified, or to
122 * the superproject working tree otherwise.
124 * NEEDSWORK: This works incorrectly on the domain and protocol part.
125 * remote_url url outcome expectation
126 * http://a.com/b ../c http://a.com/c as is
127 * http://a.com/b/ ../c http://a.com/c same as previous line, but
128 * ignore trailing slash in url
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 http:c error out
132 * http://a.com/b ../../../../../c .:c error out
133 * NEEDSWORK: Given how chop_last_dir() works, this function is broken
134 * when a local part has a colon in its path component, too.
136 static char *relative_url(const char *remote_url,
137 const char *url,
138 const char *up_path)
140 int is_relative = 0;
141 int colonsep = 0;
142 char *out;
143 char *remoteurl = xstrdup(remote_url);
144 struct strbuf sb = STRBUF_INIT;
145 size_t len = strlen(remoteurl);
147 if (is_dir_sep(remoteurl[len-1]))
148 remoteurl[len-1] = '\0';
150 if (!url_is_local_not_ssh(remoteurl) || is_absolute_path(remoteurl))
151 is_relative = 0;
152 else {
153 is_relative = 1;
155 * Prepend a './' to ensure all relative
156 * remoteurls start with './' or '../'
158 if (!starts_with_dot_slash(remoteurl) &&
159 !starts_with_dot_dot_slash(remoteurl)) {
160 strbuf_reset(&sb);
161 strbuf_addf(&sb, "./%s", remoteurl);
162 free(remoteurl);
163 remoteurl = strbuf_detach(&sb, NULL);
167 * When the url starts with '../', remove that and the
168 * last directory in remoteurl.
170 while (url) {
171 if (starts_with_dot_dot_slash(url)) {
172 url += 3;
173 colonsep |= chop_last_dir(&remoteurl, is_relative);
174 } else if (starts_with_dot_slash(url))
175 url += 2;
176 else
177 break;
179 strbuf_reset(&sb);
180 strbuf_addf(&sb, "%s%s%s", remoteurl, colonsep ? ":" : "/", url);
181 if (ends_with(url, "/"))
182 strbuf_setlen(&sb, sb.len - 1);
183 free(remoteurl);
185 if (starts_with_dot_slash(sb.buf))
186 out = xstrdup(sb.buf + 2);
187 else
188 out = xstrdup(sb.buf);
189 strbuf_reset(&sb);
191 if (!up_path || !is_relative)
192 return out;
194 strbuf_addf(&sb, "%s%s", up_path, out);
195 free(out);
196 return strbuf_detach(&sb, NULL);
199 static int resolve_relative_url(int argc, const char **argv, const char *prefix)
201 char *remoteurl = NULL;
202 char *remote = get_default_remote();
203 const char *up_path = NULL;
204 char *res;
205 const char *url;
206 struct strbuf sb = STRBUF_INIT;
208 if (argc != 2 && argc != 3)
209 die("resolve-relative-url only accepts one or two arguments");
211 url = argv[1];
212 strbuf_addf(&sb, "remote.%s.url", remote);
213 free(remote);
215 if (git_config_get_string(sb.buf, &remoteurl))
216 /* the repository is its own authoritative upstream */
217 remoteurl = xgetcwd();
219 if (argc == 3)
220 up_path = argv[2];
222 res = relative_url(remoteurl, url, up_path);
223 puts(res);
224 free(res);
225 free(remoteurl);
226 return 0;
229 static int resolve_relative_url_test(int argc, const char **argv, const char *prefix)
231 char *remoteurl, *res;
232 const char *up_path, *url;
234 if (argc != 4)
235 die("resolve-relative-url-test only accepts three arguments: <up_path> <remoteurl> <url>");
237 up_path = argv[1];
238 remoteurl = xstrdup(argv[2]);
239 url = argv[3];
241 if (!strcmp(up_path, "(null)"))
242 up_path = NULL;
244 res = relative_url(remoteurl, url, up_path);
245 puts(res);
246 free(res);
247 free(remoteurl);
248 return 0;
251 /* the result should be freed by the caller. */
252 static char *get_submodule_displaypath(const char *path, const char *prefix)
254 const char *super_prefix = get_super_prefix();
256 if (prefix && super_prefix) {
257 BUG("cannot have prefix '%s' and superprefix '%s'",
258 prefix, super_prefix);
259 } else if (prefix) {
260 struct strbuf sb = STRBUF_INIT;
261 char *displaypath = xstrdup(relative_path(path, prefix, &sb));
262 strbuf_release(&sb);
263 return displaypath;
264 } else if (super_prefix) {
265 return xstrfmt("%s%s", super_prefix, path);
266 } else {
267 return xstrdup(path);
271 static char *compute_rev_name(const char *sub_path, const char* object_id)
273 struct strbuf sb = STRBUF_INIT;
274 const char ***d;
276 static const char *describe_bare[] = { NULL };
278 static const char *describe_tags[] = { "--tags", NULL };
280 static const char *describe_contains[] = { "--contains", NULL };
282 static const char *describe_all_always[] = { "--all", "--always", NULL };
284 static const char **describe_argv[] = { describe_bare, describe_tags,
285 describe_contains,
286 describe_all_always, NULL };
288 for (d = describe_argv; *d; d++) {
289 struct child_process cp = CHILD_PROCESS_INIT;
290 prepare_submodule_repo_env(&cp.env_array);
291 cp.dir = sub_path;
292 cp.git_cmd = 1;
293 cp.no_stderr = 1;
295 argv_array_push(&cp.args, "describe");
296 argv_array_pushv(&cp.args, *d);
297 argv_array_push(&cp.args, object_id);
299 if (!capture_command(&cp, &sb, 0)) {
300 strbuf_strip_suffix(&sb, "\n");
301 return strbuf_detach(&sb, NULL);
305 strbuf_release(&sb);
306 return NULL;
309 struct module_list {
310 const struct cache_entry **entries;
311 int alloc, nr;
313 #define MODULE_LIST_INIT { NULL, 0, 0 }
315 static int module_list_compute(int argc, const char **argv,
316 const char *prefix,
317 struct pathspec *pathspec,
318 struct module_list *list)
320 int i, result = 0;
321 char *ps_matched = NULL;
322 parse_pathspec(pathspec, 0,
323 PATHSPEC_PREFER_FULL,
324 prefix, argv);
326 if (pathspec->nr)
327 ps_matched = xcalloc(pathspec->nr, 1);
329 if (read_cache() < 0)
330 die(_("index file corrupt"));
332 for (i = 0; i < active_nr; i++) {
333 const struct cache_entry *ce = active_cache[i];
335 if (!match_pathspec(&the_index, pathspec, ce->name, ce_namelen(ce),
336 0, ps_matched, 1) ||
337 !S_ISGITLINK(ce->ce_mode))
338 continue;
340 ALLOC_GROW(list->entries, list->nr + 1, list->alloc);
341 list->entries[list->nr++] = ce;
342 while (i + 1 < active_nr &&
343 !strcmp(ce->name, active_cache[i + 1]->name))
345 * Skip entries with the same name in different stages
346 * to make sure an entry is returned only once.
348 i++;
351 if (ps_matched && report_path_error(ps_matched, pathspec, prefix))
352 result = -1;
354 free(ps_matched);
356 return result;
359 static void module_list_active(struct module_list *list)
361 int i;
362 struct module_list active_modules = MODULE_LIST_INIT;
364 for (i = 0; i < list->nr; i++) {
365 const struct cache_entry *ce = list->entries[i];
367 if (!is_submodule_active(the_repository, ce->name))
368 continue;
370 ALLOC_GROW(active_modules.entries,
371 active_modules.nr + 1,
372 active_modules.alloc);
373 active_modules.entries[active_modules.nr++] = ce;
376 free(list->entries);
377 *list = active_modules;
380 static char *get_up_path(const char *path)
382 int i;
383 struct strbuf sb = STRBUF_INIT;
385 for (i = count_slashes(path); i; i--)
386 strbuf_addstr(&sb, "../");
389 * Check if 'path' ends with slash or not
390 * for having the same output for dir/sub_dir
391 * and dir/sub_dir/
393 if (!is_dir_sep(path[strlen(path) - 1]))
394 strbuf_addstr(&sb, "../");
396 return strbuf_detach(&sb, NULL);
399 static int module_list(int argc, const char **argv, const char *prefix)
401 int i;
402 struct pathspec pathspec;
403 struct module_list list = MODULE_LIST_INIT;
405 struct option module_list_options[] = {
406 OPT_STRING(0, "prefix", &prefix,
407 N_("path"),
408 N_("alternative anchor for relative paths")),
409 OPT_END()
412 const char *const git_submodule_helper_usage[] = {
413 N_("git submodule--helper list [--prefix=<path>] [<path>...]"),
414 NULL
417 argc = parse_options(argc, argv, prefix, module_list_options,
418 git_submodule_helper_usage, 0);
420 if (module_list_compute(argc, argv, prefix, &pathspec, &list) < 0)
421 return 1;
423 for (i = 0; i < list.nr; i++) {
424 const struct cache_entry *ce = list.entries[i];
426 if (ce_stage(ce))
427 printf("%06o %s U\t", ce->ce_mode, sha1_to_hex(null_sha1));
428 else
429 printf("%06o %s %d\t", ce->ce_mode,
430 oid_to_hex(&ce->oid), ce_stage(ce));
432 fprintf(stdout, "%s\n", ce->name);
434 return 0;
437 static void for_each_listed_submodule(const struct module_list *list,
438 each_submodule_fn fn, void *cb_data)
440 int i;
441 for (i = 0; i < list->nr; i++)
442 fn(list->entries[i], cb_data);
445 struct cb_foreach {
446 int argc;
447 const char **argv;
448 const char *prefix;
449 int quiet;
450 int recursive;
452 #define CB_FOREACH_INIT { 0 }
454 static void runcommand_in_submodule_cb(const struct cache_entry *list_item,
455 void *cb_data)
457 struct cb_foreach *info = cb_data;
458 const char *path = list_item->name;
459 const struct object_id *ce_oid = &list_item->oid;
461 const struct submodule *sub;
462 struct child_process cp = CHILD_PROCESS_INIT;
463 char *displaypath;
465 displaypath = get_submodule_displaypath(path, info->prefix);
467 sub = submodule_from_path(the_repository, &null_oid, path);
469 if (!sub)
470 die(_("No url found for submodule path '%s' in .gitmodules"),
471 displaypath);
473 if (!is_submodule_populated_gently(path, NULL))
474 goto cleanup;
476 prepare_submodule_repo_env(&cp.env_array);
479 * For the purpose of executing <command> in the submodule,
480 * separate shell is used for the purpose of running the
481 * child process.
483 cp.use_shell = 1;
484 cp.dir = path;
487 * NEEDSWORK: the command currently has access to the variables $name,
488 * $sm_path, $displaypath, $sha1 and $toplevel only when the command
489 * contains a single argument. This is done for maintaining a faithful
490 * translation from shell script.
492 if (info->argc == 1) {
493 char *toplevel = xgetcwd();
494 struct strbuf sb = STRBUF_INIT;
496 argv_array_pushf(&cp.env_array, "name=%s", sub->name);
497 argv_array_pushf(&cp.env_array, "sm_path=%s", path);
498 argv_array_pushf(&cp.env_array, "displaypath=%s", displaypath);
499 argv_array_pushf(&cp.env_array, "sha1=%s",
500 oid_to_hex(ce_oid));
501 argv_array_pushf(&cp.env_array, "toplevel=%s", toplevel);
504 * Since the path variable was accessible from the script
505 * before porting, it is also made available after porting.
506 * The environment variable "PATH" has a very special purpose
507 * on windows. And since environment variables are
508 * case-insensitive in windows, it interferes with the
509 * existing PATH variable. Hence, to avoid that, we expose
510 * path via the args argv_array and not via env_array.
512 sq_quote_buf(&sb, path);
513 argv_array_pushf(&cp.args, "path=%s; %s",
514 sb.buf, info->argv[0]);
515 strbuf_release(&sb);
516 free(toplevel);
517 } else {
518 argv_array_pushv(&cp.args, info->argv);
521 if (!info->quiet)
522 printf(_("Entering '%s'\n"), displaypath);
524 if (info->argv[0] && run_command(&cp))
525 die(_("run_command returned non-zero status for %s\n."),
526 displaypath);
528 if (info->recursive) {
529 struct child_process cpr = CHILD_PROCESS_INIT;
531 cpr.git_cmd = 1;
532 cpr.dir = path;
533 prepare_submodule_repo_env(&cpr.env_array);
535 argv_array_pushl(&cpr.args, "--super-prefix", NULL);
536 argv_array_pushf(&cpr.args, "%s/", displaypath);
537 argv_array_pushl(&cpr.args, "submodule--helper", "foreach", "--recursive",
538 NULL);
540 if (info->quiet)
541 argv_array_push(&cpr.args, "--quiet");
543 argv_array_pushv(&cpr.args, info->argv);
545 if (run_command(&cpr))
546 die(_("run_command returned non-zero status while "
547 "recursing in the nested submodules of %s\n."),
548 displaypath);
551 cleanup:
552 free(displaypath);
555 static int module_foreach(int argc, const char **argv, const char *prefix)
557 struct cb_foreach info = CB_FOREACH_INIT;
558 struct pathspec pathspec;
559 struct module_list list = MODULE_LIST_INIT;
561 struct option module_foreach_options[] = {
562 OPT__QUIET(&info.quiet, N_("Suppress output of entering each submodule command")),
563 OPT_BOOL(0, "recursive", &info.recursive,
564 N_("Recurse into nested submodules")),
565 OPT_END()
568 const char *const git_submodule_helper_usage[] = {
569 N_("git submodule--helper foreach [--quiet] [--recursive] <command>"),
570 NULL
573 argc = parse_options(argc, argv, prefix, module_foreach_options,
574 git_submodule_helper_usage, PARSE_OPT_KEEP_UNKNOWN);
576 if (module_list_compute(0, NULL, prefix, &pathspec, &list) < 0)
577 return 1;
579 info.argc = argc;
580 info.argv = argv;
581 info.prefix = prefix;
583 for_each_listed_submodule(&list, runcommand_in_submodule_cb, &info);
585 return 0;
588 static char *compute_submodule_clone_url(const char *rel_url)
590 char *remoteurl, *relurl;
591 char *remote = get_default_remote();
592 struct strbuf remotesb = STRBUF_INIT;
594 strbuf_addf(&remotesb, "remote.%s.url", remote);
595 if (git_config_get_string(remotesb.buf, &remoteurl)) {
596 warning(_("could not look up configuration '%s'. Assuming this repository is its own authoritative upstream."), remotesb.buf);
597 remoteurl = xgetcwd();
599 relurl = relative_url(remoteurl, rel_url, NULL);
601 free(remote);
602 free(remoteurl);
603 strbuf_release(&remotesb);
605 return relurl;
608 struct init_cb {
609 const char *prefix;
610 unsigned int flags;
613 #define INIT_CB_INIT { NULL, 0 }
615 static void init_submodule(const char *path, const char *prefix,
616 unsigned int flags)
618 const struct submodule *sub;
619 struct strbuf sb = STRBUF_INIT;
620 char *upd = NULL, *url = NULL, *displaypath;
622 displaypath = get_submodule_displaypath(path, prefix);
624 sub = submodule_from_path(the_repository, &null_oid, path);
626 if (!sub)
627 die(_("No url found for submodule path '%s' in .gitmodules"),
628 displaypath);
631 * NEEDSWORK: In a multi-working-tree world, this needs to be
632 * set in the per-worktree config.
634 * Set active flag for the submodule being initialized
636 if (!is_submodule_active(the_repository, path)) {
637 strbuf_addf(&sb, "submodule.%s.active", sub->name);
638 git_config_set_gently(sb.buf, "true");
639 strbuf_reset(&sb);
643 * Copy url setting when it is not set yet.
644 * To look up the url in .git/config, we must not fall back to
645 * .gitmodules, so look it up directly.
647 strbuf_addf(&sb, "submodule.%s.url", sub->name);
648 if (git_config_get_string(sb.buf, &url)) {
649 if (!sub->url)
650 die(_("No url found for submodule path '%s' in .gitmodules"),
651 displaypath);
653 url = xstrdup(sub->url);
655 /* Possibly a url relative to parent */
656 if (starts_with_dot_dot_slash(url) ||
657 starts_with_dot_slash(url)) {
658 char *oldurl = url;
659 url = compute_submodule_clone_url(oldurl);
660 free(oldurl);
663 if (git_config_set_gently(sb.buf, url))
664 die(_("Failed to register url for submodule path '%s'"),
665 displaypath);
666 if (!(flags & OPT_QUIET))
667 fprintf(stderr,
668 _("Submodule '%s' (%s) registered for path '%s'\n"),
669 sub->name, url, displaypath);
671 strbuf_reset(&sb);
673 /* Copy "update" setting when it is not set yet */
674 strbuf_addf(&sb, "submodule.%s.update", sub->name);
675 if (git_config_get_string(sb.buf, &upd) &&
676 sub->update_strategy.type != SM_UPDATE_UNSPECIFIED) {
677 if (sub->update_strategy.type == SM_UPDATE_COMMAND) {
678 fprintf(stderr, _("warning: command update mode suggested for submodule '%s'\n"),
679 sub->name);
680 upd = xstrdup("none");
681 } else
682 upd = xstrdup(submodule_strategy_to_string(&sub->update_strategy));
684 if (git_config_set_gently(sb.buf, upd))
685 die(_("Failed to register update mode for submodule path '%s'"), displaypath);
687 strbuf_release(&sb);
688 free(displaypath);
689 free(url);
690 free(upd);
693 static void init_submodule_cb(const struct cache_entry *list_item, void *cb_data)
695 struct init_cb *info = cb_data;
696 init_submodule(list_item->name, info->prefix, info->flags);
699 static int module_init(int argc, const char **argv, const char *prefix)
701 struct init_cb info = INIT_CB_INIT;
702 struct pathspec pathspec;
703 struct module_list list = MODULE_LIST_INIT;
704 int quiet = 0;
706 struct option module_init_options[] = {
707 OPT__QUIET(&quiet, N_("Suppress output for initializing a submodule")),
708 OPT_END()
711 const char *const git_submodule_helper_usage[] = {
712 N_("git submodule--helper init [<path>]"),
713 NULL
716 argc = parse_options(argc, argv, prefix, module_init_options,
717 git_submodule_helper_usage, 0);
719 if (module_list_compute(argc, argv, prefix, &pathspec, &list) < 0)
720 return 1;
723 * If there are no path args and submodule.active is set then,
724 * by default, only initialize 'active' modules.
726 if (!argc && git_config_get_value_multi("submodule.active"))
727 module_list_active(&list);
729 info.prefix = prefix;
730 if (quiet)
731 info.flags |= OPT_QUIET;
733 for_each_listed_submodule(&list, init_submodule_cb, &info);
735 return 0;
738 struct status_cb {
739 const char *prefix;
740 unsigned int flags;
743 #define STATUS_CB_INIT { NULL, 0 }
745 static void print_status(unsigned int flags, char state, const char *path,
746 const struct object_id *oid, const char *displaypath)
748 if (flags & OPT_QUIET)
749 return;
751 printf("%c%s %s", state, oid_to_hex(oid), displaypath);
753 if (state == ' ' || state == '+') {
754 const char *name = compute_rev_name(path, oid_to_hex(oid));
756 if (name)
757 printf(" (%s)", name);
760 printf("\n");
763 static int handle_submodule_head_ref(const char *refname,
764 const struct object_id *oid, int flags,
765 void *cb_data)
767 struct object_id *output = cb_data;
768 if (oid)
769 oidcpy(output, oid);
771 return 0;
774 static void status_submodule(const char *path, const struct object_id *ce_oid,
775 unsigned int ce_flags, const char *prefix,
776 unsigned int flags)
778 char *displaypath;
779 struct argv_array diff_files_args = ARGV_ARRAY_INIT;
780 struct rev_info rev;
781 int diff_files_result;
783 if (!submodule_from_path(the_repository, &null_oid, path))
784 die(_("no submodule mapping found in .gitmodules for path '%s'"),
785 path);
787 displaypath = get_submodule_displaypath(path, prefix);
789 if ((CE_STAGEMASK & ce_flags) >> CE_STAGESHIFT) {
790 print_status(flags, 'U', path, &null_oid, displaypath);
791 goto cleanup;
794 if (!is_submodule_active(the_repository, path)) {
795 print_status(flags, '-', path, ce_oid, displaypath);
796 goto cleanup;
799 argv_array_pushl(&diff_files_args, "diff-files",
800 "--ignore-submodules=dirty", "--quiet", "--",
801 path, NULL);
803 git_config(git_diff_basic_config, NULL);
804 repo_init_revisions(the_repository, &rev, prefix);
805 rev.abbrev = 0;
806 diff_files_args.argc = setup_revisions(diff_files_args.argc,
807 diff_files_args.argv,
808 &rev, NULL);
809 diff_files_result = run_diff_files(&rev, 0);
811 if (!diff_result_code(&rev.diffopt, diff_files_result)) {
812 print_status(flags, ' ', path, ce_oid,
813 displaypath);
814 } else if (!(flags & OPT_CACHED)) {
815 struct object_id oid;
816 struct ref_store *refs = get_submodule_ref_store(path);
818 if (!refs) {
819 print_status(flags, '-', path, ce_oid, displaypath);
820 goto cleanup;
822 if (refs_head_ref(refs, handle_submodule_head_ref, &oid))
823 die(_("could not resolve HEAD ref inside the "
824 "submodule '%s'"), path);
826 print_status(flags, '+', path, &oid, displaypath);
827 } else {
828 print_status(flags, '+', path, ce_oid, displaypath);
831 if (flags & OPT_RECURSIVE) {
832 struct child_process cpr = CHILD_PROCESS_INIT;
834 cpr.git_cmd = 1;
835 cpr.dir = path;
836 prepare_submodule_repo_env(&cpr.env_array);
838 argv_array_push(&cpr.args, "--super-prefix");
839 argv_array_pushf(&cpr.args, "%s/", displaypath);
840 argv_array_pushl(&cpr.args, "submodule--helper", "status",
841 "--recursive", NULL);
843 if (flags & OPT_CACHED)
844 argv_array_push(&cpr.args, "--cached");
846 if (flags & OPT_QUIET)
847 argv_array_push(&cpr.args, "--quiet");
849 if (run_command(&cpr))
850 die(_("failed to recurse into submodule '%s'"), path);
853 cleanup:
854 argv_array_clear(&diff_files_args);
855 free(displaypath);
858 static void status_submodule_cb(const struct cache_entry *list_item,
859 void *cb_data)
861 struct status_cb *info = cb_data;
862 status_submodule(list_item->name, &list_item->oid, list_item->ce_flags,
863 info->prefix, info->flags);
866 static int module_status(int argc, const char **argv, const char *prefix)
868 struct status_cb info = STATUS_CB_INIT;
869 struct pathspec pathspec;
870 struct module_list list = MODULE_LIST_INIT;
871 int quiet = 0;
873 struct option module_status_options[] = {
874 OPT__QUIET(&quiet, N_("Suppress submodule status output")),
875 OPT_BIT(0, "cached", &info.flags, N_("Use commit stored in the index instead of the one stored in the submodule HEAD"), OPT_CACHED),
876 OPT_BIT(0, "recursive", &info.flags, N_("recurse into nested submodules"), OPT_RECURSIVE),
877 OPT_END()
880 const char *const git_submodule_helper_usage[] = {
881 N_("git submodule status [--quiet] [--cached] [--recursive] [<path>...]"),
882 NULL
885 argc = parse_options(argc, argv, prefix, module_status_options,
886 git_submodule_helper_usage, 0);
888 if (module_list_compute(argc, argv, prefix, &pathspec, &list) < 0)
889 return 1;
891 info.prefix = prefix;
892 if (quiet)
893 info.flags |= OPT_QUIET;
895 for_each_listed_submodule(&list, status_submodule_cb, &info);
897 return 0;
900 static int module_name(int argc, const char **argv, const char *prefix)
902 const struct submodule *sub;
904 if (argc != 2)
905 usage(_("git submodule--helper name <path>"));
907 sub = submodule_from_path(the_repository, &null_oid, argv[1]);
909 if (!sub)
910 die(_("no submodule mapping found in .gitmodules for path '%s'"),
911 argv[1]);
913 printf("%s\n", sub->name);
915 return 0;
918 struct sync_cb {
919 const char *prefix;
920 unsigned int flags;
923 #define SYNC_CB_INIT { NULL, 0 }
925 static void sync_submodule(const char *path, const char *prefix,
926 unsigned int flags)
928 const struct submodule *sub;
929 char *remote_key = NULL;
930 char *sub_origin_url, *super_config_url, *displaypath;
931 struct strbuf sb = STRBUF_INIT;
932 struct child_process cp = CHILD_PROCESS_INIT;
933 char *sub_config_path = NULL;
935 if (!is_submodule_active(the_repository, path))
936 return;
938 sub = submodule_from_path(the_repository, &null_oid, path);
940 if (sub && sub->url) {
941 if (starts_with_dot_dot_slash(sub->url) ||
942 starts_with_dot_slash(sub->url)) {
943 char *remote_url, *up_path;
944 char *remote = get_default_remote();
945 strbuf_addf(&sb, "remote.%s.url", remote);
947 if (git_config_get_string(sb.buf, &remote_url))
948 remote_url = xgetcwd();
950 up_path = get_up_path(path);
951 sub_origin_url = relative_url(remote_url, sub->url, up_path);
952 super_config_url = relative_url(remote_url, sub->url, NULL);
954 free(remote);
955 free(up_path);
956 free(remote_url);
957 } else {
958 sub_origin_url = xstrdup(sub->url);
959 super_config_url = xstrdup(sub->url);
961 } else {
962 sub_origin_url = xstrdup("");
963 super_config_url = xstrdup("");
966 displaypath = get_submodule_displaypath(path, prefix);
968 if (!(flags & OPT_QUIET))
969 printf(_("Synchronizing submodule url for '%s'\n"),
970 displaypath);
972 strbuf_reset(&sb);
973 strbuf_addf(&sb, "submodule.%s.url", sub->name);
974 if (git_config_set_gently(sb.buf, super_config_url))
975 die(_("failed to register url for submodule path '%s'"),
976 displaypath);
978 if (!is_submodule_populated_gently(path, NULL))
979 goto cleanup;
981 prepare_submodule_repo_env(&cp.env_array);
982 cp.git_cmd = 1;
983 cp.dir = path;
984 argv_array_pushl(&cp.args, "submodule--helper",
985 "print-default-remote", NULL);
987 strbuf_reset(&sb);
988 if (capture_command(&cp, &sb, 0))
989 die(_("failed to get the default remote for submodule '%s'"),
990 path);
992 strbuf_strip_suffix(&sb, "\n");
993 remote_key = xstrfmt("remote.%s.url", sb.buf);
995 strbuf_reset(&sb);
996 submodule_to_gitdir(&sb, path);
997 strbuf_addstr(&sb, "/config");
999 if (git_config_set_in_file_gently(sb.buf, remote_key, sub_origin_url))
1000 die(_("failed to update remote for submodule '%s'"),
1001 path);
1003 if (flags & OPT_RECURSIVE) {
1004 struct child_process cpr = CHILD_PROCESS_INIT;
1006 cpr.git_cmd = 1;
1007 cpr.dir = path;
1008 prepare_submodule_repo_env(&cpr.env_array);
1010 argv_array_push(&cpr.args, "--super-prefix");
1011 argv_array_pushf(&cpr.args, "%s/", displaypath);
1012 argv_array_pushl(&cpr.args, "submodule--helper", "sync",
1013 "--recursive", NULL);
1015 if (flags & OPT_QUIET)
1016 argv_array_push(&cpr.args, "--quiet");
1018 if (run_command(&cpr))
1019 die(_("failed to recurse into submodule '%s'"),
1020 path);
1023 cleanup:
1024 free(super_config_url);
1025 free(sub_origin_url);
1026 strbuf_release(&sb);
1027 free(remote_key);
1028 free(displaypath);
1029 free(sub_config_path);
1032 static void sync_submodule_cb(const struct cache_entry *list_item, void *cb_data)
1034 struct sync_cb *info = cb_data;
1035 sync_submodule(list_item->name, info->prefix, info->flags);
1038 static int module_sync(int argc, const char **argv, const char *prefix)
1040 struct sync_cb info = SYNC_CB_INIT;
1041 struct pathspec pathspec;
1042 struct module_list list = MODULE_LIST_INIT;
1043 int quiet = 0;
1044 int recursive = 0;
1046 struct option module_sync_options[] = {
1047 OPT__QUIET(&quiet, N_("Suppress output of synchronizing submodule url")),
1048 OPT_BOOL(0, "recursive", &recursive,
1049 N_("Recurse into nested submodules")),
1050 OPT_END()
1053 const char *const git_submodule_helper_usage[] = {
1054 N_("git submodule--helper sync [--quiet] [--recursive] [<path>]"),
1055 NULL
1058 argc = parse_options(argc, argv, prefix, module_sync_options,
1059 git_submodule_helper_usage, 0);
1061 if (module_list_compute(argc, argv, prefix, &pathspec, &list) < 0)
1062 return 1;
1064 info.prefix = prefix;
1065 if (quiet)
1066 info.flags |= OPT_QUIET;
1067 if (recursive)
1068 info.flags |= OPT_RECURSIVE;
1070 for_each_listed_submodule(&list, sync_submodule_cb, &info);
1072 return 0;
1075 struct deinit_cb {
1076 const char *prefix;
1077 unsigned int flags;
1079 #define DEINIT_CB_INIT { NULL, 0 }
1081 static void deinit_submodule(const char *path, const char *prefix,
1082 unsigned int flags)
1084 const struct submodule *sub;
1085 char *displaypath = NULL;
1086 struct child_process cp_config = CHILD_PROCESS_INIT;
1087 struct strbuf sb_config = STRBUF_INIT;
1088 char *sub_git_dir = xstrfmt("%s/.git", path);
1090 sub = submodule_from_path(the_repository, &null_oid, path);
1092 if (!sub || !sub->name)
1093 goto cleanup;
1095 displaypath = get_submodule_displaypath(path, prefix);
1097 /* remove the submodule work tree (unless the user already did it) */
1098 if (is_directory(path)) {
1099 struct strbuf sb_rm = STRBUF_INIT;
1100 const char *format;
1103 * protect submodules containing a .git directory
1104 * NEEDSWORK: instead of dying, automatically call
1105 * absorbgitdirs and (possibly) warn.
1107 if (is_directory(sub_git_dir))
1108 die(_("Submodule work tree '%s' contains a .git "
1109 "directory (use 'rm -rf' if you really want "
1110 "to remove it including all of its history)"),
1111 displaypath);
1113 if (!(flags & OPT_FORCE)) {
1114 struct child_process cp_rm = CHILD_PROCESS_INIT;
1115 cp_rm.git_cmd = 1;
1116 argv_array_pushl(&cp_rm.args, "rm", "-qn",
1117 path, NULL);
1119 if (run_command(&cp_rm))
1120 die(_("Submodule work tree '%s' contains local "
1121 "modifications; use '-f' to discard them"),
1122 displaypath);
1125 strbuf_addstr(&sb_rm, path);
1127 if (!remove_dir_recursively(&sb_rm, 0))
1128 format = _("Cleared directory '%s'\n");
1129 else
1130 format = _("Could not remove submodule work tree '%s'\n");
1132 if (!(flags & OPT_QUIET))
1133 printf(format, displaypath);
1135 submodule_unset_core_worktree(sub);
1137 strbuf_release(&sb_rm);
1140 if (mkdir(path, 0777))
1141 printf(_("could not create empty submodule directory %s"),
1142 displaypath);
1144 cp_config.git_cmd = 1;
1145 argv_array_pushl(&cp_config.args, "config", "--get-regexp", NULL);
1146 argv_array_pushf(&cp_config.args, "submodule.%s\\.", sub->name);
1148 /* remove the .git/config entries (unless the user already did it) */
1149 if (!capture_command(&cp_config, &sb_config, 0) && sb_config.len) {
1150 char *sub_key = xstrfmt("submodule.%s", sub->name);
1152 * remove the whole section so we have a clean state when
1153 * the user later decides to init this submodule again
1155 git_config_rename_section_in_file(NULL, sub_key, NULL);
1156 if (!(flags & OPT_QUIET))
1157 printf(_("Submodule '%s' (%s) unregistered for path '%s'\n"),
1158 sub->name, sub->url, displaypath);
1159 free(sub_key);
1162 cleanup:
1163 free(displaypath);
1164 free(sub_git_dir);
1165 strbuf_release(&sb_config);
1168 static void deinit_submodule_cb(const struct cache_entry *list_item,
1169 void *cb_data)
1171 struct deinit_cb *info = cb_data;
1172 deinit_submodule(list_item->name, info->prefix, info->flags);
1175 static int module_deinit(int argc, const char **argv, const char *prefix)
1177 struct deinit_cb info = DEINIT_CB_INIT;
1178 struct pathspec pathspec;
1179 struct module_list list = MODULE_LIST_INIT;
1180 int quiet = 0;
1181 int force = 0;
1182 int all = 0;
1184 struct option module_deinit_options[] = {
1185 OPT__QUIET(&quiet, N_("Suppress submodule status output")),
1186 OPT__FORCE(&force, N_("Remove submodule working trees even if they contain local changes"), 0),
1187 OPT_BOOL(0, "all", &all, N_("Unregister all submodules")),
1188 OPT_END()
1191 const char *const git_submodule_helper_usage[] = {
1192 N_("git submodule deinit [--quiet] [-f | --force] [--all | [--] [<path>...]]"),
1193 NULL
1196 argc = parse_options(argc, argv, prefix, module_deinit_options,
1197 git_submodule_helper_usage, 0);
1199 if (all && argc) {
1200 error("pathspec and --all are incompatible");
1201 usage_with_options(git_submodule_helper_usage,
1202 module_deinit_options);
1205 if (!argc && !all)
1206 die(_("Use '--all' if you really want to deinitialize all submodules"));
1208 if (module_list_compute(argc, argv, prefix, &pathspec, &list) < 0)
1209 return 1;
1211 info.prefix = prefix;
1212 if (quiet)
1213 info.flags |= OPT_QUIET;
1214 if (force)
1215 info.flags |= OPT_FORCE;
1217 for_each_listed_submodule(&list, deinit_submodule_cb, &info);
1219 return 0;
1222 static int clone_submodule(const char *path, const char *gitdir, const char *url,
1223 const char *depth, struct string_list *reference, int dissociate,
1224 int quiet, int progress)
1226 struct child_process cp = CHILD_PROCESS_INIT;
1228 argv_array_push(&cp.args, "clone");
1229 argv_array_push(&cp.args, "--no-checkout");
1230 if (quiet)
1231 argv_array_push(&cp.args, "--quiet");
1232 if (progress)
1233 argv_array_push(&cp.args, "--progress");
1234 if (depth && *depth)
1235 argv_array_pushl(&cp.args, "--depth", depth, NULL);
1236 if (reference->nr) {
1237 struct string_list_item *item;
1238 for_each_string_list_item(item, reference)
1239 argv_array_pushl(&cp.args, "--reference",
1240 item->string, NULL);
1242 if (dissociate)
1243 argv_array_push(&cp.args, "--dissociate");
1244 if (gitdir && *gitdir)
1245 argv_array_pushl(&cp.args, "--separate-git-dir", gitdir, NULL);
1247 argv_array_push(&cp.args, "--");
1248 argv_array_push(&cp.args, url);
1249 argv_array_push(&cp.args, path);
1251 cp.git_cmd = 1;
1252 prepare_submodule_repo_env(&cp.env_array);
1253 cp.no_stdin = 1;
1255 return run_command(&cp);
1258 struct submodule_alternate_setup {
1259 const char *submodule_name;
1260 enum SUBMODULE_ALTERNATE_ERROR_MODE {
1261 SUBMODULE_ALTERNATE_ERROR_DIE,
1262 SUBMODULE_ALTERNATE_ERROR_INFO,
1263 SUBMODULE_ALTERNATE_ERROR_IGNORE
1264 } error_mode;
1265 struct string_list *reference;
1267 #define SUBMODULE_ALTERNATE_SETUP_INIT { NULL, \
1268 SUBMODULE_ALTERNATE_ERROR_IGNORE, NULL }
1270 static int add_possible_reference_from_superproject(
1271 struct object_directory *odb, void *sas_cb)
1273 struct submodule_alternate_setup *sas = sas_cb;
1274 size_t len;
1277 * If the alternate object store is another repository, try the
1278 * standard layout with .git/(modules/<name>)+/objects
1280 if (strip_suffix(odb->path, "/objects", &len)) {
1281 char *sm_alternate;
1282 struct strbuf sb = STRBUF_INIT;
1283 struct strbuf err = STRBUF_INIT;
1284 strbuf_add(&sb, odb->path, len);
1287 * We need to end the new path with '/' to mark it as a dir,
1288 * otherwise a submodule name containing '/' will be broken
1289 * as the last part of a missing submodule reference would
1290 * be taken as a file name.
1292 strbuf_addf(&sb, "/modules/%s/", sas->submodule_name);
1294 sm_alternate = compute_alternate_path(sb.buf, &err);
1295 if (sm_alternate) {
1296 string_list_append(sas->reference, xstrdup(sb.buf));
1297 free(sm_alternate);
1298 } else {
1299 switch (sas->error_mode) {
1300 case SUBMODULE_ALTERNATE_ERROR_DIE:
1301 die(_("submodule '%s' cannot add alternate: %s"),
1302 sas->submodule_name, err.buf);
1303 case SUBMODULE_ALTERNATE_ERROR_INFO:
1304 fprintf(stderr, _("submodule '%s' cannot add alternate: %s"),
1305 sas->submodule_name, err.buf);
1306 case SUBMODULE_ALTERNATE_ERROR_IGNORE:
1307 ; /* nothing */
1310 strbuf_release(&sb);
1313 return 0;
1316 static void prepare_possible_alternates(const char *sm_name,
1317 struct string_list *reference)
1319 char *sm_alternate = NULL, *error_strategy = NULL;
1320 struct submodule_alternate_setup sas = SUBMODULE_ALTERNATE_SETUP_INIT;
1322 git_config_get_string("submodule.alternateLocation", &sm_alternate);
1323 if (!sm_alternate)
1324 return;
1326 git_config_get_string("submodule.alternateErrorStrategy", &error_strategy);
1328 if (!error_strategy)
1329 error_strategy = xstrdup("die");
1331 sas.submodule_name = sm_name;
1332 sas.reference = reference;
1333 if (!strcmp(error_strategy, "die"))
1334 sas.error_mode = SUBMODULE_ALTERNATE_ERROR_DIE;
1335 else if (!strcmp(error_strategy, "info"))
1336 sas.error_mode = SUBMODULE_ALTERNATE_ERROR_INFO;
1337 else if (!strcmp(error_strategy, "ignore"))
1338 sas.error_mode = SUBMODULE_ALTERNATE_ERROR_IGNORE;
1339 else
1340 die(_("Value '%s' for submodule.alternateErrorStrategy is not recognized"), error_strategy);
1342 if (!strcmp(sm_alternate, "superproject"))
1343 foreach_alt_odb(add_possible_reference_from_superproject, &sas);
1344 else if (!strcmp(sm_alternate, "no"))
1345 ; /* do nothing */
1346 else
1347 die(_("Value '%s' for submodule.alternateLocation is not recognized"), sm_alternate);
1349 free(sm_alternate);
1350 free(error_strategy);
1353 static int module_clone(int argc, const char **argv, const char *prefix)
1355 const char *name = NULL, *url = NULL, *depth = NULL;
1356 int quiet = 0;
1357 int progress = 0;
1358 char *p, *path = NULL, *sm_gitdir;
1359 struct strbuf sb = STRBUF_INIT;
1360 struct string_list reference = STRING_LIST_INIT_NODUP;
1361 int dissociate = 0;
1362 char *sm_alternate = NULL, *error_strategy = NULL;
1364 struct option module_clone_options[] = {
1365 OPT_STRING(0, "prefix", &prefix,
1366 N_("path"),
1367 N_("alternative anchor for relative paths")),
1368 OPT_STRING(0, "path", &path,
1369 N_("path"),
1370 N_("where the new submodule will be cloned to")),
1371 OPT_STRING(0, "name", &name,
1372 N_("string"),
1373 N_("name of the new submodule")),
1374 OPT_STRING(0, "url", &url,
1375 N_("string"),
1376 N_("url where to clone the submodule from")),
1377 OPT_STRING_LIST(0, "reference", &reference,
1378 N_("repo"),
1379 N_("reference repository")),
1380 OPT_BOOL(0, "dissociate", &dissociate,
1381 N_("use --reference only while cloning")),
1382 OPT_STRING(0, "depth", &depth,
1383 N_("string"),
1384 N_("depth for shallow clones")),
1385 OPT__QUIET(&quiet, "Suppress output for cloning a submodule"),
1386 OPT_BOOL(0, "progress", &progress,
1387 N_("force cloning progress")),
1388 OPT_END()
1391 const char *const git_submodule_helper_usage[] = {
1392 N_("git submodule--helper clone [--prefix=<path>] [--quiet] "
1393 "[--reference <repository>] [--name <name>] [--depth <depth>] "
1394 "--url <url> --path <path>"),
1395 NULL
1398 argc = parse_options(argc, argv, prefix, module_clone_options,
1399 git_submodule_helper_usage, 0);
1401 if (argc || !url || !path || !*path)
1402 usage_with_options(git_submodule_helper_usage,
1403 module_clone_options);
1405 strbuf_addf(&sb, "%s/modules/%s", get_git_dir(), name);
1406 sm_gitdir = absolute_pathdup(sb.buf);
1407 strbuf_reset(&sb);
1409 if (!is_absolute_path(path)) {
1410 strbuf_addf(&sb, "%s/%s", get_git_work_tree(), path);
1411 path = strbuf_detach(&sb, NULL);
1412 } else
1413 path = xstrdup(path);
1415 if (!file_exists(sm_gitdir)) {
1416 if (safe_create_leading_directories_const(sm_gitdir) < 0)
1417 die(_("could not create directory '%s'"), sm_gitdir);
1419 prepare_possible_alternates(name, &reference);
1421 if (clone_submodule(path, sm_gitdir, url, depth, &reference, dissociate,
1422 quiet, progress))
1423 die(_("clone of '%s' into submodule path '%s' failed"),
1424 url, path);
1425 } else {
1426 if (safe_create_leading_directories_const(path) < 0)
1427 die(_("could not create directory '%s'"), path);
1428 strbuf_addf(&sb, "%s/index", sm_gitdir);
1429 unlink_or_warn(sb.buf);
1430 strbuf_reset(&sb);
1433 connect_work_tree_and_git_dir(path, sm_gitdir, 0);
1435 p = git_pathdup_submodule(path, "config");
1436 if (!p)
1437 die(_("could not get submodule directory for '%s'"), path);
1439 /* setup alternateLocation and alternateErrorStrategy in the cloned submodule if needed */
1440 git_config_get_string("submodule.alternateLocation", &sm_alternate);
1441 if (sm_alternate)
1442 git_config_set_in_file(p, "submodule.alternateLocation",
1443 sm_alternate);
1444 git_config_get_string("submodule.alternateErrorStrategy", &error_strategy);
1445 if (error_strategy)
1446 git_config_set_in_file(p, "submodule.alternateErrorStrategy",
1447 error_strategy);
1449 free(sm_alternate);
1450 free(error_strategy);
1452 strbuf_release(&sb);
1453 free(sm_gitdir);
1454 free(path);
1455 free(p);
1456 return 0;
1459 static void determine_submodule_update_strategy(struct repository *r,
1460 int just_cloned,
1461 const char *path,
1462 const char *update,
1463 struct submodule_update_strategy *out)
1465 const struct submodule *sub = submodule_from_path(r, &null_oid, path);
1466 char *key;
1467 const char *val;
1469 key = xstrfmt("submodule.%s.update", sub->name);
1471 if (update) {
1472 if (parse_submodule_update_strategy(update, out) < 0)
1473 die(_("Invalid update mode '%s' for submodule path '%s'"),
1474 update, path);
1475 } else if (!repo_config_get_string_const(r, key, &val)) {
1476 if (parse_submodule_update_strategy(val, out) < 0)
1477 die(_("Invalid update mode '%s' configured for submodule path '%s'"),
1478 val, path);
1479 } else if (sub->update_strategy.type != SM_UPDATE_UNSPECIFIED) {
1480 out->type = sub->update_strategy.type;
1481 out->command = sub->update_strategy.command;
1482 } else
1483 out->type = SM_UPDATE_CHECKOUT;
1485 if (just_cloned &&
1486 (out->type == SM_UPDATE_MERGE ||
1487 out->type == SM_UPDATE_REBASE ||
1488 out->type == SM_UPDATE_NONE))
1489 out->type = SM_UPDATE_CHECKOUT;
1491 free(key);
1494 static int module_update_module_mode(int argc, const char **argv, const char *prefix)
1496 const char *path, *update = NULL;
1497 int just_cloned;
1498 struct submodule_update_strategy update_strategy = { .type = SM_UPDATE_CHECKOUT };
1500 if (argc < 3 || argc > 4)
1501 die("submodule--helper update-module-clone expects <just-cloned> <path> [<update>]");
1503 just_cloned = git_config_int("just_cloned", argv[1]);
1504 path = argv[2];
1506 if (argc == 4)
1507 update = argv[3];
1509 determine_submodule_update_strategy(the_repository,
1510 just_cloned, path, update,
1511 &update_strategy);
1512 fputs(submodule_strategy_to_string(&update_strategy), stdout);
1514 return 0;
1517 struct update_clone_data {
1518 const struct submodule *sub;
1519 struct object_id oid;
1520 unsigned just_cloned;
1523 struct submodule_update_clone {
1524 /* index into 'list', the list of submodules to look into for cloning */
1525 int current;
1526 struct module_list list;
1527 unsigned warn_if_uninitialized : 1;
1529 /* update parameter passed via commandline */
1530 struct submodule_update_strategy update;
1532 /* configuration parameters which are passed on to the children */
1533 int progress;
1534 int quiet;
1535 int recommend_shallow;
1536 struct string_list references;
1537 int dissociate;
1538 const char *depth;
1539 const char *recursive_prefix;
1540 const char *prefix;
1542 /* to be consumed by git-submodule.sh */
1543 struct update_clone_data *update_clone;
1544 int update_clone_nr; int update_clone_alloc;
1546 /* If we want to stop as fast as possible and return an error */
1547 unsigned quickstop : 1;
1549 /* failed clones to be retried again */
1550 const struct cache_entry **failed_clones;
1551 int failed_clones_nr, failed_clones_alloc;
1553 int max_jobs;
1555 #define SUBMODULE_UPDATE_CLONE_INIT {0, MODULE_LIST_INIT, 0, \
1556 SUBMODULE_UPDATE_STRATEGY_INIT, 0, 0, -1, STRING_LIST_INIT_DUP, 0, \
1557 NULL, NULL, NULL, \
1558 NULL, 0, 0, 0, NULL, 0, 0, 1}
1561 static void next_submodule_warn_missing(struct submodule_update_clone *suc,
1562 struct strbuf *out, const char *displaypath)
1565 * Only mention uninitialized submodules when their
1566 * paths have been specified.
1568 if (suc->warn_if_uninitialized) {
1569 strbuf_addf(out,
1570 _("Submodule path '%s' not initialized"),
1571 displaypath);
1572 strbuf_addch(out, '\n');
1573 strbuf_addstr(out,
1574 _("Maybe you want to use 'update --init'?"));
1575 strbuf_addch(out, '\n');
1580 * Determine whether 'ce' needs to be cloned. If so, prepare the 'child' to
1581 * run the clone. Returns 1 if 'ce' needs to be cloned, 0 otherwise.
1583 static int prepare_to_clone_next_submodule(const struct cache_entry *ce,
1584 struct child_process *child,
1585 struct submodule_update_clone *suc,
1586 struct strbuf *out)
1588 const struct submodule *sub = NULL;
1589 const char *url = NULL;
1590 const char *update_string;
1591 enum submodule_update_type update_type;
1592 char *key;
1593 struct strbuf displaypath_sb = STRBUF_INIT;
1594 struct strbuf sb = STRBUF_INIT;
1595 const char *displaypath = NULL;
1596 int needs_cloning = 0;
1597 int need_free_url = 0;
1599 if (ce_stage(ce)) {
1600 if (suc->recursive_prefix)
1601 strbuf_addf(&sb, "%s/%s", suc->recursive_prefix, ce->name);
1602 else
1603 strbuf_addstr(&sb, ce->name);
1604 strbuf_addf(out, _("Skipping unmerged submodule %s"), sb.buf);
1605 strbuf_addch(out, '\n');
1606 goto cleanup;
1609 sub = submodule_from_path(the_repository, &null_oid, ce->name);
1611 if (suc->recursive_prefix)
1612 displaypath = relative_path(suc->recursive_prefix,
1613 ce->name, &displaypath_sb);
1614 else
1615 displaypath = ce->name;
1617 if (!sub) {
1618 next_submodule_warn_missing(suc, out, displaypath);
1619 goto cleanup;
1622 key = xstrfmt("submodule.%s.update", sub->name);
1623 if (!repo_config_get_string_const(the_repository, key, &update_string)) {
1624 update_type = parse_submodule_update_type(update_string);
1625 } else {
1626 update_type = sub->update_strategy.type;
1628 free(key);
1630 if (suc->update.type == SM_UPDATE_NONE
1631 || (suc->update.type == SM_UPDATE_UNSPECIFIED
1632 && update_type == SM_UPDATE_NONE)) {
1633 strbuf_addf(out, _("Skipping submodule '%s'"), displaypath);
1634 strbuf_addch(out, '\n');
1635 goto cleanup;
1638 /* Check if the submodule has been initialized. */
1639 if (!is_submodule_active(the_repository, ce->name)) {
1640 next_submodule_warn_missing(suc, out, displaypath);
1641 goto cleanup;
1644 strbuf_reset(&sb);
1645 strbuf_addf(&sb, "submodule.%s.url", sub->name);
1646 if (repo_config_get_string_const(the_repository, sb.buf, &url)) {
1647 if (starts_with_dot_slash(sub->url) ||
1648 starts_with_dot_dot_slash(sub->url)) {
1649 url = compute_submodule_clone_url(sub->url);
1650 need_free_url = 1;
1651 } else
1652 url = sub->url;
1655 strbuf_reset(&sb);
1656 strbuf_addf(&sb, "%s/.git", ce->name);
1657 needs_cloning = !file_exists(sb.buf);
1659 ALLOC_GROW(suc->update_clone, suc->update_clone_nr + 1,
1660 suc->update_clone_alloc);
1661 oidcpy(&suc->update_clone[suc->update_clone_nr].oid, &ce->oid);
1662 suc->update_clone[suc->update_clone_nr].just_cloned = needs_cloning;
1663 suc->update_clone[suc->update_clone_nr].sub = sub;
1664 suc->update_clone_nr++;
1666 if (!needs_cloning)
1667 goto cleanup;
1669 child->git_cmd = 1;
1670 child->no_stdin = 1;
1671 child->stdout_to_stderr = 1;
1672 child->err = -1;
1673 argv_array_push(&child->args, "submodule--helper");
1674 argv_array_push(&child->args, "clone");
1675 if (suc->progress)
1676 argv_array_push(&child->args, "--progress");
1677 if (suc->quiet)
1678 argv_array_push(&child->args, "--quiet");
1679 if (suc->prefix)
1680 argv_array_pushl(&child->args, "--prefix", suc->prefix, NULL);
1681 if (suc->recommend_shallow && sub->recommend_shallow == 1)
1682 argv_array_push(&child->args, "--depth=1");
1683 argv_array_pushl(&child->args, "--path", sub->path, NULL);
1684 argv_array_pushl(&child->args, "--name", sub->name, NULL);
1685 argv_array_pushl(&child->args, "--url", url, NULL);
1686 if (suc->references.nr) {
1687 struct string_list_item *item;
1688 for_each_string_list_item(item, &suc->references)
1689 argv_array_pushl(&child->args, "--reference", item->string, NULL);
1691 if (suc->dissociate)
1692 argv_array_push(&child->args, "--dissociate");
1693 if (suc->depth)
1694 argv_array_push(&child->args, suc->depth);
1696 cleanup:
1697 strbuf_reset(&displaypath_sb);
1698 strbuf_reset(&sb);
1699 if (need_free_url)
1700 free((void*)url);
1702 return needs_cloning;
1705 static int update_clone_get_next_task(struct child_process *child,
1706 struct strbuf *err,
1707 void *suc_cb,
1708 void **idx_task_cb)
1710 struct submodule_update_clone *suc = suc_cb;
1711 const struct cache_entry *ce;
1712 int index;
1714 for (; suc->current < suc->list.nr; suc->current++) {
1715 ce = suc->list.entries[suc->current];
1716 if (prepare_to_clone_next_submodule(ce, child, suc, err)) {
1717 int *p = xmalloc(sizeof(*p));
1718 *p = suc->current;
1719 *idx_task_cb = p;
1720 suc->current++;
1721 return 1;
1726 * The loop above tried cloning each submodule once, now try the
1727 * stragglers again, which we can imagine as an extension of the
1728 * entry list.
1730 index = suc->current - suc->list.nr;
1731 if (index < suc->failed_clones_nr) {
1732 int *p;
1733 ce = suc->failed_clones[index];
1734 if (!prepare_to_clone_next_submodule(ce, child, suc, err)) {
1735 suc->current ++;
1736 strbuf_addstr(err, "BUG: submodule considered for "
1737 "cloning, doesn't need cloning "
1738 "any more?\n");
1739 return 0;
1741 p = xmalloc(sizeof(*p));
1742 *p = suc->current;
1743 *idx_task_cb = p;
1744 suc->current ++;
1745 return 1;
1748 return 0;
1751 static int update_clone_start_failure(struct strbuf *err,
1752 void *suc_cb,
1753 void *idx_task_cb)
1755 struct submodule_update_clone *suc = suc_cb;
1756 suc->quickstop = 1;
1757 return 1;
1760 static int update_clone_task_finished(int result,
1761 struct strbuf *err,
1762 void *suc_cb,
1763 void *idx_task_cb)
1765 const struct cache_entry *ce;
1766 struct submodule_update_clone *suc = suc_cb;
1768 int *idxP = idx_task_cb;
1769 int idx = *idxP;
1770 free(idxP);
1772 if (!result)
1773 return 0;
1775 if (idx < suc->list.nr) {
1776 ce = suc->list.entries[idx];
1777 strbuf_addf(err, _("Failed to clone '%s'. Retry scheduled"),
1778 ce->name);
1779 strbuf_addch(err, '\n');
1780 ALLOC_GROW(suc->failed_clones,
1781 suc->failed_clones_nr + 1,
1782 suc->failed_clones_alloc);
1783 suc->failed_clones[suc->failed_clones_nr++] = ce;
1784 return 0;
1785 } else {
1786 idx -= suc->list.nr;
1787 ce = suc->failed_clones[idx];
1788 strbuf_addf(err, _("Failed to clone '%s' a second time, aborting"),
1789 ce->name);
1790 strbuf_addch(err, '\n');
1791 suc->quickstop = 1;
1792 return 1;
1795 return 0;
1798 static int git_update_clone_config(const char *var, const char *value,
1799 void *cb)
1801 int *max_jobs = cb;
1802 if (!strcmp(var, "submodule.fetchjobs"))
1803 *max_jobs = parse_submodule_fetchjobs(var, value);
1804 return 0;
1807 static void update_submodule(struct update_clone_data *ucd)
1809 fprintf(stdout, "dummy %s %d\t%s\n",
1810 oid_to_hex(&ucd->oid),
1811 ucd->just_cloned,
1812 ucd->sub->path);
1815 static int update_submodules(struct submodule_update_clone *suc)
1817 int i;
1819 run_processes_parallel_tr2(suc->max_jobs, update_clone_get_next_task,
1820 update_clone_start_failure,
1821 update_clone_task_finished, suc, "submodule",
1822 "parallel/update");
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, sub))
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]);