Merge branch 'ab/unused-annotation'
[git.git] / builtin / submodule--helper.c
blob60f9f568c612a69d2cc409f8785c697833d51b63
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"
22 #include "advice.h"
23 #include "branch.h"
24 #include "list-objects-filter-options.h"
26 #define OPT_QUIET (1 << 0)
27 #define OPT_CACHED (1 << 1)
28 #define OPT_RECURSIVE (1 << 2)
29 #define OPT_FORCE (1 << 3)
31 typedef void (*each_submodule_fn)(const struct cache_entry *list_item,
32 void *cb_data);
34 static int repo_get_default_remote(struct repository *repo, char **default_remote)
36 char *dest = NULL;
37 struct strbuf sb = STRBUF_INIT;
38 struct ref_store *store = get_main_ref_store(repo);
39 const char *refname = refs_resolve_ref_unsafe(store, "HEAD", 0, NULL,
40 NULL);
42 if (!refname)
43 return die_message(_("No such ref: %s"), "HEAD");
45 /* detached HEAD */
46 if (!strcmp(refname, "HEAD")) {
47 *default_remote = xstrdup("origin");
48 return 0;
51 if (!skip_prefix(refname, "refs/heads/", &refname))
52 return die_message(_("Expecting a full ref name, got %s"),
53 refname);
55 strbuf_addf(&sb, "branch.%s.remote", refname);
56 if (repo_config_get_string(repo, sb.buf, &dest))
57 *default_remote = xstrdup("origin");
58 else
59 *default_remote = dest;
61 strbuf_release(&sb);
62 return 0;
65 static int get_default_remote_submodule(const char *module_path, char **default_remote)
67 struct repository subrepo;
69 if (repo_submodule_init(&subrepo, the_repository, module_path,
70 null_oid()) < 0)
71 return die_message(_("could not get a repository handle for submodule '%s'"),
72 module_path);
73 return repo_get_default_remote(&subrepo, default_remote);
76 static char *get_default_remote(void)
78 char *default_remote;
79 int code = repo_get_default_remote(the_repository, &default_remote);
81 if (code)
82 exit(code);
84 return default_remote;
87 static char *resolve_relative_url(const char *rel_url, const char *up_path, int quiet)
89 char *remoteurl, *resolved_url;
90 char *remote = get_default_remote();
91 struct strbuf remotesb = STRBUF_INIT;
93 strbuf_addf(&remotesb, "remote.%s.url", remote);
94 if (git_config_get_string(remotesb.buf, &remoteurl)) {
95 if (!quiet)
96 warning(_("could not look up configuration '%s'. "
97 "Assuming this repository is its own "
98 "authoritative upstream."),
99 remotesb.buf);
100 remoteurl = xgetcwd();
102 resolved_url = relative_url(remoteurl, rel_url, up_path);
104 free(remote);
105 free(remoteurl);
106 strbuf_release(&remotesb);
108 return resolved_url;
111 /* the result should be freed by the caller. */
112 static char *get_submodule_displaypath(const char *path, const char *prefix)
114 const char *super_prefix = get_super_prefix();
116 if (prefix && super_prefix) {
117 BUG("cannot have prefix '%s' and superprefix '%s'",
118 prefix, super_prefix);
119 } else if (prefix) {
120 struct strbuf sb = STRBUF_INIT;
121 char *displaypath = xstrdup(relative_path(path, prefix, &sb));
122 strbuf_release(&sb);
123 return displaypath;
124 } else if (super_prefix) {
125 return xstrfmt("%s%s", super_prefix, path);
126 } else {
127 return xstrdup(path);
131 static char *compute_rev_name(const char *sub_path, const char* object_id)
133 struct strbuf sb = STRBUF_INIT;
134 const char ***d;
136 static const char *describe_bare[] = { NULL };
138 static const char *describe_tags[] = { "--tags", NULL };
140 static const char *describe_contains[] = { "--contains", NULL };
142 static const char *describe_all_always[] = { "--all", "--always", NULL };
144 static const char **describe_argv[] = { describe_bare, describe_tags,
145 describe_contains,
146 describe_all_always, NULL };
148 for (d = describe_argv; *d; d++) {
149 struct child_process cp = CHILD_PROCESS_INIT;
150 prepare_submodule_repo_env(&cp.env);
151 cp.dir = sub_path;
152 cp.git_cmd = 1;
153 cp.no_stderr = 1;
155 strvec_push(&cp.args, "describe");
156 strvec_pushv(&cp.args, *d);
157 strvec_push(&cp.args, object_id);
159 if (!capture_command(&cp, &sb, 0)) {
160 strbuf_strip_suffix(&sb, "\n");
161 return strbuf_detach(&sb, NULL);
165 strbuf_release(&sb);
166 return NULL;
169 struct module_list {
170 const struct cache_entry **entries;
171 int alloc, nr;
173 #define MODULE_LIST_INIT { 0 }
175 static int module_list_compute(int argc, const char **argv,
176 const char *prefix,
177 struct pathspec *pathspec,
178 struct module_list *list)
180 int i, result = 0;
181 char *ps_matched = NULL;
183 parse_pathspec(pathspec, 0,
184 PATHSPEC_PREFER_FULL,
185 prefix, argv);
187 if (pathspec->nr)
188 ps_matched = xcalloc(pathspec->nr, 1);
190 if (read_cache() < 0)
191 die(_("index file corrupt"));
193 for (i = 0; i < active_nr; i++) {
194 const struct cache_entry *ce = active_cache[i];
196 if (!match_pathspec(&the_index, pathspec, ce->name, ce_namelen(ce),
197 0, ps_matched, 1) ||
198 !S_ISGITLINK(ce->ce_mode))
199 continue;
201 ALLOC_GROW(list->entries, list->nr + 1, list->alloc);
202 list->entries[list->nr++] = ce;
203 while (i + 1 < active_nr &&
204 !strcmp(ce->name, active_cache[i + 1]->name))
206 * Skip entries with the same name in different stages
207 * to make sure an entry is returned only once.
209 i++;
212 if (ps_matched && report_path_error(ps_matched, pathspec))
213 result = -1;
215 free(ps_matched);
217 return result;
220 static void module_list_active(struct module_list *list)
222 int i;
223 struct module_list active_modules = MODULE_LIST_INIT;
225 for (i = 0; i < list->nr; i++) {
226 const struct cache_entry *ce = list->entries[i];
228 if (!is_submodule_active(the_repository, ce->name))
229 continue;
231 ALLOC_GROW(active_modules.entries,
232 active_modules.nr + 1,
233 active_modules.alloc);
234 active_modules.entries[active_modules.nr++] = ce;
237 free(list->entries);
238 *list = active_modules;
241 static char *get_up_path(const char *path)
243 int i;
244 struct strbuf sb = STRBUF_INIT;
246 for (i = count_slashes(path); i; i--)
247 strbuf_addstr(&sb, "../");
250 * Check if 'path' ends with slash or not
251 * for having the same output for dir/sub_dir
252 * and dir/sub_dir/
254 if (!is_dir_sep(path[strlen(path) - 1]))
255 strbuf_addstr(&sb, "../");
257 return strbuf_detach(&sb, NULL);
260 static void for_each_listed_submodule(const struct module_list *list,
261 each_submodule_fn fn, void *cb_data)
263 int i;
265 for (i = 0; i < list->nr; i++)
266 fn(list->entries[i], cb_data);
269 struct foreach_cb {
270 int argc;
271 const char **argv;
272 const char *prefix;
273 int quiet;
274 int recursive;
276 #define FOREACH_CB_INIT { 0 }
278 static void runcommand_in_submodule_cb(const struct cache_entry *list_item,
279 void *cb_data)
281 struct foreach_cb *info = cb_data;
282 const char *path = list_item->name;
283 const struct object_id *ce_oid = &list_item->oid;
284 const struct submodule *sub;
285 struct child_process cp = CHILD_PROCESS_INIT;
286 char *displaypath;
288 displaypath = get_submodule_displaypath(path, info->prefix);
290 sub = submodule_from_path(the_repository, null_oid(), path);
292 if (!sub)
293 die(_("No url found for submodule path '%s' in .gitmodules"),
294 displaypath);
296 if (!is_submodule_populated_gently(path, NULL))
297 goto cleanup;
299 prepare_submodule_repo_env(&cp.env);
302 * For the purpose of executing <command> in the submodule,
303 * separate shell is used for the purpose of running the
304 * child process.
306 cp.use_shell = 1;
307 cp.dir = path;
310 * NEEDSWORK: the command currently has access to the variables $name,
311 * $sm_path, $displaypath, $sha1 and $toplevel only when the command
312 * contains a single argument. This is done for maintaining a faithful
313 * translation from shell script.
315 if (info->argc == 1) {
316 char *toplevel = xgetcwd();
317 struct strbuf sb = STRBUF_INIT;
319 strvec_pushf(&cp.env, "name=%s", sub->name);
320 strvec_pushf(&cp.env, "sm_path=%s", path);
321 strvec_pushf(&cp.env, "displaypath=%s", displaypath);
322 strvec_pushf(&cp.env, "sha1=%s",
323 oid_to_hex(ce_oid));
324 strvec_pushf(&cp.env, "toplevel=%s", toplevel);
327 * Since the path variable was accessible from the script
328 * before porting, it is also made available after porting.
329 * The environment variable "PATH" has a very special purpose
330 * on windows. And since environment variables are
331 * case-insensitive in windows, it interferes with the
332 * existing PATH variable. Hence, to avoid that, we expose
333 * path via the args strvec and not via env.
335 sq_quote_buf(&sb, path);
336 strvec_pushf(&cp.args, "path=%s; %s",
337 sb.buf, info->argv[0]);
338 strbuf_release(&sb);
339 free(toplevel);
340 } else {
341 strvec_pushv(&cp.args, info->argv);
344 if (!info->quiet)
345 printf(_("Entering '%s'\n"), displaypath);
347 if (info->argv[0] && run_command(&cp))
348 die(_("run_command returned non-zero status for %s\n."),
349 displaypath);
351 if (info->recursive) {
352 struct child_process cpr = CHILD_PROCESS_INIT;
354 cpr.git_cmd = 1;
355 cpr.dir = path;
356 prepare_submodule_repo_env(&cpr.env);
358 strvec_pushl(&cpr.args, "--super-prefix", NULL);
359 strvec_pushf(&cpr.args, "%s/", displaypath);
360 strvec_pushl(&cpr.args, "submodule--helper", "foreach", "--recursive",
361 NULL);
363 if (info->quiet)
364 strvec_push(&cpr.args, "--quiet");
366 strvec_push(&cpr.args, "--");
367 strvec_pushv(&cpr.args, info->argv);
369 if (run_command(&cpr))
370 die(_("run_command returned non-zero status while "
371 "recursing in the nested submodules of %s\n."),
372 displaypath);
375 cleanup:
376 free(displaypath);
379 static int module_foreach(int argc, const char **argv, const char *prefix)
381 struct foreach_cb info = FOREACH_CB_INIT;
382 struct pathspec pathspec;
383 struct module_list list = MODULE_LIST_INIT;
384 struct option module_foreach_options[] = {
385 OPT__QUIET(&info.quiet, N_("suppress output of entering each submodule command")),
386 OPT_BOOL(0, "recursive", &info.recursive,
387 N_("recurse into nested submodules")),
388 OPT_END()
390 const char *const git_submodule_helper_usage[] = {
391 N_("git submodule foreach [--quiet] [--recursive] [--] <command>"),
392 NULL
395 argc = parse_options(argc, argv, prefix, module_foreach_options,
396 git_submodule_helper_usage, 0);
398 if (module_list_compute(0, NULL, prefix, &pathspec, &list) < 0)
399 return 1;
401 info.argc = argc;
402 info.argv = argv;
403 info.prefix = prefix;
405 for_each_listed_submodule(&list, runcommand_in_submodule_cb, &info);
407 return 0;
410 static int starts_with_dot_slash(const char *const path)
412 return path_match_flags(path, PATH_MATCH_STARTS_WITH_DOT_SLASH |
413 PATH_MATCH_XPLATFORM);
416 static int starts_with_dot_dot_slash(const char *const path)
418 return path_match_flags(path, PATH_MATCH_STARTS_WITH_DOT_DOT_SLASH |
419 PATH_MATCH_XPLATFORM);
422 struct init_cb {
423 const char *prefix;
424 unsigned int flags;
426 #define INIT_CB_INIT { 0 }
428 static void init_submodule(const char *path, const char *prefix,
429 unsigned int flags)
431 const struct submodule *sub;
432 struct strbuf sb = STRBUF_INIT;
433 const char *upd;
434 char *url = NULL, *displaypath;
436 displaypath = get_submodule_displaypath(path, prefix);
438 sub = submodule_from_path(the_repository, null_oid(), path);
440 if (!sub)
441 die(_("No url found for submodule path '%s' in .gitmodules"),
442 displaypath);
445 * NEEDSWORK: In a multi-working-tree world, this needs to be
446 * set in the per-worktree config.
448 * Set active flag for the submodule being initialized
450 if (!is_submodule_active(the_repository, path)) {
451 strbuf_addf(&sb, "submodule.%s.active", sub->name);
452 git_config_set_gently(sb.buf, "true");
453 strbuf_reset(&sb);
457 * Copy url setting when it is not set yet.
458 * To look up the url in .git/config, we must not fall back to
459 * .gitmodules, so look it up directly.
461 strbuf_addf(&sb, "submodule.%s.url", sub->name);
462 if (git_config_get_string(sb.buf, &url)) {
463 if (!sub->url)
464 die(_("No url found for submodule path '%s' in .gitmodules"),
465 displaypath);
467 url = xstrdup(sub->url);
469 /* Possibly a url relative to parent */
470 if (starts_with_dot_dot_slash(url) ||
471 starts_with_dot_slash(url)) {
472 char *oldurl = url;
474 url = resolve_relative_url(oldurl, NULL, 0);
475 free(oldurl);
478 if (git_config_set_gently(sb.buf, url))
479 die(_("Failed to register url for submodule path '%s'"),
480 displaypath);
481 if (!(flags & OPT_QUIET))
482 fprintf(stderr,
483 _("Submodule '%s' (%s) registered for path '%s'\n"),
484 sub->name, url, displaypath);
486 strbuf_reset(&sb);
488 /* Copy "update" setting when it is not set yet */
489 strbuf_addf(&sb, "submodule.%s.update", sub->name);
490 if (git_config_get_string_tmp(sb.buf, &upd) &&
491 sub->update_strategy.type != SM_UPDATE_UNSPECIFIED) {
492 if (sub->update_strategy.type == SM_UPDATE_COMMAND) {
493 fprintf(stderr, _("warning: command update mode suggested for submodule '%s'\n"),
494 sub->name);
495 upd = "none";
496 } else {
497 upd = submodule_update_type_to_string(sub->update_strategy.type);
500 if (git_config_set_gently(sb.buf, upd))
501 die(_("Failed to register update mode for submodule path '%s'"), displaypath);
503 strbuf_release(&sb);
504 free(displaypath);
505 free(url);
508 static void init_submodule_cb(const struct cache_entry *list_item, void *cb_data)
510 struct init_cb *info = cb_data;
512 init_submodule(list_item->name, info->prefix, info->flags);
515 static int module_init(int argc, const char **argv, const char *prefix)
517 struct init_cb info = INIT_CB_INIT;
518 struct pathspec pathspec;
519 struct module_list list = MODULE_LIST_INIT;
520 int quiet = 0;
521 struct option module_init_options[] = {
522 OPT__QUIET(&quiet, N_("suppress output for initializing a submodule")),
523 OPT_END()
525 const char *const git_submodule_helper_usage[] = {
526 N_("git submodule init [<options>] [<path>]"),
527 NULL
530 argc = parse_options(argc, argv, prefix, module_init_options,
531 git_submodule_helper_usage, 0);
533 if (module_list_compute(argc, argv, prefix, &pathspec, &list) < 0)
534 return 1;
537 * If there are no path args and submodule.active is set then,
538 * by default, only initialize 'active' modules.
540 if (!argc && git_config_get_value_multi("submodule.active"))
541 module_list_active(&list);
543 info.prefix = prefix;
544 if (quiet)
545 info.flags |= OPT_QUIET;
547 for_each_listed_submodule(&list, init_submodule_cb, &info);
549 return 0;
552 struct status_cb {
553 const char *prefix;
554 unsigned int flags;
556 #define STATUS_CB_INIT { 0 }
558 static void print_status(unsigned int flags, char state, const char *path,
559 const struct object_id *oid, const char *displaypath)
561 if (flags & OPT_QUIET)
562 return;
564 printf("%c%s %s", state, oid_to_hex(oid), displaypath);
566 if (state == ' ' || state == '+') {
567 const char *name = compute_rev_name(path, oid_to_hex(oid));
569 if (name)
570 printf(" (%s)", name);
573 printf("\n");
576 static int handle_submodule_head_ref(const char *refname UNUSED,
577 const struct object_id *oid,
578 int flags UNUSED,
579 void *cb_data)
581 struct object_id *output = cb_data;
583 if (oid)
584 oidcpy(output, oid);
586 return 0;
589 static void status_submodule(const char *path, const struct object_id *ce_oid,
590 unsigned int ce_flags, const char *prefix,
591 unsigned int flags)
593 char *displaypath;
594 struct strvec diff_files_args = STRVEC_INIT;
595 struct rev_info rev = REV_INFO_INIT;
596 int diff_files_result;
597 struct strbuf buf = STRBUF_INIT;
598 const char *git_dir;
600 if (!submodule_from_path(the_repository, null_oid(), path))
601 die(_("no submodule mapping found in .gitmodules for path '%s'"),
602 path);
604 displaypath = get_submodule_displaypath(path, prefix);
606 if ((CE_STAGEMASK & ce_flags) >> CE_STAGESHIFT) {
607 print_status(flags, 'U', path, null_oid(), displaypath);
608 goto cleanup;
611 strbuf_addf(&buf, "%s/.git", path);
612 git_dir = read_gitfile(buf.buf);
613 if (!git_dir)
614 git_dir = buf.buf;
616 if (!is_submodule_active(the_repository, path) ||
617 !is_git_directory(git_dir)) {
618 print_status(flags, '-', path, ce_oid, displaypath);
619 strbuf_release(&buf);
620 goto cleanup;
622 strbuf_release(&buf);
624 strvec_pushl(&diff_files_args, "diff-files",
625 "--ignore-submodules=dirty", "--quiet", "--",
626 path, NULL);
628 git_config(git_diff_basic_config, NULL);
630 repo_init_revisions(the_repository, &rev, NULL);
631 rev.abbrev = 0;
632 diff_files_args.nr = setup_revisions(diff_files_args.nr,
633 diff_files_args.v,
634 &rev, NULL);
635 diff_files_result = run_diff_files(&rev, 0);
637 if (!diff_result_code(&rev.diffopt, diff_files_result)) {
638 print_status(flags, ' ', path, ce_oid,
639 displaypath);
640 } else if (!(flags & OPT_CACHED)) {
641 struct object_id oid;
642 struct ref_store *refs = get_submodule_ref_store(path);
644 if (!refs) {
645 print_status(flags, '-', path, ce_oid, displaypath);
646 goto cleanup;
648 if (refs_head_ref(refs, handle_submodule_head_ref, &oid))
649 die(_("could not resolve HEAD ref inside the "
650 "submodule '%s'"), path);
652 print_status(flags, '+', path, &oid, displaypath);
653 } else {
654 print_status(flags, '+', path, ce_oid, displaypath);
657 if (flags & OPT_RECURSIVE) {
658 struct child_process cpr = CHILD_PROCESS_INIT;
660 cpr.git_cmd = 1;
661 cpr.dir = path;
662 prepare_submodule_repo_env(&cpr.env);
664 strvec_push(&cpr.args, "--super-prefix");
665 strvec_pushf(&cpr.args, "%s/", displaypath);
666 strvec_pushl(&cpr.args, "submodule--helper", "status",
667 "--recursive", NULL);
669 if (flags & OPT_CACHED)
670 strvec_push(&cpr.args, "--cached");
672 if (flags & OPT_QUIET)
673 strvec_push(&cpr.args, "--quiet");
675 if (run_command(&cpr))
676 die(_("failed to recurse into submodule '%s'"), path);
679 cleanup:
680 strvec_clear(&diff_files_args);
681 free(displaypath);
682 release_revisions(&rev);
685 static void status_submodule_cb(const struct cache_entry *list_item,
686 void *cb_data)
688 struct status_cb *info = cb_data;
690 status_submodule(list_item->name, &list_item->oid, list_item->ce_flags,
691 info->prefix, info->flags);
694 static int module_status(int argc, const char **argv, const char *prefix)
696 struct status_cb info = STATUS_CB_INIT;
697 struct pathspec pathspec;
698 struct module_list list = MODULE_LIST_INIT;
699 int quiet = 0;
700 struct option module_status_options[] = {
701 OPT__QUIET(&quiet, N_("suppress submodule status output")),
702 OPT_BIT(0, "cached", &info.flags, N_("use commit stored in the index instead of the one stored in the submodule HEAD"), OPT_CACHED),
703 OPT_BIT(0, "recursive", &info.flags, N_("recurse into nested submodules"), OPT_RECURSIVE),
704 OPT_END()
706 const char *const git_submodule_helper_usage[] = {
707 N_("git submodule status [--quiet] [--cached] [--recursive] [<path>...]"),
708 NULL
711 argc = parse_options(argc, argv, prefix, module_status_options,
712 git_submodule_helper_usage, 0);
714 if (module_list_compute(argc, argv, prefix, &pathspec, &list) < 0)
715 return 1;
717 info.prefix = prefix;
718 if (quiet)
719 info.flags |= OPT_QUIET;
721 for_each_listed_submodule(&list, status_submodule_cb, &info);
723 return 0;
726 struct module_cb {
727 unsigned int mod_src;
728 unsigned int mod_dst;
729 struct object_id oid_src;
730 struct object_id oid_dst;
731 char status;
732 const char *sm_path;
734 #define MODULE_CB_INIT { 0 }
736 struct module_cb_list {
737 struct module_cb **entries;
738 int alloc, nr;
740 #define MODULE_CB_LIST_INIT { 0 }
742 struct summary_cb {
743 int argc;
744 const char **argv;
745 const char *prefix;
746 unsigned int cached: 1;
747 unsigned int for_status: 1;
748 unsigned int files: 1;
749 int summary_limit;
751 #define SUMMARY_CB_INIT { 0 }
753 enum diff_cmd {
754 DIFF_INDEX,
755 DIFF_FILES
758 static char *verify_submodule_committish(const char *sm_path,
759 const char *committish)
761 struct child_process cp_rev_parse = CHILD_PROCESS_INIT;
762 struct strbuf result = STRBUF_INIT;
764 cp_rev_parse.git_cmd = 1;
765 cp_rev_parse.dir = sm_path;
766 prepare_submodule_repo_env(&cp_rev_parse.env);
767 strvec_pushl(&cp_rev_parse.args, "rev-parse", "-q", "--short", NULL);
768 strvec_pushf(&cp_rev_parse.args, "%s^0", committish);
769 strvec_push(&cp_rev_parse.args, "--");
771 if (capture_command(&cp_rev_parse, &result, 0))
772 return NULL;
774 strbuf_trim_trailing_newline(&result);
775 return strbuf_detach(&result, NULL);
778 static void print_submodule_summary(struct summary_cb *info, const char *errmsg,
779 int total_commits, const char *displaypath,
780 const char *src_abbrev, const char *dst_abbrev,
781 struct module_cb *p)
783 if (p->status == 'T') {
784 if (S_ISGITLINK(p->mod_dst))
785 printf(_("* %s %s(blob)->%s(submodule)"),
786 displaypath, src_abbrev, dst_abbrev);
787 else
788 printf(_("* %s %s(submodule)->%s(blob)"),
789 displaypath, src_abbrev, dst_abbrev);
790 } else {
791 printf("* %s %s...%s",
792 displaypath, src_abbrev, dst_abbrev);
795 if (total_commits < 0)
796 printf(":\n");
797 else
798 printf(" (%d):\n", total_commits);
800 if (errmsg) {
801 printf(_("%s"), errmsg);
802 } else if (total_commits > 0) {
803 struct child_process cp_log = CHILD_PROCESS_INIT;
805 cp_log.git_cmd = 1;
806 cp_log.dir = p->sm_path;
807 prepare_submodule_repo_env(&cp_log.env);
808 strvec_pushl(&cp_log.args, "log", NULL);
810 if (S_ISGITLINK(p->mod_src) && S_ISGITLINK(p->mod_dst)) {
811 if (info->summary_limit > 0)
812 strvec_pushf(&cp_log.args, "-%d",
813 info->summary_limit);
815 strvec_pushl(&cp_log.args, "--pretty= %m %s",
816 "--first-parent", NULL);
817 strvec_pushf(&cp_log.args, "%s...%s",
818 src_abbrev, dst_abbrev);
819 } else if (S_ISGITLINK(p->mod_dst)) {
820 strvec_pushl(&cp_log.args, "--pretty= > %s",
821 "-1", dst_abbrev, NULL);
822 } else {
823 strvec_pushl(&cp_log.args, "--pretty= < %s",
824 "-1", src_abbrev, NULL);
826 run_command(&cp_log);
828 printf("\n");
831 static void generate_submodule_summary(struct summary_cb *info,
832 struct module_cb *p)
834 char *displaypath, *src_abbrev = NULL, *dst_abbrev;
835 int missing_src = 0, missing_dst = 0;
836 struct strbuf errmsg = STRBUF_INIT;
837 int total_commits = -1;
839 if (!info->cached && oideq(&p->oid_dst, null_oid())) {
840 if (S_ISGITLINK(p->mod_dst)) {
841 struct ref_store *refs = get_submodule_ref_store(p->sm_path);
843 if (refs)
844 refs_head_ref(refs, handle_submodule_head_ref, &p->oid_dst);
845 } else if (S_ISLNK(p->mod_dst) || S_ISREG(p->mod_dst)) {
846 struct stat st;
847 int fd = open(p->sm_path, O_RDONLY);
849 if (fd < 0 || fstat(fd, &st) < 0 ||
850 index_fd(&the_index, &p->oid_dst, fd, &st, OBJ_BLOB,
851 p->sm_path, 0))
852 error(_("couldn't hash object from '%s'"), p->sm_path);
853 } else {
854 /* for a submodule removal (mode:0000000), don't warn */
855 if (p->mod_dst)
856 warning(_("unexpected mode %o\n"), p->mod_dst);
860 if (S_ISGITLINK(p->mod_src)) {
861 if (p->status != 'D')
862 src_abbrev = verify_submodule_committish(p->sm_path,
863 oid_to_hex(&p->oid_src));
864 if (!src_abbrev) {
865 missing_src = 1;
867 * As `rev-parse` failed, we fallback to getting
868 * the abbreviated hash using oid_src. We do
869 * this as we might still need the abbreviated
870 * hash in cases like a submodule type change, etc.
872 src_abbrev = xstrndup(oid_to_hex(&p->oid_src), 7);
874 } else {
876 * The source does not point to a submodule.
877 * So, we fallback to getting the abbreviation using
878 * oid_src as we might still need the abbreviated
879 * hash in cases like submodule add, etc.
881 src_abbrev = xstrndup(oid_to_hex(&p->oid_src), 7);
884 if (S_ISGITLINK(p->mod_dst)) {
885 dst_abbrev = verify_submodule_committish(p->sm_path,
886 oid_to_hex(&p->oid_dst));
887 if (!dst_abbrev) {
888 missing_dst = 1;
890 * As `rev-parse` failed, we fallback to getting
891 * the abbreviated hash using oid_dst. We do
892 * this as we might still need the abbreviated
893 * hash in cases like a submodule type change, etc.
895 dst_abbrev = xstrndup(oid_to_hex(&p->oid_dst), 7);
897 } else {
899 * The destination does not point to a submodule.
900 * So, we fallback to getting the abbreviation using
901 * oid_dst as we might still need the abbreviated
902 * hash in cases like a submodule removal, etc.
904 dst_abbrev = xstrndup(oid_to_hex(&p->oid_dst), 7);
907 displaypath = get_submodule_displaypath(p->sm_path, info->prefix);
909 if (!missing_src && !missing_dst) {
910 struct child_process cp_rev_list = CHILD_PROCESS_INIT;
911 struct strbuf sb_rev_list = STRBUF_INIT;
913 strvec_pushl(&cp_rev_list.args, "rev-list",
914 "--first-parent", "--count", NULL);
915 if (S_ISGITLINK(p->mod_src) && S_ISGITLINK(p->mod_dst))
916 strvec_pushf(&cp_rev_list.args, "%s...%s",
917 src_abbrev, dst_abbrev);
918 else
919 strvec_push(&cp_rev_list.args, S_ISGITLINK(p->mod_src) ?
920 src_abbrev : dst_abbrev);
921 strvec_push(&cp_rev_list.args, "--");
923 cp_rev_list.git_cmd = 1;
924 cp_rev_list.dir = p->sm_path;
925 prepare_submodule_repo_env(&cp_rev_list.env);
927 if (!capture_command(&cp_rev_list, &sb_rev_list, 0))
928 total_commits = atoi(sb_rev_list.buf);
930 strbuf_release(&sb_rev_list);
931 } else {
933 * Don't give error msg for modification whose dst is not
934 * submodule, i.e., deleted or changed to blob
936 if (S_ISGITLINK(p->mod_dst)) {
937 if (missing_src && missing_dst) {
938 strbuf_addf(&errmsg, " Warn: %s doesn't contain commits %s and %s\n",
939 displaypath, oid_to_hex(&p->oid_src),
940 oid_to_hex(&p->oid_dst));
941 } else {
942 strbuf_addf(&errmsg, " Warn: %s doesn't contain commit %s\n",
943 displaypath, missing_src ?
944 oid_to_hex(&p->oid_src) :
945 oid_to_hex(&p->oid_dst));
950 print_submodule_summary(info, errmsg.len ? errmsg.buf : NULL,
951 total_commits, displaypath, src_abbrev,
952 dst_abbrev, p);
954 free(displaypath);
955 free(src_abbrev);
956 free(dst_abbrev);
959 static void prepare_submodule_summary(struct summary_cb *info,
960 struct module_cb_list *list)
962 int i;
963 for (i = 0; i < list->nr; i++) {
964 const struct submodule *sub;
965 struct module_cb *p = list->entries[i];
966 struct strbuf sm_gitdir = STRBUF_INIT;
968 if (p->status == 'D' || p->status == 'T') {
969 generate_submodule_summary(info, p);
970 continue;
973 if (info->for_status && p->status != 'A' &&
974 (sub = submodule_from_path(the_repository,
975 null_oid(), p->sm_path))) {
976 char *config_key = NULL;
977 const char *value;
978 int ignore_all = 0;
980 config_key = xstrfmt("submodule.%s.ignore",
981 sub->name);
982 if (!git_config_get_string_tmp(config_key, &value))
983 ignore_all = !strcmp(value, "all");
984 else if (sub->ignore)
985 ignore_all = !strcmp(sub->ignore, "all");
987 free(config_key);
988 if (ignore_all)
989 continue;
992 /* Also show added or modified modules which are checked out */
993 strbuf_addstr(&sm_gitdir, p->sm_path);
994 if (is_nonbare_repository_dir(&sm_gitdir))
995 generate_submodule_summary(info, p);
996 strbuf_release(&sm_gitdir);
1000 static void submodule_summary_callback(struct diff_queue_struct *q,
1001 struct diff_options *options,
1002 void *data)
1004 int i;
1005 struct module_cb_list *list = data;
1006 for (i = 0; i < q->nr; i++) {
1007 struct diff_filepair *p = q->queue[i];
1008 struct module_cb *temp;
1010 if (!S_ISGITLINK(p->one->mode) && !S_ISGITLINK(p->two->mode))
1011 continue;
1012 temp = (struct module_cb*)malloc(sizeof(struct module_cb));
1013 temp->mod_src = p->one->mode;
1014 temp->mod_dst = p->two->mode;
1015 temp->oid_src = p->one->oid;
1016 temp->oid_dst = p->two->oid;
1017 temp->status = p->status;
1018 temp->sm_path = xstrdup(p->one->path);
1020 ALLOC_GROW(list->entries, list->nr + 1, list->alloc);
1021 list->entries[list->nr++] = temp;
1025 static const char *get_diff_cmd(enum diff_cmd diff_cmd)
1027 switch (diff_cmd) {
1028 case DIFF_INDEX: return "diff-index";
1029 case DIFF_FILES: return "diff-files";
1030 default: BUG("bad diff_cmd value %d", diff_cmd);
1034 static int compute_summary_module_list(struct object_id *head_oid,
1035 struct summary_cb *info,
1036 enum diff_cmd diff_cmd)
1038 struct strvec diff_args = STRVEC_INIT;
1039 struct rev_info rev;
1040 struct setup_revision_opt opt = {
1041 .free_removed_argv_elements = 1,
1043 struct module_cb_list list = MODULE_CB_LIST_INIT;
1044 int ret = 0;
1046 strvec_push(&diff_args, get_diff_cmd(diff_cmd));
1047 if (info->cached)
1048 strvec_push(&diff_args, "--cached");
1049 strvec_pushl(&diff_args, "--ignore-submodules=dirty", "--raw", NULL);
1050 if (head_oid)
1051 strvec_push(&diff_args, oid_to_hex(head_oid));
1052 strvec_push(&diff_args, "--");
1053 if (info->argc)
1054 strvec_pushv(&diff_args, info->argv);
1056 git_config(git_diff_basic_config, NULL);
1057 init_revisions(&rev, info->prefix);
1058 rev.abbrev = 0;
1059 precompose_argv_prefix(diff_args.nr, diff_args.v, NULL);
1060 setup_revisions(diff_args.nr, diff_args.v, &rev, &opt);
1061 rev.diffopt.output_format = DIFF_FORMAT_NO_OUTPUT | DIFF_FORMAT_CALLBACK;
1062 rev.diffopt.format_callback = submodule_summary_callback;
1063 rev.diffopt.format_callback_data = &list;
1065 if (!info->cached) {
1066 if (diff_cmd == DIFF_INDEX)
1067 setup_work_tree();
1068 if (read_cache_preload(&rev.diffopt.pathspec) < 0) {
1069 perror("read_cache_preload");
1070 ret = -1;
1071 goto cleanup;
1073 } else if (read_cache() < 0) {
1074 perror("read_cache");
1075 ret = -1;
1076 goto cleanup;
1079 if (diff_cmd == DIFF_INDEX)
1080 run_diff_index(&rev, info->cached);
1081 else
1082 run_diff_files(&rev, 0);
1083 prepare_submodule_summary(info, &list);
1084 cleanup:
1085 strvec_clear(&diff_args);
1086 release_revisions(&rev);
1087 return ret;
1090 static int module_summary(int argc, const char **argv, const char *prefix)
1092 struct summary_cb info = SUMMARY_CB_INIT;
1093 int cached = 0;
1094 int for_status = 0;
1095 int files = 0;
1096 int summary_limit = -1;
1097 enum diff_cmd diff_cmd = DIFF_INDEX;
1098 struct object_id head_oid;
1099 int ret;
1100 struct option module_summary_options[] = {
1101 OPT_BOOL(0, "cached", &cached,
1102 N_("use the commit stored in the index instead of the submodule HEAD")),
1103 OPT_BOOL(0, "files", &files,
1104 N_("compare the commit in the index with that in the submodule HEAD")),
1105 OPT_BOOL(0, "for-status", &for_status,
1106 N_("skip submodules with 'ignore_config' value set to 'all'")),
1107 OPT_INTEGER('n', "summary-limit", &summary_limit,
1108 N_("limit the summary size")),
1109 OPT_END()
1111 const char *const git_submodule_helper_usage[] = {
1112 N_("git submodule summary [<options>] [<commit>] [--] [<path>]"),
1113 NULL
1116 argc = parse_options(argc, argv, prefix, module_summary_options,
1117 git_submodule_helper_usage, 0);
1119 if (!summary_limit)
1120 return 0;
1122 if (!get_oid(argc ? argv[0] : "HEAD", &head_oid)) {
1123 if (argc) {
1124 argv++;
1125 argc--;
1127 } else if (!argc || !strcmp(argv[0], "HEAD")) {
1128 /* before the first commit: compare with an empty tree */
1129 oidcpy(&head_oid, the_hash_algo->empty_tree);
1130 if (argc) {
1131 argv++;
1132 argc--;
1134 } else {
1135 if (get_oid("HEAD", &head_oid))
1136 die(_("could not fetch a revision for HEAD"));
1139 if (files) {
1140 if (cached)
1141 die(_("options '%s' and '%s' cannot be used together"), "--cached", "--files");
1142 diff_cmd = DIFF_FILES;
1145 info.argc = argc;
1146 info.argv = argv;
1147 info.prefix = prefix;
1148 info.cached = !!cached;
1149 info.files = !!files;
1150 info.for_status = !!for_status;
1151 info.summary_limit = summary_limit;
1153 ret = compute_summary_module_list((diff_cmd == DIFF_INDEX) ? &head_oid : NULL,
1154 &info, diff_cmd);
1155 return ret;
1158 struct sync_cb {
1159 const char *prefix;
1160 unsigned int flags;
1162 #define SYNC_CB_INIT { 0 }
1164 static void sync_submodule(const char *path, const char *prefix,
1165 unsigned int flags)
1167 const struct submodule *sub;
1168 char *remote_key = NULL;
1169 char *sub_origin_url, *super_config_url, *displaypath, *default_remote;
1170 struct strbuf sb = STRBUF_INIT;
1171 char *sub_config_path = NULL;
1172 int code;
1174 if (!is_submodule_active(the_repository, path))
1175 return;
1177 sub = submodule_from_path(the_repository, null_oid(), path);
1179 if (sub && sub->url) {
1180 if (starts_with_dot_dot_slash(sub->url) ||
1181 starts_with_dot_slash(sub->url)) {
1182 char *up_path = get_up_path(path);
1184 sub_origin_url = resolve_relative_url(sub->url, up_path, 1);
1185 super_config_url = resolve_relative_url(sub->url, NULL, 1);
1186 free(up_path);
1187 } else {
1188 sub_origin_url = xstrdup(sub->url);
1189 super_config_url = xstrdup(sub->url);
1191 } else {
1192 sub_origin_url = xstrdup("");
1193 super_config_url = xstrdup("");
1196 displaypath = get_submodule_displaypath(path, prefix);
1198 if (!(flags & OPT_QUIET))
1199 printf(_("Synchronizing submodule url for '%s'\n"),
1200 displaypath);
1202 strbuf_reset(&sb);
1203 strbuf_addf(&sb, "submodule.%s.url", sub->name);
1204 if (git_config_set_gently(sb.buf, super_config_url))
1205 die(_("failed to register url for submodule path '%s'"),
1206 displaypath);
1208 if (!is_submodule_populated_gently(path, NULL))
1209 goto cleanup;
1211 strbuf_reset(&sb);
1212 code = get_default_remote_submodule(path, &default_remote);
1213 if (code)
1214 exit(code);
1216 remote_key = xstrfmt("remote.%s.url", default_remote);
1217 free(default_remote);
1219 submodule_to_gitdir(&sb, path);
1220 strbuf_addstr(&sb, "/config");
1222 if (git_config_set_in_file_gently(sb.buf, remote_key, sub_origin_url))
1223 die(_("failed to update remote for submodule '%s'"),
1224 path);
1226 if (flags & OPT_RECURSIVE) {
1227 struct child_process cpr = CHILD_PROCESS_INIT;
1229 cpr.git_cmd = 1;
1230 cpr.dir = path;
1231 prepare_submodule_repo_env(&cpr.env);
1233 strvec_push(&cpr.args, "--super-prefix");
1234 strvec_pushf(&cpr.args, "%s/", displaypath);
1235 strvec_pushl(&cpr.args, "submodule--helper", "sync",
1236 "--recursive", NULL);
1238 if (flags & OPT_QUIET)
1239 strvec_push(&cpr.args, "--quiet");
1241 if (run_command(&cpr))
1242 die(_("failed to recurse into submodule '%s'"),
1243 path);
1246 cleanup:
1247 free(super_config_url);
1248 free(sub_origin_url);
1249 strbuf_release(&sb);
1250 free(remote_key);
1251 free(displaypath);
1252 free(sub_config_path);
1255 static void sync_submodule_cb(const struct cache_entry *list_item, void *cb_data)
1257 struct sync_cb *info = cb_data;
1259 sync_submodule(list_item->name, info->prefix, info->flags);
1262 static int module_sync(int argc, const char **argv, const char *prefix)
1264 struct sync_cb info = SYNC_CB_INIT;
1265 struct pathspec pathspec;
1266 struct module_list list = MODULE_LIST_INIT;
1267 int quiet = 0;
1268 int recursive = 0;
1269 struct option module_sync_options[] = {
1270 OPT__QUIET(&quiet, N_("suppress output of synchronizing submodule url")),
1271 OPT_BOOL(0, "recursive", &recursive,
1272 N_("recurse into nested submodules")),
1273 OPT_END()
1275 const char *const git_submodule_helper_usage[] = {
1276 N_("git submodule sync [--quiet] [--recursive] [<path>]"),
1277 NULL
1280 argc = parse_options(argc, argv, prefix, module_sync_options,
1281 git_submodule_helper_usage, 0);
1283 if (module_list_compute(argc, argv, prefix, &pathspec, &list) < 0)
1284 return 1;
1286 info.prefix = prefix;
1287 if (quiet)
1288 info.flags |= OPT_QUIET;
1289 if (recursive)
1290 info.flags |= OPT_RECURSIVE;
1292 for_each_listed_submodule(&list, sync_submodule_cb, &info);
1294 return 0;
1297 struct deinit_cb {
1298 const char *prefix;
1299 unsigned int flags;
1301 #define DEINIT_CB_INIT { 0 }
1303 static void deinit_submodule(const char *path, const char *prefix,
1304 unsigned int flags)
1306 const struct submodule *sub;
1307 char *displaypath = NULL;
1308 struct child_process cp_config = CHILD_PROCESS_INIT;
1309 struct strbuf sb_config = STRBUF_INIT;
1310 char *sub_git_dir = xstrfmt("%s/.git", path);
1312 sub = submodule_from_path(the_repository, null_oid(), path);
1314 if (!sub || !sub->name)
1315 goto cleanup;
1317 displaypath = get_submodule_displaypath(path, prefix);
1319 /* remove the submodule work tree (unless the user already did it) */
1320 if (is_directory(path)) {
1321 struct strbuf sb_rm = STRBUF_INIT;
1322 const char *format;
1324 if (is_directory(sub_git_dir)) {
1325 if (!(flags & OPT_QUIET))
1326 warning(_("Submodule work tree '%s' contains a .git "
1327 "directory. This will be replaced with a "
1328 ".git file by using absorbgitdirs."),
1329 displaypath);
1331 absorb_git_dir_into_superproject(path,
1332 ABSORB_GITDIR_RECURSE_SUBMODULES);
1336 if (!(flags & OPT_FORCE)) {
1337 struct child_process cp_rm = CHILD_PROCESS_INIT;
1339 cp_rm.git_cmd = 1;
1340 strvec_pushl(&cp_rm.args, "rm", "-qn",
1341 path, NULL);
1343 if (run_command(&cp_rm))
1344 die(_("Submodule work tree '%s' contains local "
1345 "modifications; use '-f' to discard them"),
1346 displaypath);
1349 strbuf_addstr(&sb_rm, path);
1351 if (!remove_dir_recursively(&sb_rm, 0))
1352 format = _("Cleared directory '%s'\n");
1353 else
1354 format = _("Could not remove submodule work tree '%s'\n");
1356 if (!(flags & OPT_QUIET))
1357 printf(format, displaypath);
1359 submodule_unset_core_worktree(sub);
1361 strbuf_release(&sb_rm);
1364 if (mkdir(path, 0777))
1365 printf(_("could not create empty submodule directory %s"),
1366 displaypath);
1368 cp_config.git_cmd = 1;
1369 strvec_pushl(&cp_config.args, "config", "--get-regexp", NULL);
1370 strvec_pushf(&cp_config.args, "submodule.%s\\.", sub->name);
1372 /* remove the .git/config entries (unless the user already did it) */
1373 if (!capture_command(&cp_config, &sb_config, 0) && sb_config.len) {
1374 char *sub_key = xstrfmt("submodule.%s", sub->name);
1377 * remove the whole section so we have a clean state when
1378 * the user later decides to init this submodule again
1380 git_config_rename_section_in_file(NULL, sub_key, NULL);
1381 if (!(flags & OPT_QUIET))
1382 printf(_("Submodule '%s' (%s) unregistered for path '%s'\n"),
1383 sub->name, sub->url, displaypath);
1384 free(sub_key);
1387 cleanup:
1388 free(displaypath);
1389 free(sub_git_dir);
1390 strbuf_release(&sb_config);
1393 static void deinit_submodule_cb(const struct cache_entry *list_item,
1394 void *cb_data)
1396 struct deinit_cb *info = cb_data;
1397 deinit_submodule(list_item->name, info->prefix, info->flags);
1400 static int module_deinit(int argc, const char **argv, const char *prefix)
1402 struct deinit_cb info = DEINIT_CB_INIT;
1403 struct pathspec pathspec;
1404 struct module_list list = MODULE_LIST_INIT;
1405 int quiet = 0;
1406 int force = 0;
1407 int all = 0;
1408 struct option module_deinit_options[] = {
1409 OPT__QUIET(&quiet, N_("suppress submodule status output")),
1410 OPT__FORCE(&force, N_("remove submodule working trees even if they contain local changes"), 0),
1411 OPT_BOOL(0, "all", &all, N_("unregister all submodules")),
1412 OPT_END()
1414 const char *const git_submodule_helper_usage[] = {
1415 N_("git submodule deinit [--quiet] [-f | --force] [--all | [--] [<path>...]]"),
1416 NULL
1419 argc = parse_options(argc, argv, prefix, module_deinit_options,
1420 git_submodule_helper_usage, 0);
1422 if (all && argc) {
1423 error("pathspec and --all are incompatible");
1424 usage_with_options(git_submodule_helper_usage,
1425 module_deinit_options);
1428 if (!argc && !all)
1429 die(_("Use '--all' if you really want to deinitialize all submodules"));
1431 if (module_list_compute(argc, argv, prefix, &pathspec, &list) < 0)
1432 return 1;
1434 info.prefix = prefix;
1435 if (quiet)
1436 info.flags |= OPT_QUIET;
1437 if (force)
1438 info.flags |= OPT_FORCE;
1440 for_each_listed_submodule(&list, deinit_submodule_cb, &info);
1442 return 0;
1445 struct module_clone_data {
1446 const char *prefix;
1447 const char *path;
1448 const char *name;
1449 const char *url;
1450 const char *depth;
1451 struct list_objects_filter_options *filter_options;
1452 unsigned int quiet: 1;
1453 unsigned int progress: 1;
1454 unsigned int dissociate: 1;
1455 unsigned int require_init: 1;
1456 int single_branch;
1458 #define MODULE_CLONE_DATA_INIT { \
1459 .single_branch = -1, \
1462 struct submodule_alternate_setup {
1463 const char *submodule_name;
1464 enum SUBMODULE_ALTERNATE_ERROR_MODE {
1465 SUBMODULE_ALTERNATE_ERROR_DIE,
1466 SUBMODULE_ALTERNATE_ERROR_INFO,
1467 SUBMODULE_ALTERNATE_ERROR_IGNORE
1468 } error_mode;
1469 struct string_list *reference;
1471 #define SUBMODULE_ALTERNATE_SETUP_INIT { \
1472 .error_mode = SUBMODULE_ALTERNATE_ERROR_IGNORE, \
1475 static const char alternate_error_advice[] = N_(
1476 "An alternate computed from a superproject's alternate is invalid.\n"
1477 "To allow Git to clone without an alternate in such a case, set\n"
1478 "submodule.alternateErrorStrategy to 'info' or, equivalently, clone with\n"
1479 "'--reference-if-able' instead of '--reference'."
1482 static int add_possible_reference_from_superproject(
1483 struct object_directory *odb, void *sas_cb)
1485 struct submodule_alternate_setup *sas = sas_cb;
1486 size_t len;
1489 * If the alternate object store is another repository, try the
1490 * standard layout with .git/(modules/<name>)+/objects
1492 if (strip_suffix(odb->path, "/objects", &len)) {
1493 struct repository alternate;
1494 char *sm_alternate;
1495 struct strbuf sb = STRBUF_INIT;
1496 struct strbuf err = STRBUF_INIT;
1497 strbuf_add(&sb, odb->path, len);
1499 if (repo_init(&alternate, sb.buf, NULL) < 0)
1500 die(_("could not get a repository handle for gitdir '%s'"),
1501 sb.buf);
1504 * We need to end the new path with '/' to mark it as a dir,
1505 * otherwise a submodule name containing '/' will be broken
1506 * as the last part of a missing submodule reference would
1507 * be taken as a file name.
1509 strbuf_reset(&sb);
1510 submodule_name_to_gitdir(&sb, &alternate, sas->submodule_name);
1511 strbuf_addch(&sb, '/');
1512 repo_clear(&alternate);
1514 sm_alternate = compute_alternate_path(sb.buf, &err);
1515 if (sm_alternate) {
1516 string_list_append(sas->reference, xstrdup(sb.buf));
1517 free(sm_alternate);
1518 } else {
1519 switch (sas->error_mode) {
1520 case SUBMODULE_ALTERNATE_ERROR_DIE:
1521 if (advice_enabled(ADVICE_SUBMODULE_ALTERNATE_ERROR_STRATEGY_DIE))
1522 advise(_(alternate_error_advice));
1523 die(_("submodule '%s' cannot add alternate: %s"),
1524 sas->submodule_name, err.buf);
1525 case SUBMODULE_ALTERNATE_ERROR_INFO:
1526 fprintf_ln(stderr, _("submodule '%s' cannot add alternate: %s"),
1527 sas->submodule_name, err.buf);
1528 case SUBMODULE_ALTERNATE_ERROR_IGNORE:
1529 ; /* nothing */
1532 strbuf_release(&sb);
1535 return 0;
1538 static void prepare_possible_alternates(const char *sm_name,
1539 struct string_list *reference)
1541 char *sm_alternate = NULL, *error_strategy = NULL;
1542 struct submodule_alternate_setup sas = SUBMODULE_ALTERNATE_SETUP_INIT;
1544 git_config_get_string("submodule.alternateLocation", &sm_alternate);
1545 if (!sm_alternate)
1546 return;
1548 git_config_get_string("submodule.alternateErrorStrategy", &error_strategy);
1550 if (!error_strategy)
1551 error_strategy = xstrdup("die");
1553 sas.submodule_name = sm_name;
1554 sas.reference = reference;
1555 if (!strcmp(error_strategy, "die"))
1556 sas.error_mode = SUBMODULE_ALTERNATE_ERROR_DIE;
1557 else if (!strcmp(error_strategy, "info"))
1558 sas.error_mode = SUBMODULE_ALTERNATE_ERROR_INFO;
1559 else if (!strcmp(error_strategy, "ignore"))
1560 sas.error_mode = SUBMODULE_ALTERNATE_ERROR_IGNORE;
1561 else
1562 die(_("Value '%s' for submodule.alternateErrorStrategy is not recognized"), error_strategy);
1564 if (!strcmp(sm_alternate, "superproject"))
1565 foreach_alt_odb(add_possible_reference_from_superproject, &sas);
1566 else if (!strcmp(sm_alternate, "no"))
1567 ; /* do nothing */
1568 else
1569 die(_("Value '%s' for submodule.alternateLocation is not recognized"), sm_alternate);
1571 free(sm_alternate);
1572 free(error_strategy);
1575 static char *clone_submodule_sm_gitdir(const char *name)
1577 struct strbuf sb = STRBUF_INIT;
1578 char *sm_gitdir;
1580 submodule_name_to_gitdir(&sb, the_repository, name);
1581 sm_gitdir = absolute_pathdup(sb.buf);
1582 strbuf_release(&sb);
1584 return sm_gitdir;
1587 static int clone_submodule(const struct module_clone_data *clone_data,
1588 struct string_list *reference)
1590 char *p;
1591 char *sm_gitdir = clone_submodule_sm_gitdir(clone_data->name);
1592 char *sm_alternate = NULL, *error_strategy = NULL;
1593 struct child_process cp = CHILD_PROCESS_INIT;
1594 const char *clone_data_path;
1596 if (!is_absolute_path(clone_data->path))
1597 clone_data_path = xstrfmt("%s/%s", get_git_work_tree(),
1598 clone_data->path);
1599 else
1600 clone_data_path = xstrdup(clone_data->path);
1602 if (validate_submodule_git_dir(sm_gitdir, clone_data->name) < 0)
1603 die(_("refusing to create/use '%s' in another submodule's "
1604 "git dir"), sm_gitdir);
1606 if (!file_exists(sm_gitdir)) {
1607 if (safe_create_leading_directories_const(sm_gitdir) < 0)
1608 die(_("could not create directory '%s'"), sm_gitdir);
1610 prepare_possible_alternates(clone_data->name, reference);
1612 strvec_push(&cp.args, "clone");
1613 strvec_push(&cp.args, "--no-checkout");
1614 if (clone_data->quiet)
1615 strvec_push(&cp.args, "--quiet");
1616 if (clone_data->progress)
1617 strvec_push(&cp.args, "--progress");
1618 if (clone_data->depth && *(clone_data->depth))
1619 strvec_pushl(&cp.args, "--depth", clone_data->depth, NULL);
1620 if (reference->nr) {
1621 struct string_list_item *item;
1623 for_each_string_list_item(item, reference)
1624 strvec_pushl(&cp.args, "--reference",
1625 item->string, NULL);
1627 if (clone_data->dissociate)
1628 strvec_push(&cp.args, "--dissociate");
1629 if (sm_gitdir && *sm_gitdir)
1630 strvec_pushl(&cp.args, "--separate-git-dir", sm_gitdir, NULL);
1631 if (clone_data->filter_options && clone_data->filter_options->choice)
1632 strvec_pushf(&cp.args, "--filter=%s",
1633 expand_list_objects_filter_spec(
1634 clone_data->filter_options));
1635 if (clone_data->single_branch >= 0)
1636 strvec_push(&cp.args, clone_data->single_branch ?
1637 "--single-branch" :
1638 "--no-single-branch");
1640 strvec_push(&cp.args, "--");
1641 strvec_push(&cp.args, clone_data->url);
1642 strvec_push(&cp.args, clone_data_path);
1644 cp.git_cmd = 1;
1645 prepare_submodule_repo_env(&cp.env);
1646 cp.no_stdin = 1;
1648 if(run_command(&cp))
1649 die(_("clone of '%s' into submodule path '%s' failed"),
1650 clone_data->url, clone_data_path);
1651 } else {
1652 char *path;
1654 if (clone_data->require_init && !access(clone_data_path, X_OK) &&
1655 !is_empty_dir(clone_data_path))
1656 die(_("directory not empty: '%s'"), clone_data_path);
1657 if (safe_create_leading_directories_const(clone_data_path) < 0)
1658 die(_("could not create directory '%s'"), clone_data_path);
1659 path = xstrfmt("%s/index", sm_gitdir);
1660 unlink_or_warn(path);
1661 free(path);
1664 connect_work_tree_and_git_dir(clone_data_path, sm_gitdir, 0);
1666 p = git_pathdup_submodule(clone_data_path, "config");
1667 if (!p)
1668 die(_("could not get submodule directory for '%s'"), clone_data_path);
1670 /* setup alternateLocation and alternateErrorStrategy in the cloned submodule if needed */
1671 git_config_get_string("submodule.alternateLocation", &sm_alternate);
1672 if (sm_alternate)
1673 git_config_set_in_file(p, "submodule.alternateLocation",
1674 sm_alternate);
1675 git_config_get_string("submodule.alternateErrorStrategy", &error_strategy);
1676 if (error_strategy)
1677 git_config_set_in_file(p, "submodule.alternateErrorStrategy",
1678 error_strategy);
1680 free(sm_alternate);
1681 free(error_strategy);
1683 free(sm_gitdir);
1684 free(p);
1685 return 0;
1688 static int module_clone(int argc, const char **argv, const char *prefix)
1690 int dissociate = 0, quiet = 0, progress = 0, require_init = 0;
1691 struct module_clone_data clone_data = MODULE_CLONE_DATA_INIT;
1692 struct list_objects_filter_options filter_options = { 0 };
1693 struct string_list reference = STRING_LIST_INIT_NODUP;
1694 struct option module_clone_options[] = {
1695 OPT_STRING(0, "prefix", &clone_data.prefix,
1696 N_("path"),
1697 N_("alternative anchor for relative paths")),
1698 OPT_STRING(0, "path", &clone_data.path,
1699 N_("path"),
1700 N_("where the new submodule will be cloned to")),
1701 OPT_STRING(0, "name", &clone_data.name,
1702 N_("string"),
1703 N_("name of the new submodule")),
1704 OPT_STRING(0, "url", &clone_data.url,
1705 N_("string"),
1706 N_("url where to clone the submodule from")),
1707 OPT_STRING_LIST(0, "reference", &reference,
1708 N_("repo"),
1709 N_("reference repository")),
1710 OPT_BOOL(0, "dissociate", &dissociate,
1711 N_("use --reference only while cloning")),
1712 OPT_STRING(0, "depth", &clone_data.depth,
1713 N_("string"),
1714 N_("depth for shallow clones")),
1715 OPT__QUIET(&quiet, "suppress output for cloning a submodule"),
1716 OPT_BOOL(0, "progress", &progress,
1717 N_("force cloning progress")),
1718 OPT_BOOL(0, "require-init", &require_init,
1719 N_("disallow cloning into non-empty directory")),
1720 OPT_BOOL(0, "single-branch", &clone_data.single_branch,
1721 N_("clone only one branch, HEAD or --branch")),
1722 OPT_PARSE_LIST_OBJECTS_FILTER(&filter_options),
1723 OPT_END()
1725 const char *const git_submodule_helper_usage[] = {
1726 N_("git submodule--helper clone [--prefix=<path>] [--quiet] "
1727 "[--reference <repository>] [--name <name>] [--depth <depth>] "
1728 "[--single-branch] [--filter <filter-spec>] "
1729 "--url <url> --path <path>"),
1730 NULL
1733 argc = parse_options(argc, argv, prefix, module_clone_options,
1734 git_submodule_helper_usage, 0);
1736 clone_data.dissociate = !!dissociate;
1737 clone_data.quiet = !!quiet;
1738 clone_data.progress = !!progress;
1739 clone_data.require_init = !!require_init;
1740 clone_data.filter_options = &filter_options;
1742 if (argc || !clone_data.url || !clone_data.path || !*(clone_data.path))
1743 usage_with_options(git_submodule_helper_usage,
1744 module_clone_options);
1746 clone_submodule(&clone_data, &reference);
1747 list_objects_filter_release(&filter_options);
1748 return 0;
1751 static int determine_submodule_update_strategy(struct repository *r,
1752 int just_cloned,
1753 const char *path,
1754 enum submodule_update_type update,
1755 struct submodule_update_strategy *out)
1757 const struct submodule *sub = submodule_from_path(r, null_oid(), path);
1758 char *key;
1759 const char *val;
1760 int ret;
1762 key = xstrfmt("submodule.%s.update", sub->name);
1764 if (update) {
1765 out->type = update;
1766 } else if (!repo_config_get_string_tmp(r, key, &val)) {
1767 if (parse_submodule_update_strategy(val, out) < 0) {
1768 ret = die_message(_("Invalid update mode '%s' configured for submodule path '%s'"),
1769 val, path);
1770 goto cleanup;
1772 } else if (sub->update_strategy.type != SM_UPDATE_UNSPECIFIED) {
1773 if (sub->update_strategy.type == SM_UPDATE_COMMAND)
1774 BUG("how did we read update = !command from .gitmodules?");
1775 out->type = sub->update_strategy.type;
1776 out->command = sub->update_strategy.command;
1777 } else
1778 out->type = SM_UPDATE_CHECKOUT;
1780 if (just_cloned &&
1781 (out->type == SM_UPDATE_MERGE ||
1782 out->type == SM_UPDATE_REBASE ||
1783 out->type == SM_UPDATE_NONE))
1784 out->type = SM_UPDATE_CHECKOUT;
1786 ret = 0;
1787 cleanup:
1788 free(key);
1789 return ret;
1792 struct update_clone_data {
1793 const struct submodule *sub;
1794 struct object_id oid;
1795 unsigned just_cloned;
1798 struct submodule_update_clone {
1799 /* index into 'update_data.list', the list of submodules to look into for cloning */
1800 int current;
1802 /* configuration parameters which are passed on to the children */
1803 const struct update_data *update_data;
1805 /* to be consumed by update_submodule() */
1806 struct update_clone_data *update_clone;
1807 int update_clone_nr; int update_clone_alloc;
1809 /* If we want to stop as fast as possible and return an error */
1810 unsigned quickstop : 1;
1812 /* failed clones to be retried again */
1813 const struct cache_entry **failed_clones;
1814 int failed_clones_nr, failed_clones_alloc;
1816 #define SUBMODULE_UPDATE_CLONE_INIT { 0 }
1818 struct update_data {
1819 const char *prefix;
1820 const char *displaypath;
1821 enum submodule_update_type update_default;
1822 struct object_id suboid;
1823 struct string_list references;
1824 struct submodule_update_strategy update_strategy;
1825 struct list_objects_filter_options *filter_options;
1826 struct module_list list;
1827 int depth;
1828 int max_jobs;
1829 int single_branch;
1830 int recommend_shallow;
1831 unsigned int require_init;
1832 unsigned int force;
1833 unsigned int quiet;
1834 unsigned int nofetch;
1835 unsigned int remote;
1836 unsigned int progress;
1837 unsigned int dissociate;
1838 unsigned int init;
1839 unsigned int warn_if_uninitialized;
1840 unsigned int recursive;
1842 /* copied over from update_clone_data */
1843 struct object_id oid;
1844 unsigned int just_cloned;
1845 const char *sm_path;
1847 #define UPDATE_DATA_INIT { \
1848 .update_strategy = SUBMODULE_UPDATE_STRATEGY_INIT, \
1849 .list = MODULE_LIST_INIT, \
1850 .recommend_shallow = -1, \
1851 .references = STRING_LIST_INIT_DUP, \
1852 .single_branch = -1, \
1853 .max_jobs = 1, \
1856 static void next_submodule_warn_missing(struct submodule_update_clone *suc,
1857 struct strbuf *out, const char *displaypath)
1860 * Only mention uninitialized submodules when their
1861 * paths have been specified.
1863 if (suc->update_data->warn_if_uninitialized) {
1864 strbuf_addf(out,
1865 _("Submodule path '%s' not initialized"),
1866 displaypath);
1867 strbuf_addch(out, '\n');
1868 strbuf_addstr(out,
1869 _("Maybe you want to use 'update --init'?"));
1870 strbuf_addch(out, '\n');
1875 * Determine whether 'ce' needs to be cloned. If so, prepare the 'child' to
1876 * run the clone. Returns 1 if 'ce' needs to be cloned, 0 otherwise.
1878 static int prepare_to_clone_next_submodule(const struct cache_entry *ce,
1879 struct child_process *child,
1880 struct submodule_update_clone *suc,
1881 struct strbuf *out)
1883 const struct submodule *sub = NULL;
1884 const char *url = NULL;
1885 const char *update_string;
1886 enum submodule_update_type update_type;
1887 char *key;
1888 const struct update_data *ud = suc->update_data;
1889 char *displaypath = get_submodule_displaypath(ce->name, ud->prefix);
1890 struct strbuf sb = STRBUF_INIT;
1891 int needs_cloning = 0;
1892 int need_free_url = 0;
1894 if (ce_stage(ce)) {
1895 strbuf_addf(out, _("Skipping unmerged submodule %s"), displaypath);
1896 strbuf_addch(out, '\n');
1897 goto cleanup;
1900 sub = submodule_from_path(the_repository, null_oid(), ce->name);
1902 if (!sub) {
1903 next_submodule_warn_missing(suc, out, displaypath);
1904 goto cleanup;
1907 key = xstrfmt("submodule.%s.update", sub->name);
1908 if (!repo_config_get_string_tmp(the_repository, key, &update_string)) {
1909 update_type = parse_submodule_update_type(update_string);
1910 } else {
1911 update_type = sub->update_strategy.type;
1913 free(key);
1915 if (suc->update_data->update_strategy.type == SM_UPDATE_NONE
1916 || (suc->update_data->update_strategy.type == SM_UPDATE_UNSPECIFIED
1917 && update_type == SM_UPDATE_NONE)) {
1918 strbuf_addf(out, _("Skipping submodule '%s'"), displaypath);
1919 strbuf_addch(out, '\n');
1920 goto cleanup;
1923 /* Check if the submodule has been initialized. */
1924 if (!is_submodule_active(the_repository, ce->name)) {
1925 next_submodule_warn_missing(suc, out, displaypath);
1926 goto cleanup;
1929 strbuf_reset(&sb);
1930 strbuf_addf(&sb, "submodule.%s.url", sub->name);
1931 if (repo_config_get_string_tmp(the_repository, sb.buf, &url)) {
1932 if (starts_with_dot_slash(sub->url) ||
1933 starts_with_dot_dot_slash(sub->url)) {
1934 url = resolve_relative_url(sub->url, NULL, 0);
1935 need_free_url = 1;
1936 } else
1937 url = sub->url;
1940 strbuf_reset(&sb);
1941 strbuf_addf(&sb, "%s/.git", ce->name);
1942 needs_cloning = !file_exists(sb.buf);
1944 ALLOC_GROW(suc->update_clone, suc->update_clone_nr + 1,
1945 suc->update_clone_alloc);
1946 oidcpy(&suc->update_clone[suc->update_clone_nr].oid, &ce->oid);
1947 suc->update_clone[suc->update_clone_nr].just_cloned = needs_cloning;
1948 suc->update_clone[suc->update_clone_nr].sub = sub;
1949 suc->update_clone_nr++;
1951 if (!needs_cloning)
1952 goto cleanup;
1954 child->git_cmd = 1;
1955 child->no_stdin = 1;
1956 child->stdout_to_stderr = 1;
1957 child->err = -1;
1958 strvec_push(&child->args, "submodule--helper");
1959 strvec_push(&child->args, "clone");
1960 if (suc->update_data->progress)
1961 strvec_push(&child->args, "--progress");
1962 if (suc->update_data->quiet)
1963 strvec_push(&child->args, "--quiet");
1964 if (suc->update_data->prefix)
1965 strvec_pushl(&child->args, "--prefix", suc->update_data->prefix, NULL);
1966 if (suc->update_data->recommend_shallow && sub->recommend_shallow == 1)
1967 strvec_push(&child->args, "--depth=1");
1968 else if (suc->update_data->depth)
1969 strvec_pushf(&child->args, "--depth=%d", suc->update_data->depth);
1970 if (suc->update_data->filter_options && suc->update_data->filter_options->choice)
1971 strvec_pushf(&child->args, "--filter=%s",
1972 expand_list_objects_filter_spec(suc->update_data->filter_options));
1973 if (suc->update_data->require_init)
1974 strvec_push(&child->args, "--require-init");
1975 strvec_pushl(&child->args, "--path", sub->path, NULL);
1976 strvec_pushl(&child->args, "--name", sub->name, NULL);
1977 strvec_pushl(&child->args, "--url", url, NULL);
1978 if (suc->update_data->references.nr) {
1979 struct string_list_item *item;
1981 for_each_string_list_item(item, &suc->update_data->references)
1982 strvec_pushl(&child->args, "--reference", item->string, NULL);
1984 if (suc->update_data->dissociate)
1985 strvec_push(&child->args, "--dissociate");
1986 if (suc->update_data->single_branch >= 0)
1987 strvec_push(&child->args, suc->update_data->single_branch ?
1988 "--single-branch" :
1989 "--no-single-branch");
1991 cleanup:
1992 free(displaypath);
1993 strbuf_release(&sb);
1994 if (need_free_url)
1995 free((void*)url);
1997 return needs_cloning;
2000 static int update_clone_get_next_task(struct child_process *child,
2001 struct strbuf *err,
2002 void *suc_cb,
2003 void **idx_task_cb)
2005 struct submodule_update_clone *suc = suc_cb;
2006 const struct cache_entry *ce;
2007 int index;
2009 for (; suc->current < suc->update_data->list.nr; suc->current++) {
2010 ce = suc->update_data->list.entries[suc->current];
2011 if (prepare_to_clone_next_submodule(ce, child, suc, err)) {
2012 int *p = xmalloc(sizeof(*p));
2014 *p = suc->current;
2015 *idx_task_cb = p;
2016 suc->current++;
2017 return 1;
2022 * The loop above tried cloning each submodule once, now try the
2023 * stragglers again, which we can imagine as an extension of the
2024 * entry list.
2026 index = suc->current - suc->update_data->list.nr;
2027 if (index < suc->failed_clones_nr) {
2028 int *p;
2030 ce = suc->failed_clones[index];
2031 if (!prepare_to_clone_next_submodule(ce, child, suc, err)) {
2032 suc->current ++;
2033 strbuf_addstr(err, "BUG: submodule considered for "
2034 "cloning, doesn't need cloning "
2035 "any more?\n");
2036 return 0;
2038 p = xmalloc(sizeof(*p));
2039 *p = suc->current;
2040 *idx_task_cb = p;
2041 suc->current ++;
2042 return 1;
2045 return 0;
2048 static int update_clone_start_failure(struct strbuf *err,
2049 void *suc_cb,
2050 void *idx_task_cb)
2052 struct submodule_update_clone *suc = suc_cb;
2054 suc->quickstop = 1;
2055 return 1;
2058 static int update_clone_task_finished(int result,
2059 struct strbuf *err,
2060 void *suc_cb,
2061 void *idx_task_cb)
2063 const struct cache_entry *ce;
2064 struct submodule_update_clone *suc = suc_cb;
2065 int *idxP = idx_task_cb;
2066 int idx = *idxP;
2068 free(idxP);
2070 if (!result)
2071 return 0;
2073 if (idx < suc->update_data->list.nr) {
2074 ce = suc->update_data->list.entries[idx];
2075 strbuf_addf(err, _("Failed to clone '%s'. Retry scheduled"),
2076 ce->name);
2077 strbuf_addch(err, '\n');
2078 ALLOC_GROW(suc->failed_clones,
2079 suc->failed_clones_nr + 1,
2080 suc->failed_clones_alloc);
2081 suc->failed_clones[suc->failed_clones_nr++] = ce;
2082 return 0;
2083 } else {
2084 idx -= suc->update_data->list.nr;
2085 ce = suc->failed_clones[idx];
2086 strbuf_addf(err, _("Failed to clone '%s' a second time, aborting"),
2087 ce->name);
2088 strbuf_addch(err, '\n');
2089 suc->quickstop = 1;
2090 return 1;
2093 return 0;
2096 static int git_update_clone_config(const char *var, const char *value,
2097 void *cb)
2099 int *max_jobs = cb;
2101 if (!strcmp(var, "submodule.fetchjobs"))
2102 *max_jobs = parse_submodule_fetchjobs(var, value);
2103 return 0;
2106 static int is_tip_reachable(const char *path, const struct object_id *oid)
2108 struct child_process cp = CHILD_PROCESS_INIT;
2109 struct strbuf rev = STRBUF_INIT;
2110 char *hex = oid_to_hex(oid);
2112 cp.git_cmd = 1;
2113 cp.dir = xstrdup(path);
2114 cp.no_stderr = 1;
2115 strvec_pushl(&cp.args, "rev-list", "-n", "1", hex, "--not", "--all", NULL);
2117 prepare_submodule_repo_env(&cp.env);
2119 if (capture_command(&cp, &rev, GIT_MAX_HEXSZ + 1) || rev.len)
2120 return 0;
2122 return 1;
2125 static int fetch_in_submodule(const char *module_path, int depth, int quiet,
2126 const struct object_id *oid)
2128 struct child_process cp = CHILD_PROCESS_INIT;
2130 prepare_submodule_repo_env(&cp.env);
2131 cp.git_cmd = 1;
2132 cp.dir = xstrdup(module_path);
2134 strvec_push(&cp.args, "fetch");
2135 if (quiet)
2136 strvec_push(&cp.args, "--quiet");
2137 if (depth)
2138 strvec_pushf(&cp.args, "--depth=%d", depth);
2139 if (oid) {
2140 char *hex = oid_to_hex(oid);
2141 char *remote = get_default_remote();
2143 strvec_pushl(&cp.args, remote, hex, NULL);
2144 free(remote);
2147 return run_command(&cp);
2150 static int run_update_command(const struct update_data *ud, int subforce)
2152 struct child_process cp = CHILD_PROCESS_INIT;
2153 char *oid = oid_to_hex(&ud->oid);
2154 int ret;
2156 switch (ud->update_strategy.type) {
2157 case SM_UPDATE_CHECKOUT:
2158 cp.git_cmd = 1;
2159 strvec_pushl(&cp.args, "checkout", "-q", NULL);
2160 if (subforce)
2161 strvec_push(&cp.args, "-f");
2162 break;
2163 case SM_UPDATE_REBASE:
2164 cp.git_cmd = 1;
2165 strvec_push(&cp.args, "rebase");
2166 if (ud->quiet)
2167 strvec_push(&cp.args, "--quiet");
2168 break;
2169 case SM_UPDATE_MERGE:
2170 cp.git_cmd = 1;
2171 strvec_push(&cp.args, "merge");
2172 if (ud->quiet)
2173 strvec_push(&cp.args, "--quiet");
2174 break;
2175 case SM_UPDATE_COMMAND:
2176 cp.use_shell = 1;
2177 strvec_push(&cp.args, ud->update_strategy.command);
2178 break;
2179 default:
2180 BUG("unexpected update strategy type: %d",
2181 ud->update_strategy.type);
2183 strvec_push(&cp.args, oid);
2185 cp.dir = xstrdup(ud->sm_path);
2186 prepare_submodule_repo_env(&cp.env);
2187 if ((ret = run_command(&cp))) {
2188 switch (ud->update_strategy.type) {
2189 case SM_UPDATE_CHECKOUT:
2190 die_message(_("Unable to checkout '%s' in submodule path '%s'"),
2191 oid, ud->displaypath);
2192 /* No "ret" assignment, use "git checkout"'s */
2193 break;
2194 case SM_UPDATE_REBASE:
2195 ret = die_message(_("Unable to rebase '%s' in submodule path '%s'"),
2196 oid, ud->displaypath);
2197 break;
2198 case SM_UPDATE_MERGE:
2199 ret = die_message(_("Unable to merge '%s' in submodule path '%s'"),
2200 oid, ud->displaypath);
2201 break;
2202 case SM_UPDATE_COMMAND:
2203 ret = die_message(_("Execution of '%s %s' failed in submodule path '%s'"),
2204 ud->update_strategy.command, oid, ud->displaypath);
2205 break;
2206 default:
2207 BUG("unexpected update strategy type: %d",
2208 ud->update_strategy.type);
2211 return ret;
2214 if (ud->quiet)
2215 return 0;
2217 switch (ud->update_strategy.type) {
2218 case SM_UPDATE_CHECKOUT:
2219 printf(_("Submodule path '%s': checked out '%s'\n"),
2220 ud->displaypath, oid);
2221 break;
2222 case SM_UPDATE_REBASE:
2223 printf(_("Submodule path '%s': rebased into '%s'\n"),
2224 ud->displaypath, oid);
2225 break;
2226 case SM_UPDATE_MERGE:
2227 printf(_("Submodule path '%s': merged in '%s'\n"),
2228 ud->displaypath, oid);
2229 break;
2230 case SM_UPDATE_COMMAND:
2231 printf(_("Submodule path '%s': '%s %s'\n"),
2232 ud->displaypath, ud->update_strategy.command, oid);
2233 break;
2234 default:
2235 BUG("unexpected update strategy type: %d",
2236 ud->update_strategy.type);
2239 return 0;
2242 static int run_update_procedure(const struct update_data *ud)
2244 int subforce = is_null_oid(&ud->suboid) || ud->force;
2246 if (!ud->nofetch) {
2248 * Run fetch only if `oid` isn't present or it
2249 * is not reachable from a ref.
2251 if (!is_tip_reachable(ud->sm_path, &ud->oid) &&
2252 fetch_in_submodule(ud->sm_path, ud->depth, ud->quiet, NULL) &&
2253 !ud->quiet)
2254 fprintf_ln(stderr,
2255 _("Unable to fetch in submodule path '%s'; "
2256 "trying to directly fetch %s:"),
2257 ud->displaypath, oid_to_hex(&ud->oid));
2259 * Now we tried the usual fetch, but `oid` may
2260 * not be reachable from any of the refs.
2262 if (!is_tip_reachable(ud->sm_path, &ud->oid) &&
2263 fetch_in_submodule(ud->sm_path, ud->depth, ud->quiet, &ud->oid))
2264 return die_message(_("Fetched in submodule path '%s', but it did not "
2265 "contain %s. Direct fetching of that commit failed."),
2266 ud->displaypath, oid_to_hex(&ud->oid));
2269 return run_update_command(ud, subforce);
2272 static int remote_submodule_branch(const char *path, const char **branch)
2274 const struct submodule *sub;
2275 char *key;
2276 *branch = NULL;
2278 sub = submodule_from_path(the_repository, null_oid(), path);
2279 if (!sub)
2280 return die_message(_("could not initialize submodule at path '%s'"),
2281 path);
2283 key = xstrfmt("submodule.%s.branch", sub->name);
2284 if (repo_config_get_string_tmp(the_repository, key, branch))
2285 *branch = sub->branch;
2286 free(key);
2288 if (!*branch) {
2289 *branch = "HEAD";
2290 return 0;
2293 if (!strcmp(*branch, ".")) {
2294 const char *refname = resolve_ref_unsafe("HEAD", 0, NULL, NULL);
2296 if (!refname)
2297 return die_message(_("No such ref: %s"), "HEAD");
2299 /* detached HEAD */
2300 if (!strcmp(refname, "HEAD"))
2301 return die_message(_("Submodule (%s) branch configured to inherit "
2302 "branch from superproject, but the superproject "
2303 "is not on any branch"), sub->name);
2305 if (!skip_prefix(refname, "refs/heads/", &refname))
2306 return die_message(_("Expecting a full ref name, got %s"),
2307 refname);
2309 *branch = refname;
2310 return 0;
2313 /* Our "branch" is coming from repo_config_get_string_tmp() */
2314 return 0;
2317 static int ensure_core_worktree(const char *path)
2319 const char *cw;
2320 struct repository subrepo;
2322 if (repo_submodule_init(&subrepo, the_repository, path, null_oid()))
2323 return die_message(_("could not get a repository handle for submodule '%s'"),
2324 path);
2326 if (!repo_config_get_string_tmp(&subrepo, "core.worktree", &cw)) {
2327 char *cfg_file, *abs_path;
2328 const char *rel_path;
2329 struct strbuf sb = STRBUF_INIT;
2331 cfg_file = repo_git_path(&subrepo, "config");
2333 abs_path = absolute_pathdup(path);
2334 rel_path = relative_path(abs_path, subrepo.gitdir, &sb);
2336 git_config_set_in_file(cfg_file, "core.worktree", rel_path);
2338 free(cfg_file);
2339 free(abs_path);
2340 strbuf_release(&sb);
2343 return 0;
2346 static const char *submodule_update_type_to_label(enum submodule_update_type type)
2348 switch (type) {
2349 case SM_UPDATE_CHECKOUT:
2350 return "checkout";
2351 case SM_UPDATE_MERGE:
2352 return "merge";
2353 case SM_UPDATE_REBASE:
2354 return "rebase";
2355 case SM_UPDATE_UNSPECIFIED:
2356 case SM_UPDATE_NONE:
2357 case SM_UPDATE_COMMAND:
2358 break;
2360 BUG("unreachable with type %d", type);
2363 static void update_data_to_args(const struct update_data *update_data,
2364 struct strvec *args)
2366 enum submodule_update_type update_type = update_data->update_default;
2368 if (update_data->displaypath) {
2369 strvec_push(args, "--super-prefix");
2370 strvec_pushf(args, "%s/", update_data->displaypath);
2372 strvec_pushl(args, "submodule--helper", "update", "--recursive", NULL);
2373 strvec_pushf(args, "--jobs=%d", update_data->max_jobs);
2374 if (update_data->quiet)
2375 strvec_push(args, "--quiet");
2376 if (update_data->force)
2377 strvec_push(args, "--force");
2378 if (update_data->init)
2379 strvec_push(args, "--init");
2380 if (update_data->remote)
2381 strvec_push(args, "--remote");
2382 if (update_data->nofetch)
2383 strvec_push(args, "--no-fetch");
2384 if (update_data->dissociate)
2385 strvec_push(args, "--dissociate");
2386 if (update_data->progress)
2387 strvec_push(args, "--progress");
2388 if (update_data->require_init)
2389 strvec_push(args, "--require-init");
2390 if (update_data->depth)
2391 strvec_pushf(args, "--depth=%d", update_data->depth);
2392 if (update_type != SM_UPDATE_UNSPECIFIED)
2393 strvec_pushf(args, "--%s",
2394 submodule_update_type_to_label(update_type));
2396 if (update_data->references.nr) {
2397 struct string_list_item *item;
2399 for_each_string_list_item(item, &update_data->references)
2400 strvec_pushl(args, "--reference", item->string, NULL);
2402 if (update_data->filter_options && update_data->filter_options->choice)
2403 strvec_pushf(args, "--filter=%s",
2404 expand_list_objects_filter_spec(
2405 update_data->filter_options));
2406 if (update_data->recommend_shallow == 0)
2407 strvec_push(args, "--no-recommend-shallow");
2408 else if (update_data->recommend_shallow == 1)
2409 strvec_push(args, "--recommend-shallow");
2410 if (update_data->single_branch >= 0)
2411 strvec_push(args, update_data->single_branch ?
2412 "--single-branch" :
2413 "--no-single-branch");
2416 static int update_submodule(struct update_data *update_data)
2418 int ret;
2420 ret = ensure_core_worktree(update_data->sm_path);
2421 if (ret)
2422 return ret;
2424 update_data->displaypath = get_submodule_displaypath(
2425 update_data->sm_path, update_data->prefix);
2427 ret = determine_submodule_update_strategy(the_repository,
2428 update_data->just_cloned,
2429 update_data->sm_path,
2430 update_data->update_default,
2431 &update_data->update_strategy);
2432 if (ret)
2433 return ret;
2435 if (update_data->just_cloned)
2436 oidcpy(&update_data->suboid, null_oid());
2437 else if (resolve_gitlink_ref(update_data->sm_path, "HEAD", &update_data->suboid))
2438 return die_message(_("Unable to find current revision in submodule path '%s'"),
2439 update_data->displaypath);
2441 if (update_data->remote) {
2442 char *remote_name;
2443 const char *branch;
2444 char *remote_ref;
2445 int code;
2447 code = get_default_remote_submodule(update_data->sm_path, &remote_name);
2448 if (code)
2449 return code;
2450 code = remote_submodule_branch(update_data->sm_path, &branch);
2451 if (code)
2452 return code;
2453 remote_ref = xstrfmt("refs/remotes/%s/%s", remote_name, branch);
2455 if (!update_data->nofetch) {
2456 if (fetch_in_submodule(update_data->sm_path, update_data->depth,
2457 0, NULL))
2458 return die_message(_("Unable to fetch in submodule path '%s'"),
2459 update_data->sm_path);
2462 if (resolve_gitlink_ref(update_data->sm_path, remote_ref, &update_data->oid))
2463 return die_message(_("Unable to find %s revision in submodule path '%s'"),
2464 remote_ref, update_data->sm_path);
2466 free(remote_ref);
2469 if (!oideq(&update_data->oid, &update_data->suboid) || update_data->force) {
2470 ret = run_update_procedure(update_data);
2471 if (ret)
2472 return ret;
2475 if (update_data->recursive) {
2476 struct child_process cp = CHILD_PROCESS_INIT;
2477 struct update_data next = *update_data;
2479 next.prefix = NULL;
2480 oidcpy(&next.oid, null_oid());
2481 oidcpy(&next.suboid, null_oid());
2483 cp.dir = update_data->sm_path;
2484 cp.git_cmd = 1;
2485 prepare_submodule_repo_env(&cp.env);
2486 update_data_to_args(&next, &cp.args);
2488 ret = run_command(&cp);
2489 if (ret)
2490 die_message(_("Failed to recurse into submodule path '%s'"),
2491 update_data->displaypath);
2492 return ret;
2495 return 0;
2498 static int update_submodules(struct update_data *update_data)
2500 int i, ret = 0;
2501 struct submodule_update_clone suc = SUBMODULE_UPDATE_CLONE_INIT;
2503 suc.update_data = update_data;
2504 run_processes_parallel_tr2(suc.update_data->max_jobs, update_clone_get_next_task,
2505 update_clone_start_failure,
2506 update_clone_task_finished, &suc, "submodule",
2507 "parallel/update");
2510 * We saved the output and put it out all at once now.
2511 * That means:
2512 * - the listener does not have to interleave their (checkout)
2513 * work with our fetching. The writes involved in a
2514 * checkout involve more straightforward sequential I/O.
2515 * - the listener can avoid doing any work if fetching failed.
2517 if (suc.quickstop) {
2518 ret = 1;
2519 goto cleanup;
2522 for (i = 0; i < suc.update_clone_nr; i++) {
2523 struct update_clone_data ucd = suc.update_clone[i];
2524 int code;
2526 oidcpy(&update_data->oid, &ucd.oid);
2527 update_data->just_cloned = ucd.just_cloned;
2528 update_data->sm_path = ucd.sub->path;
2530 code = update_submodule(update_data);
2531 if (!code)
2532 continue;
2533 ret = code;
2534 if (ret == 128)
2535 goto cleanup;
2538 cleanup:
2539 string_list_clear(&update_data->references, 0);
2540 return ret;
2543 static int module_update(int argc, const char **argv, const char *prefix)
2545 struct pathspec pathspec;
2546 struct update_data opt = UPDATE_DATA_INIT;
2547 struct list_objects_filter_options filter_options = { 0 };
2548 int ret;
2549 struct option module_update_options[] = {
2550 OPT__FORCE(&opt.force, N_("force checkout updates"), 0),
2551 OPT_BOOL(0, "init", &opt.init,
2552 N_("initialize uninitialized submodules before update")),
2553 OPT_BOOL(0, "remote", &opt.remote,
2554 N_("use SHA-1 of submodule's remote tracking branch")),
2555 OPT_BOOL(0, "recursive", &opt.recursive,
2556 N_("traverse submodules recursively")),
2557 OPT_BOOL('N', "no-fetch", &opt.nofetch,
2558 N_("don't fetch new objects from the remote site")),
2559 OPT_STRING(0, "prefix", &opt.prefix,
2560 N_("path"),
2561 N_("path into the working tree")),
2562 OPT_SET_INT(0, "checkout", &opt.update_default,
2563 N_("use the 'checkout' update strategy (default)"),
2564 SM_UPDATE_CHECKOUT),
2565 OPT_SET_INT('m', "merge", &opt.update_default,
2566 N_("use the 'merge' update strategy"),
2567 SM_UPDATE_MERGE),
2568 OPT_SET_INT('r', "rebase", &opt.update_default,
2569 N_("use the 'rebase' update strategy"),
2570 SM_UPDATE_REBASE),
2571 OPT_STRING_LIST(0, "reference", &opt.references, N_("repo"),
2572 N_("reference repository")),
2573 OPT_BOOL(0, "dissociate", &opt.dissociate,
2574 N_("use --reference only while cloning")),
2575 OPT_INTEGER(0, "depth", &opt.depth,
2576 N_("create a shallow clone truncated to the "
2577 "specified number of revisions")),
2578 OPT_INTEGER('j', "jobs", &opt.max_jobs,
2579 N_("parallel jobs")),
2580 OPT_BOOL(0, "recommend-shallow", &opt.recommend_shallow,
2581 N_("whether the initial clone should follow the shallow recommendation")),
2582 OPT__QUIET(&opt.quiet, N_("don't print cloning progress")),
2583 OPT_BOOL(0, "progress", &opt.progress,
2584 N_("force cloning progress")),
2585 OPT_BOOL(0, "require-init", &opt.require_init,
2586 N_("disallow cloning into non-empty directory, implies --init")),
2587 OPT_BOOL(0, "single-branch", &opt.single_branch,
2588 N_("clone only one branch, HEAD or --branch")),
2589 OPT_PARSE_LIST_OBJECTS_FILTER(&filter_options),
2590 OPT_END()
2592 const char *const git_submodule_helper_usage[] = {
2593 N_("git submodule [--quiet] update"
2594 " [--init [--filter=<filter-spec>]] [--remote]"
2595 " [-N|--no-fetch] [-f|--force]"
2596 " [--checkout|--merge|--rebase]"
2597 " [--[no-]recommend-shallow] [--reference <repository>]"
2598 " [--recursive] [--[no-]single-branch] [--] [<path>...]"),
2599 NULL
2602 update_clone_config_from_gitmodules(&opt.max_jobs);
2603 git_config(git_update_clone_config, &opt.max_jobs);
2605 argc = parse_options(argc, argv, prefix, module_update_options,
2606 git_submodule_helper_usage, 0);
2608 if (opt.require_init)
2609 opt.init = 1;
2611 if (filter_options.choice && !opt.init) {
2612 usage_with_options(git_submodule_helper_usage,
2613 module_update_options);
2616 opt.filter_options = &filter_options;
2618 if (opt.update_default)
2619 opt.update_strategy.type = opt.update_default;
2621 if (module_list_compute(argc, argv, prefix, &pathspec, &opt.list) < 0) {
2622 list_objects_filter_release(&filter_options);
2623 return 1;
2626 if (pathspec.nr)
2627 opt.warn_if_uninitialized = 1;
2629 if (opt.init) {
2630 struct module_list list = MODULE_LIST_INIT;
2631 struct init_cb info = INIT_CB_INIT;
2633 if (module_list_compute(argc, argv, opt.prefix,
2634 &pathspec, &list) < 0)
2635 return 1;
2638 * If there are no path args and submodule.active is set then,
2639 * by default, only initialize 'active' modules.
2641 if (!argc && git_config_get_value_multi("submodule.active"))
2642 module_list_active(&list);
2644 info.prefix = opt.prefix;
2645 if (opt.quiet)
2646 info.flags |= OPT_QUIET;
2648 for_each_listed_submodule(&list, init_submodule_cb, &info);
2651 ret = update_submodules(&opt);
2652 list_objects_filter_release(&filter_options);
2653 return ret;
2656 static int push_check(int argc, const char **argv, const char *prefix)
2658 struct remote *remote;
2659 const char *superproject_head;
2660 char *head;
2661 int detached_head = 0;
2662 struct object_id head_oid;
2664 if (argc < 3)
2665 die("submodule--helper push-check requires at least 2 arguments");
2668 * superproject's resolved head ref.
2669 * if HEAD then the superproject is in a detached head state, otherwise
2670 * it will be the resolved head ref.
2672 superproject_head = argv[1];
2673 argv++;
2674 argc--;
2675 /* Get the submodule's head ref and determine if it is detached */
2676 head = resolve_refdup("HEAD", 0, &head_oid, NULL);
2677 if (!head)
2678 die(_("Failed to resolve HEAD as a valid ref."));
2679 if (!strcmp(head, "HEAD"))
2680 detached_head = 1;
2683 * The remote must be configured.
2684 * This is to avoid pushing to the exact same URL as the parent.
2686 remote = pushremote_get(argv[1]);
2687 if (!remote || remote->origin == REMOTE_UNCONFIGURED)
2688 die("remote '%s' not configured", argv[1]);
2690 /* Check the refspec */
2691 if (argc > 2) {
2692 int i;
2693 struct ref *local_refs = get_local_heads();
2694 struct refspec refspec = REFSPEC_INIT_PUSH;
2696 refspec_appendn(&refspec, argv + 2, argc - 2);
2698 for (i = 0; i < refspec.nr; i++) {
2699 const struct refspec_item *rs = &refspec.items[i];
2701 if (rs->pattern || rs->matching)
2702 continue;
2704 /* LHS must match a single ref */
2705 switch (count_refspec_match(rs->src, local_refs, NULL)) {
2706 case 1:
2707 break;
2708 case 0:
2710 * If LHS matches 'HEAD' then we need to ensure
2711 * that it matches the same named branch
2712 * checked out in the superproject.
2714 if (!strcmp(rs->src, "HEAD")) {
2715 if (!detached_head &&
2716 !strcmp(head, superproject_head))
2717 break;
2718 die("HEAD does not match the named branch in the superproject");
2720 /* fallthrough */
2721 default:
2722 die("src refspec '%s' must name a ref",
2723 rs->src);
2726 refspec_clear(&refspec);
2728 free(head);
2730 return 0;
2733 static int absorb_git_dirs(int argc, const char **argv, const char *prefix)
2735 int i;
2736 struct pathspec pathspec;
2737 struct module_list list = MODULE_LIST_INIT;
2738 unsigned flags = ABSORB_GITDIR_RECURSE_SUBMODULES;
2739 struct option embed_gitdir_options[] = {
2740 OPT_STRING(0, "prefix", &prefix,
2741 N_("path"),
2742 N_("path into the working tree")),
2743 OPT_BIT(0, "--recursive", &flags, N_("recurse into submodules"),
2744 ABSORB_GITDIR_RECURSE_SUBMODULES),
2745 OPT_END()
2747 const char *const git_submodule_helper_usage[] = {
2748 N_("git submodule absorbgitdirs [<options>] [<path>...]"),
2749 NULL
2752 argc = parse_options(argc, argv, prefix, embed_gitdir_options,
2753 git_submodule_helper_usage, 0);
2755 if (module_list_compute(argc, argv, prefix, &pathspec, &list) < 0)
2756 return 1;
2758 for (i = 0; i < list.nr; i++)
2759 absorb_git_dir_into_superproject(list.entries[i]->name, flags);
2761 return 0;
2764 static int module_config(int argc, const char **argv, const char *prefix)
2766 enum {
2767 CHECK_WRITEABLE = 1,
2768 DO_UNSET = 2
2769 } command = 0;
2770 struct option module_config_options[] = {
2771 OPT_CMDMODE(0, "check-writeable", &command,
2772 N_("check if it is safe to write to the .gitmodules file"),
2773 CHECK_WRITEABLE),
2774 OPT_CMDMODE(0, "unset", &command,
2775 N_("unset the config in the .gitmodules file"),
2776 DO_UNSET),
2777 OPT_END()
2779 const char *const git_submodule_helper_usage[] = {
2780 N_("git submodule--helper config <name> [<value>]"),
2781 N_("git submodule--helper config --unset <name>"),
2782 "git submodule--helper config --check-writeable",
2783 NULL
2786 argc = parse_options(argc, argv, prefix, module_config_options,
2787 git_submodule_helper_usage, PARSE_OPT_KEEP_ARGV0);
2789 if (argc == 1 && command == CHECK_WRITEABLE)
2790 return is_writing_gitmodules_ok() ? 0 : -1;
2792 /* Equivalent to ACTION_GET in builtin/config.c */
2793 if (argc == 2 && command != DO_UNSET)
2794 return print_config_from_gitmodules(the_repository, argv[1]);
2796 /* Equivalent to ACTION_SET in builtin/config.c */
2797 if (argc == 3 || (argc == 2 && command == DO_UNSET)) {
2798 const char *value = (argc == 3) ? argv[2] : NULL;
2800 if (!is_writing_gitmodules_ok())
2801 die(_("please make sure that the .gitmodules file is in the working tree"));
2803 return config_set_in_gitmodules_file_gently(argv[1], value);
2806 usage_with_options(git_submodule_helper_usage, module_config_options);
2809 static int module_set_url(int argc, const char **argv, const char *prefix)
2811 int quiet = 0;
2812 const char *newurl;
2813 const char *path;
2814 char *config_name;
2815 struct option options[] = {
2816 OPT__QUIET(&quiet, N_("suppress output for setting url of a submodule")),
2817 OPT_END()
2819 const char *const usage[] = {
2820 N_("git submodule set-url [--quiet] <path> <newurl>"),
2821 NULL
2824 argc = parse_options(argc, argv, prefix, options, usage, 0);
2826 if (argc != 2 || !(path = argv[0]) || !(newurl = argv[1]))
2827 usage_with_options(usage, options);
2829 config_name = xstrfmt("submodule.%s.url", path);
2831 config_set_in_gitmodules_file_gently(config_name, newurl);
2832 sync_submodule(path, prefix, quiet ? OPT_QUIET : 0);
2834 free(config_name);
2836 return 0;
2839 static int module_set_branch(int argc, const char **argv, const char *prefix)
2841 int opt_default = 0, ret;
2842 const char *opt_branch = NULL;
2843 const char *path;
2844 char *config_name;
2845 struct option options[] = {
2847 * We accept the `quiet` option for uniformity across subcommands,
2848 * though there is nothing to make less verbose in this subcommand.
2850 OPT_NOOP_NOARG('q', "quiet"),
2852 OPT_BOOL('d', "default", &opt_default,
2853 N_("set the default tracking branch to master")),
2854 OPT_STRING('b', "branch", &opt_branch, N_("branch"),
2855 N_("set the default tracking branch")),
2856 OPT_END()
2858 const char *const usage[] = {
2859 N_("git submodule set-branch [-q|--quiet] (-d|--default) <path>"),
2860 N_("git submodule set-branch [-q|--quiet] (-b|--branch) <branch> <path>"),
2861 NULL
2864 argc = parse_options(argc, argv, prefix, options, usage, 0);
2866 if (!opt_branch && !opt_default)
2867 die(_("--branch or --default required"));
2869 if (opt_branch && opt_default)
2870 die(_("options '%s' and '%s' cannot be used together"), "--branch", "--default");
2872 if (argc != 1 || !(path = argv[0]))
2873 usage_with_options(usage, options);
2875 config_name = xstrfmt("submodule.%s.branch", path);
2876 ret = config_set_in_gitmodules_file_gently(config_name, opt_branch);
2878 free(config_name);
2879 return !!ret;
2882 static int module_create_branch(int argc, const char **argv, const char *prefix)
2884 enum branch_track track;
2885 int quiet = 0, force = 0, reflog = 0, dry_run = 0;
2886 struct option options[] = {
2887 OPT__QUIET(&quiet, N_("print only error messages")),
2888 OPT__FORCE(&force, N_("force creation"), 0),
2889 OPT_BOOL(0, "create-reflog", &reflog,
2890 N_("create the branch's reflog")),
2891 OPT_CALLBACK_F('t', "track", &track, "(direct|inherit)",
2892 N_("set branch tracking configuration"),
2893 PARSE_OPT_OPTARG,
2894 parse_opt_tracking_mode),
2895 OPT__DRY_RUN(&dry_run,
2896 N_("show whether the branch would be created")),
2897 OPT_END()
2899 const char *const usage[] = {
2900 N_("git submodule--helper create-branch [-f|--force] [--create-reflog] [-q|--quiet] [-t|--track] [-n|--dry-run] <name> <start-oid> <start-name>"),
2901 NULL
2904 git_config(git_default_config, NULL);
2905 track = git_branch_track;
2906 argc = parse_options(argc, argv, prefix, options, usage, 0);
2908 if (argc != 3)
2909 usage_with_options(usage, options);
2911 if (!quiet && !dry_run)
2912 printf_ln(_("creating branch '%s'"), argv[0]);
2914 create_branches_recursively(the_repository, argv[0], argv[1], argv[2],
2915 force, reflog, quiet, track, dry_run);
2916 return 0;
2919 struct add_data {
2920 const char *prefix;
2921 const char *branch;
2922 const char *reference_path;
2923 char *sm_path;
2924 const char *sm_name;
2925 const char *repo;
2926 const char *realrepo;
2927 int depth;
2928 unsigned int force: 1;
2929 unsigned int quiet: 1;
2930 unsigned int progress: 1;
2931 unsigned int dissociate: 1;
2933 #define ADD_DATA_INIT { .depth = -1 }
2935 static void append_fetch_remotes(struct strbuf *msg, const char *git_dir_path)
2937 struct child_process cp_remote = CHILD_PROCESS_INIT;
2938 struct strbuf sb_remote_out = STRBUF_INIT;
2940 cp_remote.git_cmd = 1;
2941 strvec_pushf(&cp_remote.env,
2942 "GIT_DIR=%s", git_dir_path);
2943 strvec_push(&cp_remote.env, "GIT_WORK_TREE=.");
2944 strvec_pushl(&cp_remote.args, "remote", "-v", NULL);
2945 if (!capture_command(&cp_remote, &sb_remote_out, 0)) {
2946 char *next_line;
2947 char *line = sb_remote_out.buf;
2949 while ((next_line = strchr(line, '\n')) != NULL) {
2950 size_t len = next_line - line;
2952 if (strip_suffix_mem(line, &len, " (fetch)"))
2953 strbuf_addf(msg, " %.*s\n", (int)len, line);
2954 line = next_line + 1;
2958 strbuf_release(&sb_remote_out);
2961 static int add_submodule(const struct add_data *add_data)
2963 char *submod_gitdir_path;
2964 struct module_clone_data clone_data = MODULE_CLONE_DATA_INIT;
2965 struct string_list reference = STRING_LIST_INIT_NODUP;
2967 /* perhaps the path already exists and is already a git repo, else clone it */
2968 if (is_directory(add_data->sm_path)) {
2969 struct strbuf sm_path = STRBUF_INIT;
2970 strbuf_addstr(&sm_path, add_data->sm_path);
2971 submod_gitdir_path = xstrfmt("%s/.git", add_data->sm_path);
2972 if (is_nonbare_repository_dir(&sm_path))
2973 printf(_("Adding existing repo at '%s' to the index\n"),
2974 add_data->sm_path);
2975 else
2976 die(_("'%s' already exists and is not a valid git repo"),
2977 add_data->sm_path);
2978 strbuf_release(&sm_path);
2979 free(submod_gitdir_path);
2980 } else {
2981 struct child_process cp = CHILD_PROCESS_INIT;
2983 submod_gitdir_path = xstrfmt(".git/modules/%s", add_data->sm_name);
2985 if (is_directory(submod_gitdir_path)) {
2986 if (!add_data->force) {
2987 struct strbuf msg = STRBUF_INIT;
2988 char *die_msg;
2990 strbuf_addf(&msg, _("A git directory for '%s' is found "
2991 "locally with remote(s):\n"),
2992 add_data->sm_name);
2994 append_fetch_remotes(&msg, submod_gitdir_path);
2995 free(submod_gitdir_path);
2997 strbuf_addf(&msg, _("If you want to reuse this local git "
2998 "directory instead of cloning again from\n"
2999 " %s\n"
3000 "use the '--force' option. If the local git "
3001 "directory is not the correct repo\n"
3002 "or you are unsure what this means choose "
3003 "another name with the '--name' option."),
3004 add_data->realrepo);
3006 die_msg = strbuf_detach(&msg, NULL);
3007 die("%s", die_msg);
3008 } else {
3009 printf(_("Reactivating local git directory for "
3010 "submodule '%s'\n"), add_data->sm_name);
3013 free(submod_gitdir_path);
3015 clone_data.prefix = add_data->prefix;
3016 clone_data.path = add_data->sm_path;
3017 clone_data.name = add_data->sm_name;
3018 clone_data.url = add_data->realrepo;
3019 clone_data.quiet = add_data->quiet;
3020 clone_data.progress = add_data->progress;
3021 if (add_data->reference_path)
3022 string_list_append(&reference,
3023 xstrdup(add_data->reference_path));
3024 clone_data.dissociate = add_data->dissociate;
3025 if (add_data->depth >= 0)
3026 clone_data.depth = xstrfmt("%d", add_data->depth);
3028 if (clone_submodule(&clone_data, &reference))
3029 return -1;
3031 prepare_submodule_repo_env(&cp.env);
3032 cp.git_cmd = 1;
3033 cp.dir = add_data->sm_path;
3035 * NOTE: we only get here if add_data->force is true, so
3036 * passing --force to checkout is reasonable.
3038 strvec_pushl(&cp.args, "checkout", "-f", "-q", NULL);
3040 if (add_data->branch) {
3041 strvec_pushl(&cp.args, "-B", add_data->branch, NULL);
3042 strvec_pushf(&cp.args, "origin/%s", add_data->branch);
3045 if (run_command(&cp))
3046 die(_("unable to checkout submodule '%s'"), add_data->sm_path);
3048 return 0;
3051 static int config_submodule_in_gitmodules(const char *name, const char *var, const char *value)
3053 char *key;
3054 int ret;
3056 if (!is_writing_gitmodules_ok())
3057 die(_("please make sure that the .gitmodules file is in the working tree"));
3059 key = xstrfmt("submodule.%s.%s", name, var);
3060 ret = config_set_in_gitmodules_file_gently(key, value);
3061 free(key);
3063 return ret;
3066 static void configure_added_submodule(struct add_data *add_data)
3068 char *key;
3069 char *val = NULL;
3070 struct child_process add_submod = CHILD_PROCESS_INIT;
3071 struct child_process add_gitmodules = CHILD_PROCESS_INIT;
3073 key = xstrfmt("submodule.%s.url", add_data->sm_name);
3074 git_config_set_gently(key, add_data->realrepo);
3075 free(key);
3077 add_submod.git_cmd = 1;
3078 strvec_pushl(&add_submod.args, "add",
3079 "--no-warn-embedded-repo", NULL);
3080 if (add_data->force)
3081 strvec_push(&add_submod.args, "--force");
3082 strvec_pushl(&add_submod.args, "--", add_data->sm_path, NULL);
3084 if (run_command(&add_submod))
3085 die(_("Failed to add submodule '%s'"), add_data->sm_path);
3087 if (config_submodule_in_gitmodules(add_data->sm_name, "path", add_data->sm_path) ||
3088 config_submodule_in_gitmodules(add_data->sm_name, "url", add_data->repo))
3089 die(_("Failed to register submodule '%s'"), add_data->sm_path);
3091 if (add_data->branch) {
3092 if (config_submodule_in_gitmodules(add_data->sm_name,
3093 "branch", add_data->branch))
3094 die(_("Failed to register submodule '%s'"), add_data->sm_path);
3097 add_gitmodules.git_cmd = 1;
3098 strvec_pushl(&add_gitmodules.args,
3099 "add", "--force", "--", ".gitmodules", NULL);
3101 if (run_command(&add_gitmodules))
3102 die(_("Failed to register submodule '%s'"), add_data->sm_path);
3105 * NEEDSWORK: In a multi-working-tree world this needs to be
3106 * set in the per-worktree config.
3109 * NEEDSWORK: In the longer run, we need to get rid of this
3110 * pattern of querying "submodule.active" before calling
3111 * is_submodule_active(), since that function needs to find
3112 * out the value of "submodule.active" again anyway.
3114 if (!git_config_get_string("submodule.active", &val)) {
3116 * If the submodule being added isn't already covered by the
3117 * current configured pathspec, set the submodule's active flag
3119 if (!is_submodule_active(the_repository, add_data->sm_path)) {
3120 key = xstrfmt("submodule.%s.active", add_data->sm_name);
3121 git_config_set_gently(key, "true");
3122 free(key);
3124 } else {
3125 key = xstrfmt("submodule.%s.active", add_data->sm_name);
3126 git_config_set_gently(key, "true");
3127 free(key);
3131 static void die_on_index_match(const char *path, int force)
3133 struct pathspec ps;
3134 const char *args[] = { path, NULL };
3135 parse_pathspec(&ps, 0, PATHSPEC_PREFER_CWD, NULL, args);
3137 if (read_cache_preload(NULL) < 0)
3138 die(_("index file corrupt"));
3140 if (ps.nr) {
3141 int i;
3142 char *ps_matched = xcalloc(ps.nr, 1);
3144 /* TODO: audit for interaction with sparse-index. */
3145 ensure_full_index(&the_index);
3148 * Since there is only one pathspec, we just need
3149 * need to check ps_matched[0] to know if a cache
3150 * entry matched.
3152 for (i = 0; i < active_nr; i++) {
3153 ce_path_match(&the_index, active_cache[i], &ps,
3154 ps_matched);
3156 if (ps_matched[0]) {
3157 if (!force)
3158 die(_("'%s' already exists in the index"),
3159 path);
3160 if (!S_ISGITLINK(active_cache[i]->ce_mode))
3161 die(_("'%s' already exists in the index "
3162 "and is not a submodule"), path);
3163 break;
3166 free(ps_matched);
3168 clear_pathspec(&ps);
3171 static void die_on_repo_without_commits(const char *path)
3173 struct strbuf sb = STRBUF_INIT;
3174 strbuf_addstr(&sb, path);
3175 if (is_nonbare_repository_dir(&sb)) {
3176 struct object_id oid;
3177 if (resolve_gitlink_ref(path, "HEAD", &oid) < 0)
3178 die(_("'%s' does not have a commit checked out"), path);
3180 strbuf_release(&sb);
3183 static int module_add(int argc, const char **argv, const char *prefix)
3185 int force = 0, quiet = 0, progress = 0, dissociate = 0;
3186 struct add_data add_data = ADD_DATA_INIT;
3187 char *to_free = NULL;
3188 struct option options[] = {
3189 OPT_STRING('b', "branch", &add_data.branch, N_("branch"),
3190 N_("branch of repository to add as submodule")),
3191 OPT__FORCE(&force, N_("allow adding an otherwise ignored submodule path"),
3192 PARSE_OPT_NOCOMPLETE),
3193 OPT__QUIET(&quiet, N_("print only error messages")),
3194 OPT_BOOL(0, "progress", &progress, N_("force cloning progress")),
3195 OPT_STRING(0, "reference", &add_data.reference_path, N_("repository"),
3196 N_("reference repository")),
3197 OPT_BOOL(0, "dissociate", &dissociate, N_("borrow the objects from reference repositories")),
3198 OPT_STRING(0, "name", &add_data.sm_name, N_("name"),
3199 N_("sets the submodule's name to the given string "
3200 "instead of defaulting to its path")),
3201 OPT_INTEGER(0, "depth", &add_data.depth, N_("depth for shallow clones")),
3202 OPT_END()
3204 const char *const usage[] = {
3205 N_("git submodule add [<options>] [--] <repository> [<path>]"),
3206 NULL
3209 argc = parse_options(argc, argv, prefix, options, usage, 0);
3211 if (!is_writing_gitmodules_ok())
3212 die(_("please make sure that the .gitmodules file is in the working tree"));
3214 if (prefix && *prefix &&
3215 add_data.reference_path && !is_absolute_path(add_data.reference_path))
3216 add_data.reference_path = xstrfmt("%s%s", prefix, add_data.reference_path);
3218 if (argc == 0 || argc > 2)
3219 usage_with_options(usage, options);
3221 add_data.repo = argv[0];
3222 if (argc == 1)
3223 add_data.sm_path = git_url_basename(add_data.repo, 0, 0);
3224 else
3225 add_data.sm_path = xstrdup(argv[1]);
3227 if (prefix && *prefix && !is_absolute_path(add_data.sm_path))
3228 add_data.sm_path = xstrfmt("%s%s", prefix, add_data.sm_path);
3230 if (starts_with_dot_dot_slash(add_data.repo) ||
3231 starts_with_dot_slash(add_data.repo)) {
3232 if (prefix)
3233 die(_("Relative path can only be used from the toplevel "
3234 "of the working tree"));
3236 /* dereference source url relative to parent's url */
3237 to_free = resolve_relative_url(add_data.repo, NULL, 1);
3238 add_data.realrepo = to_free;
3239 } else if (is_dir_sep(add_data.repo[0]) || strchr(add_data.repo, ':')) {
3240 add_data.realrepo = add_data.repo;
3241 } else {
3242 die(_("repo URL: '%s' must be absolute or begin with ./|../"),
3243 add_data.repo);
3247 * normalize path:
3248 * multiple //; leading ./; /./; /../;
3250 normalize_path_copy(add_data.sm_path, add_data.sm_path);
3251 strip_dir_trailing_slashes(add_data.sm_path);
3253 die_on_index_match(add_data.sm_path, force);
3254 die_on_repo_without_commits(add_data.sm_path);
3256 if (!force) {
3257 int exit_code = -1;
3258 struct strbuf sb = STRBUF_INIT;
3259 struct child_process cp = CHILD_PROCESS_INIT;
3261 cp.git_cmd = 1;
3262 cp.no_stdout = 1;
3263 strvec_pushl(&cp.args, "add", "--dry-run", "--ignore-missing",
3264 "--no-warn-embedded-repo", add_data.sm_path, NULL);
3265 if ((exit_code = pipe_command(&cp, NULL, 0, NULL, 0, &sb, 0))) {
3266 strbuf_complete_line(&sb);
3267 fputs(sb.buf, stderr);
3268 free(add_data.sm_path);
3269 return exit_code;
3271 strbuf_release(&sb);
3274 if(!add_data.sm_name)
3275 add_data.sm_name = add_data.sm_path;
3277 if (check_submodule_name(add_data.sm_name))
3278 die(_("'%s' is not a valid submodule name"), add_data.sm_name);
3280 add_data.prefix = prefix;
3281 add_data.force = !!force;
3282 add_data.quiet = !!quiet;
3283 add_data.progress = !!progress;
3284 add_data.dissociate = !!dissociate;
3286 if (add_submodule(&add_data)) {
3287 free(add_data.sm_path);
3288 return 1;
3290 configure_added_submodule(&add_data);
3291 free(add_data.sm_path);
3292 free(to_free);
3294 return 0;
3297 #define SUPPORT_SUPER_PREFIX (1<<0)
3299 struct cmd_struct {
3300 const char *cmd;
3301 int (*fn)(int, const char **, const char *);
3302 unsigned option;
3305 static struct cmd_struct commands[] = {
3306 {"clone", module_clone, SUPPORT_SUPER_PREFIX},
3307 {"add", module_add, 0},
3308 {"update", module_update, SUPPORT_SUPER_PREFIX},
3309 {"foreach", module_foreach, SUPPORT_SUPER_PREFIX},
3310 {"init", module_init, 0},
3311 {"status", module_status, SUPPORT_SUPER_PREFIX},
3312 {"sync", module_sync, SUPPORT_SUPER_PREFIX},
3313 {"deinit", module_deinit, 0},
3314 {"summary", module_summary, 0},
3315 {"push-check", push_check, 0},
3316 {"absorbgitdirs", absorb_git_dirs, SUPPORT_SUPER_PREFIX},
3317 {"config", module_config, 0},
3318 {"set-url", module_set_url, 0},
3319 {"set-branch", module_set_branch, 0},
3320 {"create-branch", module_create_branch, 0},
3323 int cmd_submodule__helper(int argc, const char **argv, const char *prefix)
3325 int i;
3326 if (argc < 2 || !strcmp(argv[1], "-h"))
3327 usage("git submodule--helper <command>");
3329 for (i = 0; i < ARRAY_SIZE(commands); i++) {
3330 if (!strcmp(argv[1], commands[i].cmd)) {
3331 if (get_super_prefix() &&
3332 !(commands[i].option & SUPPORT_SUPER_PREFIX))
3333 die(_("%s doesn't support --super-prefix"),
3334 commands[i].cmd);
3335 return commands[i].fn(argc - 1, argv + 1, prefix);
3339 die(_("'%s' is not a valid submodule--helper "
3340 "subcommand"), argv[1]);