The 19th batch
[alt-git.git] / submodule.c
blob97d0d47b561fa42a982f613e7bae7105b56d4fab
1 #define USE_THE_REPOSITORY_VARIABLE
3 #include "git-compat-util.h"
4 #include "abspath.h"
5 #include "repository.h"
6 #include "config.h"
7 #include "submodule-config.h"
8 #include "submodule.h"
9 #include "dir.h"
10 #include "diff.h"
11 #include "commit.h"
12 #include "environment.h"
13 #include "gettext.h"
14 #include "hex.h"
15 #include "revision.h"
16 #include "run-command.h"
17 #include "diffcore.h"
18 #include "refs.h"
19 #include "string-list.h"
20 #include "oid-array.h"
21 #include "strvec.h"
22 #include "thread-utils.h"
23 #include "path.h"
24 #include "remote.h"
25 #include "worktree.h"
26 #include "parse-options.h"
27 #include "object-file.h"
28 #include "object-name.h"
29 #include "object-store-ll.h"
30 #include "commit-reach.h"
31 #include "read-cache-ll.h"
32 #include "setup.h"
33 #include "trace2.h"
35 static int config_update_recurse_submodules = RECURSE_SUBMODULES_OFF;
36 static int initialized_fetch_ref_tips;
37 static struct oid_array ref_tips_before_fetch;
38 static struct oid_array ref_tips_after_fetch;
41 * Check if the .gitmodules file is unmerged. Parsing of the .gitmodules file
42 * will be disabled because we can't guess what might be configured in
43 * .gitmodules unless the user resolves the conflict.
45 int is_gitmodules_unmerged(struct index_state *istate)
47 int pos = index_name_pos(istate, GITMODULES_FILE, strlen(GITMODULES_FILE));
48 if (pos < 0) { /* .gitmodules not found or isn't merged */
49 pos = -1 - pos;
50 if (istate->cache_nr > pos) { /* there is a .gitmodules */
51 const struct cache_entry *ce = istate->cache[pos];
52 if (ce_namelen(ce) == strlen(GITMODULES_FILE) &&
53 !strcmp(ce->name, GITMODULES_FILE))
54 return 1;
58 return 0;
62 * Check if the .gitmodules file is safe to write.
64 * Writing to the .gitmodules file requires that the file exists in the
65 * working tree or, if it doesn't, that a brand new .gitmodules file is going
66 * to be created (i.e. it's neither in the index nor in the current branch).
68 * It is not safe to write to .gitmodules if it's not in the working tree but
69 * it is in the index or in the current branch, because writing new values
70 * (and staging them) would blindly overwrite ALL the old content.
72 int is_writing_gitmodules_ok(void)
74 struct object_id oid;
75 return file_exists(GITMODULES_FILE) ||
76 (repo_get_oid(the_repository, GITMODULES_INDEX, &oid) < 0 && repo_get_oid(the_repository, GITMODULES_HEAD, &oid) < 0);
80 * Check if the .gitmodules file has unstaged modifications. This must be
81 * checked before allowing modifications to the .gitmodules file with the
82 * intention to stage them later, because when continuing we would stage the
83 * modifications the user didn't stage herself too. That might change in a
84 * future version when we learn to stage the changes we do ourselves without
85 * staging any previous modifications.
87 int is_staging_gitmodules_ok(struct index_state *istate)
89 int pos = index_name_pos(istate, GITMODULES_FILE, strlen(GITMODULES_FILE));
91 if ((pos >= 0) && (pos < istate->cache_nr)) {
92 struct stat st;
93 if (lstat(GITMODULES_FILE, &st) == 0 &&
94 ie_modified(istate, istate->cache[pos], &st, 0) & DATA_CHANGED)
95 return 0;
98 return 1;
101 static int for_each_remote_ref_submodule(const char *submodule,
102 each_ref_fn fn, void *cb_data)
104 return refs_for_each_remote_ref(repo_get_submodule_ref_store(the_repository,
105 submodule),
106 fn, cb_data);
110 * Try to update the "path" entry in the "submodule.<name>" section of the
111 * .gitmodules file. Return 0 only if a .gitmodules file was found, a section
112 * with the correct path=<oldpath> setting was found and we could update it.
114 int update_path_in_gitmodules(const char *oldpath, const char *newpath)
116 struct strbuf entry = STRBUF_INIT;
117 const struct submodule *submodule;
118 int ret;
120 if (!file_exists(GITMODULES_FILE)) /* Do nothing without .gitmodules */
121 return -1;
123 if (is_gitmodules_unmerged(the_repository->index))
124 die(_("Cannot change unmerged .gitmodules, resolve merge conflicts first"));
126 submodule = submodule_from_path(the_repository, null_oid(), oldpath);
127 if (!submodule || !submodule->name) {
128 warning(_("Could not find section in .gitmodules where path=%s"), oldpath);
129 return -1;
131 strbuf_addstr(&entry, "submodule.");
132 strbuf_addstr(&entry, submodule->name);
133 strbuf_addstr(&entry, ".path");
134 ret = config_set_in_gitmodules_file_gently(entry.buf, newpath);
135 strbuf_release(&entry);
136 return ret;
140 * Try to remove the "submodule.<name>" section from .gitmodules where the given
141 * path is configured. Return 0 only if a .gitmodules file was found, a section
142 * with the correct path=<path> setting was found and we could remove it.
144 int remove_path_from_gitmodules(const char *path)
146 struct strbuf sect = STRBUF_INIT;
147 const struct submodule *submodule;
149 if (!file_exists(GITMODULES_FILE)) /* Do nothing without .gitmodules */
150 return -1;
152 if (is_gitmodules_unmerged(the_repository->index))
153 die(_("Cannot change unmerged .gitmodules, resolve merge conflicts first"));
155 submodule = submodule_from_path(the_repository, null_oid(), path);
156 if (!submodule || !submodule->name) {
157 warning(_("Could not find section in .gitmodules where path=%s"), path);
158 return -1;
160 strbuf_addstr(&sect, "submodule.");
161 strbuf_addstr(&sect, submodule->name);
162 if (repo_config_rename_section_in_file(the_repository, GITMODULES_FILE, sect.buf, NULL) < 0) {
163 /* Maybe the user already did that, don't error out here */
164 warning(_("Could not remove .gitmodules entry for %s"), path);
165 strbuf_release(&sect);
166 return -1;
168 strbuf_release(&sect);
169 return 0;
172 void stage_updated_gitmodules(struct index_state *istate)
174 if (add_file_to_index(istate, GITMODULES_FILE, 0))
175 die(_("staging updated .gitmodules failed"));
178 static struct string_list added_submodule_odb_paths = STRING_LIST_INIT_NODUP;
180 void add_submodule_odb_by_path(const char *path)
182 string_list_insert(&added_submodule_odb_paths, xstrdup(path));
185 int register_all_submodule_odb_as_alternates(void)
187 int i;
188 int ret = added_submodule_odb_paths.nr;
190 for (i = 0; i < added_submodule_odb_paths.nr; i++)
191 add_to_alternates_memory(added_submodule_odb_paths.items[i].string);
192 if (ret) {
193 string_list_clear(&added_submodule_odb_paths, 0);
194 trace2_data_intmax("submodule", the_repository,
195 "register_all_submodule_odb_as_alternates/registered", ret);
196 if (git_env_bool("GIT_TEST_FATAL_REGISTER_SUBMODULE_ODB", 0))
197 BUG("register_all_submodule_odb_as_alternates() called");
199 return ret;
202 void set_diffopt_flags_from_submodule_config(struct diff_options *diffopt,
203 const char *path)
205 const struct submodule *submodule = submodule_from_path(the_repository,
206 null_oid(),
207 path);
208 if (submodule) {
209 const char *ignore;
210 char *key;
212 key = xstrfmt("submodule.%s.ignore", submodule->name);
213 if (repo_config_get_string_tmp(the_repository, key, &ignore))
214 ignore = submodule->ignore;
215 free(key);
217 if (ignore)
218 handle_ignore_submodules_arg(diffopt, ignore);
219 else if (is_gitmodules_unmerged(the_repository->index))
220 diffopt->flags.ignore_submodules = 1;
224 /* Cheap function that only determines if we're interested in submodules at all */
225 int git_default_submodule_config(const char *var, const char *value,
226 void *cb UNUSED)
228 if (!strcmp(var, "submodule.recurse")) {
229 int v = git_config_bool(var, value) ?
230 RECURSE_SUBMODULES_ON : RECURSE_SUBMODULES_OFF;
231 config_update_recurse_submodules = v;
233 return 0;
236 int option_parse_recurse_submodules_worktree_updater(const struct option *opt,
237 const char *arg, int unset)
239 if (unset) {
240 config_update_recurse_submodules = RECURSE_SUBMODULES_OFF;
241 return 0;
243 if (arg)
244 config_update_recurse_submodules =
245 parse_update_recurse_submodules_arg(opt->long_name,
246 arg);
247 else
248 config_update_recurse_submodules = RECURSE_SUBMODULES_ON;
250 return 0;
254 * Determine if a submodule has been initialized at a given 'path'
257 * NEEDSWORK: Emit a warning if submodule.active exists, but is valueless,
258 * ie, the config looks like: "[submodule] active\n".
259 * Since that is an invalid pathspec, we should inform the user.
261 int is_tree_submodule_active(struct repository *repo,
262 const struct object_id *treeish_name,
263 const char *path)
265 int ret = 0;
266 char *key = NULL;
267 char *value = NULL;
268 const struct string_list *sl;
269 const struct submodule *module;
271 module = submodule_from_path(repo, treeish_name, path);
273 /* early return if there isn't a path->module mapping */
274 if (!module)
275 return 0;
277 /* submodule.<name>.active is set */
278 key = xstrfmt("submodule.%s.active", module->name);
279 if (!repo_config_get_bool(repo, key, &ret)) {
280 free(key);
281 return ret;
283 free(key);
285 /* submodule.active is set */
286 if (!repo_config_get_string_multi(repo, "submodule.active", &sl)) {
287 struct pathspec ps;
288 struct strvec args = STRVEC_INIT;
289 const struct string_list_item *item;
291 for_each_string_list_item(item, sl) {
292 strvec_push(&args, item->string);
295 parse_pathspec(&ps, 0, 0, NULL, args.v);
296 ret = match_pathspec(repo->index, &ps, path, strlen(path), 0, NULL, 1);
298 strvec_clear(&args);
299 clear_pathspec(&ps);
300 return ret;
303 /* fallback to checking if the URL is set */
304 key = xstrfmt("submodule.%s.url", module->name);
305 ret = !repo_config_get_string(repo, key, &value);
307 free(value);
308 free(key);
309 return ret;
312 int is_submodule_active(struct repository *repo, const char *path)
314 return is_tree_submodule_active(repo, null_oid(), path);
317 int is_submodule_populated_gently(const char *path, int *return_error_code)
319 int ret = 0;
320 char *gitdir = xstrfmt("%s/.git", path);
322 if (resolve_gitdir_gently(gitdir, return_error_code))
323 ret = 1;
325 free(gitdir);
326 return ret;
330 * Dies if the provided 'prefix' corresponds to an unpopulated submodule
332 void die_in_unpopulated_submodule(struct index_state *istate,
333 const char *prefix)
335 int i, prefixlen;
337 if (!prefix)
338 return;
340 prefixlen = strlen(prefix);
342 for (i = 0; i < istate->cache_nr; i++) {
343 struct cache_entry *ce = istate->cache[i];
344 int ce_len = ce_namelen(ce);
346 if (!S_ISGITLINK(ce->ce_mode))
347 continue;
348 if (prefixlen <= ce_len)
349 continue;
350 if (strncmp(ce->name, prefix, ce_len))
351 continue;
352 if (prefix[ce_len] != '/')
353 continue;
355 die(_("in unpopulated submodule '%s'"), ce->name);
360 * Dies if any paths in the provided pathspec descends into a submodule
362 void die_path_inside_submodule(struct index_state *istate,
363 const struct pathspec *ps)
365 int i, j;
367 for (i = 0; i < istate->cache_nr; i++) {
368 struct cache_entry *ce = istate->cache[i];
369 int ce_len = ce_namelen(ce);
371 if (!S_ISGITLINK(ce->ce_mode))
372 continue;
374 for (j = 0; j < ps->nr ; j++) {
375 const struct pathspec_item *item = &ps->items[j];
377 if (item->len <= ce_len)
378 continue;
379 if (item->match[ce_len] != '/')
380 continue;
381 if (strncmp(ce->name, item->match, ce_len))
382 continue;
383 if (item->len == ce_len + 1)
384 continue;
386 die(_("Pathspec '%s' is in submodule '%.*s'"),
387 item->original, ce_len, ce->name);
392 enum submodule_update_type parse_submodule_update_type(const char *value)
394 if (!strcmp(value, "none"))
395 return SM_UPDATE_NONE;
396 else if (!strcmp(value, "checkout"))
397 return SM_UPDATE_CHECKOUT;
398 else if (!strcmp(value, "rebase"))
399 return SM_UPDATE_REBASE;
400 else if (!strcmp(value, "merge"))
401 return SM_UPDATE_MERGE;
402 else if (*value == '!')
403 return SM_UPDATE_COMMAND;
404 else
405 return SM_UPDATE_UNSPECIFIED;
408 int parse_submodule_update_strategy(const char *value,
409 struct submodule_update_strategy *dst)
411 enum submodule_update_type type;
413 free((void*)dst->command);
414 dst->command = NULL;
416 type = parse_submodule_update_type(value);
417 if (type == SM_UPDATE_UNSPECIFIED)
418 return -1;
420 dst->type = type;
421 if (type == SM_UPDATE_COMMAND)
422 dst->command = xstrdup(value + 1);
424 return 0;
427 const char *submodule_update_type_to_string(enum submodule_update_type type)
429 switch (type) {
430 case SM_UPDATE_CHECKOUT:
431 return "checkout";
432 case SM_UPDATE_MERGE:
433 return "merge";
434 case SM_UPDATE_REBASE:
435 return "rebase";
436 case SM_UPDATE_NONE:
437 return "none";
438 case SM_UPDATE_UNSPECIFIED:
439 case SM_UPDATE_COMMAND:
440 BUG("init_submodule() should handle type %d", type);
441 default:
442 BUG("unexpected update strategy type: %d", type);
446 void handle_ignore_submodules_arg(struct diff_options *diffopt,
447 const char *arg)
449 diffopt->flags.ignore_submodule_set = 1;
450 diffopt->flags.ignore_submodules = 0;
451 diffopt->flags.ignore_untracked_in_submodules = 0;
452 diffopt->flags.ignore_dirty_submodules = 0;
454 if (!strcmp(arg, "all"))
455 diffopt->flags.ignore_submodules = 1;
456 else if (!strcmp(arg, "untracked"))
457 diffopt->flags.ignore_untracked_in_submodules = 1;
458 else if (!strcmp(arg, "dirty"))
459 diffopt->flags.ignore_dirty_submodules = 1;
460 else if (strcmp(arg, "none"))
461 die(_("bad --ignore-submodules argument: %s"), arg);
463 * Please update _git_status() in git-completion.bash when you
464 * add new options
468 static int prepare_submodule_diff_summary(struct repository *r, struct rev_info *rev,
469 const char *path,
470 struct commit *left, struct commit *right,
471 struct commit_list *merge_bases)
473 struct commit_list *list;
475 repo_init_revisions(r, rev, NULL);
476 setup_revisions(0, NULL, rev, NULL);
477 rev->left_right = 1;
478 rev->first_parent_only = 1;
479 left->object.flags |= SYMMETRIC_LEFT;
480 add_pending_object(rev, &left->object, path);
481 add_pending_object(rev, &right->object, path);
482 for (list = merge_bases; list; list = list->next) {
483 list->item->object.flags |= UNINTERESTING;
484 add_pending_object(rev, &list->item->object,
485 oid_to_hex(&list->item->object.oid));
487 return prepare_revision_walk(rev);
490 static void print_submodule_diff_summary(struct repository *r, struct rev_info *rev, struct diff_options *o)
492 static const char format[] = " %m %s";
493 struct strbuf sb = STRBUF_INIT;
494 struct commit *commit;
496 while ((commit = get_revision(rev))) {
497 struct pretty_print_context ctx = {0};
498 ctx.date_mode = rev->date_mode;
499 ctx.output_encoding = get_log_output_encoding();
500 strbuf_setlen(&sb, 0);
501 repo_format_commit_message(r, commit, format, &sb,
502 &ctx);
503 strbuf_addch(&sb, '\n');
504 if (commit->object.flags & SYMMETRIC_LEFT)
505 diff_emit_submodule_del(o, sb.buf);
506 else
507 diff_emit_submodule_add(o, sb.buf);
509 strbuf_release(&sb);
512 void prepare_submodule_repo_env(struct strvec *out)
514 prepare_other_repo_env(out, DEFAULT_GIT_DIR_ENVIRONMENT);
517 static void prepare_submodule_repo_env_in_gitdir(struct strvec *out)
519 prepare_other_repo_env(out, ".");
523 * Initialize a repository struct for a submodule based on the provided 'path'.
525 * Returns the repository struct on success,
526 * NULL when the submodule is not present.
528 static struct repository *open_submodule(const char *path)
530 struct strbuf sb = STRBUF_INIT;
531 struct repository *out = xmalloc(sizeof(*out));
533 if (submodule_to_gitdir(&sb, path) || repo_init(out, sb.buf, NULL)) {
534 strbuf_release(&sb);
535 free(out);
536 return NULL;
539 /* Mark it as a submodule */
540 out->submodule_prefix = xstrdup(path);
542 strbuf_release(&sb);
543 return out;
547 * Helper function to display the submodule header line prior to the full
548 * summary output.
550 * If it can locate the submodule git directory it will create a repository
551 * handle for the submodule and lookup both the left and right commits and
552 * put them into the left and right pointers.
554 static void show_submodule_header(struct diff_options *o,
555 const char *path,
556 struct object_id *one, struct object_id *two,
557 unsigned dirty_submodule,
558 struct repository *sub,
559 struct commit **left, struct commit **right,
560 struct commit_list **merge_bases)
562 const char *message = NULL;
563 struct strbuf sb = STRBUF_INIT;
564 int fast_forward = 0, fast_backward = 0;
566 if (dirty_submodule & DIRTY_SUBMODULE_UNTRACKED)
567 diff_emit_submodule_untracked(o, path);
569 if (dirty_submodule & DIRTY_SUBMODULE_MODIFIED)
570 diff_emit_submodule_modified(o, path);
572 if (is_null_oid(one))
573 message = "(new submodule)";
574 else if (is_null_oid(two))
575 message = "(submodule deleted)";
577 if (!sub) {
578 if (!message)
579 message = "(commits not present)";
580 goto output_header;
584 * Attempt to lookup the commit references, and determine if this is
585 * a fast forward or fast backwards update.
587 *left = lookup_commit_reference(sub, one);
588 *right = lookup_commit_reference(sub, two);
591 * Warn about missing commits in the submodule project, but only if
592 * they aren't null.
594 if ((!is_null_oid(one) && !*left) ||
595 (!is_null_oid(two) && !*right))
596 message = "(commits not present)";
598 *merge_bases = NULL;
599 if (repo_get_merge_bases(sub, *left, *right, merge_bases) < 0) {
600 message = "(corrupt repository)";
601 goto output_header;
604 if (*merge_bases) {
605 if ((*merge_bases)->item == *left)
606 fast_forward = 1;
607 else if ((*merge_bases)->item == *right)
608 fast_backward = 1;
611 if (oideq(one, two)) {
612 strbuf_release(&sb);
613 return;
616 output_header:
617 strbuf_addf(&sb, "Submodule %s ", path);
618 strbuf_add_unique_abbrev(&sb, one, DEFAULT_ABBREV);
619 strbuf_addstr(&sb, (fast_backward || fast_forward) ? ".." : "...");
620 strbuf_add_unique_abbrev(&sb, two, DEFAULT_ABBREV);
621 if (message)
622 strbuf_addf(&sb, " %s\n", message);
623 else
624 strbuf_addf(&sb, "%s:\n", fast_backward ? " (rewind)" : "");
625 diff_emit_submodule_header(o, sb.buf);
627 strbuf_release(&sb);
630 void show_submodule_diff_summary(struct diff_options *o, const char *path,
631 struct object_id *one, struct object_id *two,
632 unsigned dirty_submodule)
634 struct rev_info rev = REV_INFO_INIT;
635 struct commit *left = NULL, *right = NULL;
636 struct commit_list *merge_bases = NULL;
637 struct repository *sub;
639 sub = open_submodule(path);
640 show_submodule_header(o, path, one, two, dirty_submodule,
641 sub, &left, &right, &merge_bases);
644 * If we don't have both a left and a right pointer, there is no
645 * reason to try and display a summary. The header line should contain
646 * all the information the user needs.
648 if (!left || !right || !sub)
649 goto out;
651 /* Treat revision walker failure the same as missing commits */
652 if (prepare_submodule_diff_summary(sub, &rev, path, left, right, merge_bases)) {
653 diff_emit_submodule_error(o, "(revision walker failed)\n");
654 goto out;
657 print_submodule_diff_summary(sub, &rev, o);
659 out:
660 free_commit_list(merge_bases);
661 release_revisions(&rev);
662 clear_commit_marks(left, ~0);
663 clear_commit_marks(right, ~0);
664 if (sub) {
665 repo_clear(sub);
666 free(sub);
670 void show_submodule_inline_diff(struct diff_options *o, const char *path,
671 struct object_id *one, struct object_id *two,
672 unsigned dirty_submodule)
674 const struct object_id *old_oid = the_hash_algo->empty_tree, *new_oid = the_hash_algo->empty_tree;
675 struct commit *left = NULL, *right = NULL;
676 struct commit_list *merge_bases = NULL;
677 struct child_process cp = CHILD_PROCESS_INIT;
678 struct strbuf sb = STRBUF_INIT;
679 struct repository *sub;
681 sub = open_submodule(path);
682 show_submodule_header(o, path, one, two, dirty_submodule,
683 sub, &left, &right, &merge_bases);
685 /* We need a valid left and right commit to display a difference */
686 if (!(left || is_null_oid(one)) ||
687 !(right || is_null_oid(two)))
688 goto done;
690 if (left)
691 old_oid = one;
692 if (right)
693 new_oid = two;
695 cp.git_cmd = 1;
696 cp.dir = path;
697 cp.out = -1;
698 cp.no_stdin = 1;
700 /* TODO: other options may need to be passed here. */
701 strvec_pushl(&cp.args, "diff", "--submodule=diff", NULL);
702 strvec_pushf(&cp.args, "--color=%s", want_color(o->use_color) ?
703 "always" : "never");
705 if (o->flags.reverse_diff) {
706 strvec_pushf(&cp.args, "--src-prefix=%s%s/",
707 o->b_prefix, path);
708 strvec_pushf(&cp.args, "--dst-prefix=%s%s/",
709 o->a_prefix, path);
710 } else {
711 strvec_pushf(&cp.args, "--src-prefix=%s%s/",
712 o->a_prefix, path);
713 strvec_pushf(&cp.args, "--dst-prefix=%s%s/",
714 o->b_prefix, path);
716 strvec_push(&cp.args, oid_to_hex(old_oid));
718 * If the submodule has modified content, we will diff against the
719 * work tree, under the assumption that the user has asked for the
720 * diff format and wishes to actually see all differences even if they
721 * haven't yet been committed to the submodule yet.
723 if (!(dirty_submodule & DIRTY_SUBMODULE_MODIFIED))
724 strvec_push(&cp.args, oid_to_hex(new_oid));
726 prepare_submodule_repo_env(&cp.env);
728 if (!is_directory(path)) {
729 /* fall back to absorbed git dir, if any */
730 if (!sub)
731 goto done;
732 cp.dir = sub->gitdir;
733 strvec_push(&cp.env, GIT_DIR_ENVIRONMENT "=.");
734 strvec_push(&cp.env, GIT_WORK_TREE_ENVIRONMENT "=.");
737 if (start_command(&cp)) {
738 diff_emit_submodule_error(o, "(diff failed)\n");
739 goto done;
742 while (strbuf_getwholeline_fd(&sb, cp.out, '\n') != EOF)
743 diff_emit_submodule_pipethrough(o, sb.buf, sb.len);
745 if (finish_command(&cp))
746 diff_emit_submodule_error(o, "(diff failed)\n");
748 done:
749 strbuf_release(&sb);
750 free_commit_list(merge_bases);
751 if (left)
752 clear_commit_marks(left, ~0);
753 if (right)
754 clear_commit_marks(right, ~0);
755 if (sub) {
756 repo_clear(sub);
757 free(sub);
761 int should_update_submodules(void)
763 return config_update_recurse_submodules == RECURSE_SUBMODULES_ON;
766 const struct submodule *submodule_from_ce(const struct cache_entry *ce)
768 if (!S_ISGITLINK(ce->ce_mode))
769 return NULL;
771 if (!should_update_submodules())
772 return NULL;
774 return submodule_from_path(the_repository, null_oid(), ce->name);
778 struct collect_changed_submodules_cb_data {
779 struct repository *repo;
780 struct string_list *changed;
781 const struct object_id *commit_oid;
785 * this would normally be two functions: default_name_from_path() and
786 * path_from_default_name(). Since the default name is the same as
787 * the submodule path we can get away with just one function which only
788 * checks whether there is a submodule in the working directory at that
789 * location.
791 static const char *default_name_or_path(const char *path_or_name)
793 int error_code;
795 if (!is_submodule_populated_gently(path_or_name, &error_code))
796 return NULL;
798 return path_or_name;
802 * Holds relevant information for a changed submodule. Used as the .util
803 * member of the changed submodule name string_list_item.
805 * (super_oid, path) allows the submodule config to be read from _some_
806 * .gitmodules file. We store this information the first time we find a
807 * superproject commit that points to the submodule, but this is
808 * arbitrary - we can choose any (super_oid, path) that matches the
809 * submodule's name.
811 * NEEDSWORK: Storing an arbitrary commit is undesirable because we can't
812 * guarantee that we're reading the commit that the user would expect. A better
813 * scheme would be to just fetch a submodule by its name. This requires two
814 * steps:
815 * - Create a function that behaves like repo_submodule_init(), but accepts a
816 * submodule name instead of treeish_name and path. This should be easy
817 * because repo_submodule_init() internally uses the submodule's name.
819 * - Replace most instances of 'struct submodule' (which is the .gitmodules
820 * config) with just the submodule name. This is OK because we expect
821 * submodule settings to be stored in .git/config (via "git submodule init"),
822 * not .gitmodules. This also lets us delete get_non_gitmodules_submodule(),
823 * which constructs a bogus 'struct submodule' for the sake of giving a
824 * placeholder name to a gitlink.
826 struct changed_submodule_data {
828 * The first superproject commit in the rev walk that points to
829 * the submodule.
831 const struct object_id *super_oid;
833 * Path to the submodule in the superproject commit referenced
834 * by 'super_oid'.
836 char *path;
837 /* The submodule commits that have changed in the rev walk. */
838 struct oid_array new_commits;
841 static void changed_submodule_data_clear(struct changed_submodule_data *cs_data)
843 oid_array_clear(&cs_data->new_commits);
844 free(cs_data->path);
847 static void collect_changed_submodules_cb(struct diff_queue_struct *q,
848 struct diff_options *options UNUSED,
849 void *data)
851 struct collect_changed_submodules_cb_data *me = data;
852 struct string_list *changed = me->changed;
853 const struct object_id *commit_oid = me->commit_oid;
854 int i;
856 for (i = 0; i < q->nr; i++) {
857 struct diff_filepair *p = q->queue[i];
858 const struct submodule *submodule;
859 const char *name;
860 struct string_list_item *item;
861 struct changed_submodule_data *cs_data;
863 if (!S_ISGITLINK(p->two->mode))
864 continue;
866 submodule = submodule_from_path(me->repo,
867 commit_oid, p->two->path);
868 if (submodule)
869 name = submodule->name;
870 else {
871 name = default_name_or_path(p->two->path);
872 /* make sure name does not collide with existing one */
873 if (name)
874 submodule = submodule_from_name(me->repo,
875 commit_oid, name);
876 if (submodule) {
877 warning(_("Submodule in commit %s at path: "
878 "'%s' collides with a submodule named "
879 "the same. Skipping it."),
880 oid_to_hex(commit_oid), p->two->path);
881 name = NULL;
885 if (!name)
886 continue;
888 item = string_list_insert(changed, name);
889 if (item->util)
890 cs_data = item->util;
891 else {
892 item->util = xcalloc(1, sizeof(struct changed_submodule_data));
893 cs_data = item->util;
894 cs_data->super_oid = commit_oid;
895 cs_data->path = xstrdup(p->two->path);
897 oid_array_append(&cs_data->new_commits, &p->two->oid);
902 * Collect the paths of submodules in 'changed' which have changed based on
903 * the revisions as specified in 'argv'. Each entry in 'changed' will also
904 * have a corresponding 'struct oid_array' (in the 'util' field) which lists
905 * what the submodule pointers were updated to during the change.
907 static void collect_changed_submodules(struct repository *r,
908 struct string_list *changed,
909 struct strvec *argv)
911 struct rev_info rev;
912 const struct commit *commit;
913 int save_warning;
914 struct setup_revision_opt s_r_opt = {
915 .assume_dashdash = 1,
918 save_warning = warn_on_object_refname_ambiguity;
919 warn_on_object_refname_ambiguity = 0;
920 repo_init_revisions(r, &rev, NULL);
921 setup_revisions(argv->nr, argv->v, &rev, &s_r_opt);
922 warn_on_object_refname_ambiguity = save_warning;
923 if (prepare_revision_walk(&rev))
924 die(_("revision walk setup failed"));
926 while ((commit = get_revision(&rev))) {
927 struct rev_info diff_rev;
928 struct collect_changed_submodules_cb_data data;
929 data.repo = r;
930 data.changed = changed;
931 data.commit_oid = &commit->object.oid;
933 repo_init_revisions(r, &diff_rev, NULL);
934 diff_rev.diffopt.output_format |= DIFF_FORMAT_CALLBACK;
935 diff_rev.diffopt.format_callback = collect_changed_submodules_cb;
936 diff_rev.diffopt.format_callback_data = &data;
937 diff_rev.dense_combined_merges = 1;
938 diff_tree_combined_merge(commit, &diff_rev);
939 release_revisions(&diff_rev);
942 reset_revision_walk();
943 release_revisions(&rev);
946 static void free_submodules_data(struct string_list *submodules)
948 struct string_list_item *item;
949 for_each_string_list_item(item, submodules)
950 changed_submodule_data_clear(item->util);
952 string_list_clear(submodules, 1);
955 static int has_remote(const char *refname UNUSED,
956 const char *referent UNUSED,
957 const struct object_id *oid UNUSED,
958 int flags UNUSED, void *cb_data UNUSED)
960 return 1;
963 static int append_oid_to_argv(const struct object_id *oid, void *data)
965 struct strvec *argv = data;
966 strvec_push(argv, oid_to_hex(oid));
967 return 0;
970 struct has_commit_data {
971 struct repository *repo;
972 int result;
973 const char *path;
974 const struct object_id *super_oid;
977 static int check_has_commit(const struct object_id *oid, void *data)
979 struct has_commit_data *cb = data;
980 struct repository subrepo;
981 enum object_type type;
983 if (repo_submodule_init(&subrepo, cb->repo, cb->path, cb->super_oid)) {
984 cb->result = 0;
985 /* subrepo failed to init, so don't clean it up. */
986 return 0;
989 type = oid_object_info(&subrepo, oid, NULL);
991 switch (type) {
992 case OBJ_COMMIT:
993 goto cleanup;
994 case OBJ_BAD:
996 * Object is missing or invalid. If invalid, an error message
997 * has already been printed.
999 cb->result = 0;
1000 goto cleanup;
1001 default:
1002 die(_("submodule entry '%s' (%s) is a %s, not a commit"),
1003 cb->path, oid_to_hex(oid), type_name(type));
1005 cleanup:
1006 repo_clear(&subrepo);
1007 return 0;
1010 static int submodule_has_commits(struct repository *r,
1011 const char *path,
1012 const struct object_id *super_oid,
1013 struct oid_array *commits)
1015 struct has_commit_data has_commit = {
1016 .repo = r,
1017 .result = 1,
1018 .path = path,
1019 .super_oid = super_oid
1022 if (validate_submodule_path(path) < 0)
1023 exit(128);
1025 oid_array_for_each_unique(commits, check_has_commit, &has_commit);
1027 if (has_commit.result) {
1029 * Even if the submodule is checked out and the commit is
1030 * present, make sure it exists in the submodule's object store
1031 * and that it is reachable from a ref.
1033 struct child_process cp = CHILD_PROCESS_INIT;
1034 struct strbuf out = STRBUF_INIT;
1036 strvec_pushl(&cp.args, "rev-list", "-n", "1", NULL);
1037 oid_array_for_each_unique(commits, append_oid_to_argv, &cp.args);
1038 strvec_pushl(&cp.args, "--not", "--all", NULL);
1040 prepare_submodule_repo_env(&cp.env);
1041 cp.git_cmd = 1;
1042 cp.no_stdin = 1;
1043 cp.dir = path;
1045 if (capture_command(&cp, &out, GIT_MAX_HEXSZ + 1) || out.len)
1046 has_commit.result = 0;
1048 strbuf_release(&out);
1051 return has_commit.result;
1054 static int submodule_needs_pushing(struct repository *r,
1055 const char *path,
1056 struct oid_array *commits)
1058 if (!submodule_has_commits(r, path, null_oid(), commits))
1060 * NOTE: We do consider it safe to return "no" here. The
1061 * correct answer would be "We do not know" instead of
1062 * "No push needed", but it is quite hard to change
1063 * the submodule pointer without having the submodule
1064 * around. If a user did however change the submodules
1065 * without having the submodule around, this indicates
1066 * an expert who knows what they are doing or a
1067 * maintainer integrating work from other people. In
1068 * both cases it should be safe to skip this check.
1070 return 0;
1072 if (for_each_remote_ref_submodule(path, has_remote, NULL) > 0) {
1073 struct child_process cp = CHILD_PROCESS_INIT;
1074 struct strbuf buf = STRBUF_INIT;
1075 int needs_pushing = 0;
1077 strvec_push(&cp.args, "rev-list");
1078 oid_array_for_each_unique(commits, append_oid_to_argv, &cp.args);
1079 strvec_pushl(&cp.args, "--not", "--remotes", "-n", "1" , NULL);
1081 prepare_submodule_repo_env(&cp.env);
1082 cp.git_cmd = 1;
1083 cp.no_stdin = 1;
1084 cp.out = -1;
1085 cp.dir = path;
1086 if (start_command(&cp))
1087 die(_("Could not run 'git rev-list <commits> --not --remotes -n 1' command in submodule %s"),
1088 path);
1089 if (strbuf_read(&buf, cp.out, the_hash_algo->hexsz + 1))
1090 needs_pushing = 1;
1091 finish_command(&cp);
1092 close(cp.out);
1093 strbuf_release(&buf);
1094 return needs_pushing;
1097 return 0;
1100 int find_unpushed_submodules(struct repository *r,
1101 struct oid_array *commits,
1102 const char *remotes_name,
1103 struct string_list *needs_pushing)
1105 struct string_list submodules = STRING_LIST_INIT_DUP;
1106 struct string_list_item *name;
1107 struct strvec argv = STRVEC_INIT;
1109 /* argv.v[0] will be ignored by setup_revisions */
1110 strvec_push(&argv, "find_unpushed_submodules");
1111 oid_array_for_each_unique(commits, append_oid_to_argv, &argv);
1112 strvec_push(&argv, "--not");
1113 strvec_pushf(&argv, "--remotes=%s", remotes_name);
1115 collect_changed_submodules(r, &submodules, &argv);
1117 for_each_string_list_item(name, &submodules) {
1118 struct changed_submodule_data *cs_data = name->util;
1119 const struct submodule *submodule;
1120 const char *path = NULL;
1122 submodule = submodule_from_name(r, null_oid(), name->string);
1123 if (submodule)
1124 path = submodule->path;
1125 else
1126 path = default_name_or_path(name->string);
1128 if (!path)
1129 continue;
1131 if (submodule_needs_pushing(r, path, &cs_data->new_commits))
1132 string_list_insert(needs_pushing, path);
1135 free_submodules_data(&submodules);
1136 strvec_clear(&argv);
1138 return needs_pushing->nr;
1141 static int push_submodule(const char *path,
1142 const struct remote *remote,
1143 const struct refspec *rs,
1144 const struct string_list *push_options,
1145 int dry_run)
1147 if (validate_submodule_path(path) < 0)
1148 exit(128);
1150 if (for_each_remote_ref_submodule(path, has_remote, NULL) > 0) {
1151 struct child_process cp = CHILD_PROCESS_INIT;
1152 strvec_push(&cp.args, "push");
1154 * When recursing into a submodule, treat any "only" configurations as "on-
1155 * demand", since "only" would not work (we need all submodules to be pushed
1156 * in order to be able to push the superproject).
1158 strvec_push(&cp.args, "--recurse-submodules=only-is-on-demand");
1159 if (dry_run)
1160 strvec_push(&cp.args, "--dry-run");
1162 if (push_options && push_options->nr) {
1163 const struct string_list_item *item;
1164 for_each_string_list_item(item, push_options)
1165 strvec_pushf(&cp.args, "--push-option=%s",
1166 item->string);
1169 if (remote->origin != REMOTE_UNCONFIGURED) {
1170 int i;
1171 strvec_push(&cp.args, remote->name);
1172 for (i = 0; i < rs->raw_nr; i++)
1173 strvec_push(&cp.args, rs->raw[i]);
1176 prepare_submodule_repo_env(&cp.env);
1177 cp.git_cmd = 1;
1178 cp.no_stdin = 1;
1179 cp.dir = path;
1180 if (run_command(&cp))
1181 return 0;
1182 close(cp.out);
1185 return 1;
1189 * Perform a check in the submodule to see if the remote and refspec work.
1190 * Die if the submodule can't be pushed.
1192 static void submodule_push_check(const char *path, const char *head,
1193 const struct remote *remote,
1194 const struct refspec *rs)
1196 struct child_process cp = CHILD_PROCESS_INIT;
1197 int i;
1199 if (validate_submodule_path(path) < 0)
1200 exit(128);
1202 strvec_push(&cp.args, "submodule--helper");
1203 strvec_push(&cp.args, "push-check");
1204 strvec_push(&cp.args, head);
1205 strvec_push(&cp.args, remote->name);
1207 for (i = 0; i < rs->raw_nr; i++)
1208 strvec_push(&cp.args, rs->raw[i]);
1210 prepare_submodule_repo_env(&cp.env);
1211 cp.git_cmd = 1;
1212 cp.no_stdin = 1;
1213 cp.no_stdout = 1;
1214 cp.dir = path;
1217 * Simply indicate if 'submodule--helper push-check' failed.
1218 * More detailed error information will be provided by the
1219 * child process.
1221 if (run_command(&cp))
1222 die(_("process for submodule '%s' failed"), path);
1225 int push_unpushed_submodules(struct repository *r,
1226 struct oid_array *commits,
1227 const struct remote *remote,
1228 const struct refspec *rs,
1229 const struct string_list *push_options,
1230 int dry_run)
1232 int i, ret = 1;
1233 struct string_list needs_pushing = STRING_LIST_INIT_DUP;
1235 if (!find_unpushed_submodules(r, commits,
1236 remote->name, &needs_pushing))
1237 return 1;
1240 * Verify that the remote and refspec can be propagated to all
1241 * submodules. This check can be skipped if the remote and refspec
1242 * won't be propagated due to the remote being unconfigured (e.g. a URL
1243 * instead of a remote name).
1245 if (remote->origin != REMOTE_UNCONFIGURED) {
1246 char *head;
1247 struct object_id head_oid;
1249 head = refs_resolve_refdup(get_main_ref_store(the_repository),
1250 "HEAD", 0, &head_oid, NULL);
1251 if (!head)
1252 die(_("Failed to resolve HEAD as a valid ref."));
1254 for (i = 0; i < needs_pushing.nr; i++)
1255 submodule_push_check(needs_pushing.items[i].string,
1256 head, remote, rs);
1257 free(head);
1260 /* Actually push the submodules */
1261 for (i = 0; i < needs_pushing.nr; i++) {
1262 const char *path = needs_pushing.items[i].string;
1263 fprintf(stderr, _("Pushing submodule '%s'\n"), path);
1264 if (!push_submodule(path, remote, rs,
1265 push_options, dry_run)) {
1266 fprintf(stderr, _("Unable to push submodule '%s'\n"), path);
1267 ret = 0;
1271 string_list_clear(&needs_pushing, 0);
1273 return ret;
1276 static int append_oid_to_array(const char *ref UNUSED,
1277 const char *referent UNUSED,
1278 const struct object_id *oid,
1279 int flags UNUSED, void *data)
1281 struct oid_array *array = data;
1282 oid_array_append(array, oid);
1283 return 0;
1286 void check_for_new_submodule_commits(struct object_id *oid)
1288 if (!initialized_fetch_ref_tips) {
1289 refs_for_each_ref(get_main_ref_store(the_repository),
1290 append_oid_to_array, &ref_tips_before_fetch);
1291 initialized_fetch_ref_tips = 1;
1294 oid_array_append(&ref_tips_after_fetch, oid);
1298 * Returns 1 if there is at least one submodule gitdir in
1299 * $GIT_DIR/modules and 0 otherwise. This follows
1300 * submodule_name_to_gitdir(), which looks for submodules in
1301 * $GIT_DIR/modules, not $GIT_COMMON_DIR.
1303 * A submodule can be moved to $GIT_DIR/modules manually by running "git
1304 * submodule absorbgitdirs", or it may be initialized there by "git
1305 * submodule update".
1307 static int repo_has_absorbed_submodules(struct repository *r)
1309 int ret;
1310 struct strbuf buf = STRBUF_INIT;
1312 strbuf_repo_git_path(&buf, r, "modules/");
1313 ret = file_exists(buf.buf) && !is_empty_dir(buf.buf);
1314 strbuf_release(&buf);
1315 return ret;
1318 static void calculate_changed_submodule_paths(struct repository *r,
1319 struct string_list *changed_submodule_names)
1321 struct strvec argv = STRVEC_INIT;
1322 struct string_list_item *name;
1324 /* No need to check if no submodules would be fetched */
1325 if (!submodule_from_path(r, NULL, NULL) &&
1326 !repo_has_absorbed_submodules(r))
1327 return;
1329 strvec_push(&argv, "--"); /* argv[0] program name */
1330 oid_array_for_each_unique(&ref_tips_after_fetch,
1331 append_oid_to_argv, &argv);
1332 strvec_push(&argv, "--not");
1333 oid_array_for_each_unique(&ref_tips_before_fetch,
1334 append_oid_to_argv, &argv);
1337 * Collect all submodules (whether checked out or not) for which new
1338 * commits have been recorded upstream in "changed_submodule_names".
1340 collect_changed_submodules(r, changed_submodule_names, &argv);
1342 for_each_string_list_item(name, changed_submodule_names) {
1343 struct changed_submodule_data *cs_data = name->util;
1344 const struct submodule *submodule;
1345 const char *path = NULL;
1347 submodule = submodule_from_name(r, null_oid(), name->string);
1348 if (submodule)
1349 path = submodule->path;
1350 else
1351 path = default_name_or_path(name->string);
1353 if (!path)
1354 continue;
1356 if (submodule_has_commits(r, path, null_oid(), &cs_data->new_commits)) {
1357 changed_submodule_data_clear(cs_data);
1358 *name->string = '\0';
1362 string_list_remove_empty_items(changed_submodule_names, 1);
1364 strvec_clear(&argv);
1365 oid_array_clear(&ref_tips_before_fetch);
1366 oid_array_clear(&ref_tips_after_fetch);
1367 initialized_fetch_ref_tips = 0;
1370 int submodule_touches_in_range(struct repository *r,
1371 struct object_id *excl_oid,
1372 struct object_id *incl_oid)
1374 struct string_list subs = STRING_LIST_INIT_DUP;
1375 struct strvec args = STRVEC_INIT;
1376 int ret;
1378 /* No need to check if there are no submodules configured */
1379 if (!submodule_from_path(r, NULL, NULL))
1380 return 0;
1382 strvec_push(&args, "--"); /* args[0] program name */
1383 strvec_push(&args, oid_to_hex(incl_oid));
1384 if (!is_null_oid(excl_oid)) {
1385 strvec_push(&args, "--not");
1386 strvec_push(&args, oid_to_hex(excl_oid));
1389 collect_changed_submodules(r, &subs, &args);
1390 ret = subs.nr;
1392 strvec_clear(&args);
1394 free_submodules_data(&subs);
1395 return ret;
1398 struct submodule_parallel_fetch {
1400 * The index of the last index entry processed by
1401 * get_fetch_task_from_index().
1403 int index_count;
1405 * The index of the last string_list entry processed by
1406 * get_fetch_task_from_changed().
1408 int changed_count;
1409 struct strvec args;
1410 struct repository *r;
1411 const char *prefix;
1412 int command_line_option;
1413 int default_option;
1414 int quiet;
1415 int result;
1418 * Names of submodules that have new commits. Generated by
1419 * walking the newly fetched superproject commits.
1421 struct string_list changed_submodule_names;
1423 * Names of submodules that have already been processed. Lets us
1424 * avoid fetching the same submodule more than once.
1426 struct string_list seen_submodule_names;
1428 /* Pending fetches by OIDs */
1429 struct fetch_task **oid_fetch_tasks;
1430 int oid_fetch_tasks_nr, oid_fetch_tasks_alloc;
1432 struct strbuf submodules_with_errors;
1434 #define SPF_INIT { \
1435 .args = STRVEC_INIT, \
1436 .changed_submodule_names = STRING_LIST_INIT_DUP, \
1437 .seen_submodule_names = STRING_LIST_INIT_DUP, \
1438 .submodules_with_errors = STRBUF_INIT, \
1441 static int get_fetch_recurse_config(const struct submodule *submodule,
1442 struct submodule_parallel_fetch *spf)
1444 if (spf->command_line_option != RECURSE_SUBMODULES_DEFAULT)
1445 return spf->command_line_option;
1447 if (submodule) {
1448 char *key;
1449 const char *value;
1451 int fetch_recurse = submodule->fetch_recurse;
1452 key = xstrfmt("submodule.%s.fetchRecurseSubmodules", submodule->name);
1453 if (!repo_config_get_string_tmp(spf->r, key, &value)) {
1454 fetch_recurse = parse_fetch_recurse_submodules_arg(key, value);
1456 free(key);
1458 if (fetch_recurse != RECURSE_SUBMODULES_NONE)
1459 /* local config overrules everything except commandline */
1460 return fetch_recurse;
1463 return spf->default_option;
1467 * Fetch in progress (if callback data) or
1468 * pending (if in oid_fetch_tasks in struct submodule_parallel_fetch)
1470 struct fetch_task {
1471 struct repository *repo;
1472 const struct submodule *sub;
1473 unsigned free_sub : 1; /* Do we need to free the submodule? */
1474 const char *default_argv; /* The default fetch mode. */
1475 struct strvec git_args; /* Args for the child git process. */
1477 struct oid_array *commits; /* Ensure these commits are fetched */
1481 * When a submodule is not defined in .gitmodules, we cannot access it
1482 * via the regular submodule-config. Create a fake submodule, which we can
1483 * work on.
1485 static const struct submodule *get_non_gitmodules_submodule(const char *path)
1487 struct submodule *ret = NULL;
1488 const char *name = default_name_or_path(path);
1490 if (!name)
1491 return NULL;
1493 ret = xmalloc(sizeof(*ret));
1494 memset(ret, 0, sizeof(*ret));
1495 ret->path = name;
1496 ret->name = name;
1498 return (const struct submodule *) ret;
1501 static void fetch_task_free(struct fetch_task *p)
1503 if (p->free_sub)
1504 free((void*)p->sub);
1505 p->free_sub = 0;
1506 p->sub = NULL;
1508 if (p->repo)
1509 repo_clear(p->repo);
1510 FREE_AND_NULL(p->repo);
1512 strvec_clear(&p->git_args);
1513 free(p);
1516 static struct repository *get_submodule_repo_for(struct repository *r,
1517 const char *path,
1518 const struct object_id *treeish_name)
1520 struct repository *ret = xmalloc(sizeof(*ret));
1522 if (repo_submodule_init(ret, r, path, treeish_name)) {
1523 free(ret);
1524 return NULL;
1527 return ret;
1530 static struct fetch_task *fetch_task_create(struct submodule_parallel_fetch *spf,
1531 const char *path,
1532 const struct object_id *treeish_name)
1534 struct fetch_task *task = xmalloc(sizeof(*task));
1535 memset(task, 0, sizeof(*task));
1537 if (validate_submodule_path(path) < 0)
1538 exit(128);
1540 task->sub = submodule_from_path(spf->r, treeish_name, path);
1542 if (!task->sub) {
1544 * No entry in .gitmodules? Technically not a submodule,
1545 * but historically we supported repositories that happen to be
1546 * in-place where a gitlink is. Keep supporting them.
1548 task->sub = get_non_gitmodules_submodule(path);
1549 if (!task->sub)
1550 goto cleanup;
1552 task->free_sub = 1;
1555 if (string_list_lookup(&spf->seen_submodule_names, task->sub->name))
1556 goto cleanup;
1558 switch (get_fetch_recurse_config(task->sub, spf))
1560 default:
1561 case RECURSE_SUBMODULES_DEFAULT:
1562 case RECURSE_SUBMODULES_ON_DEMAND:
1563 if (!task->sub ||
1564 !string_list_lookup(
1565 &spf->changed_submodule_names,
1566 task->sub->name))
1567 goto cleanup;
1568 task->default_argv = "on-demand";
1569 break;
1570 case RECURSE_SUBMODULES_ON:
1571 task->default_argv = "yes";
1572 break;
1573 case RECURSE_SUBMODULES_OFF:
1574 goto cleanup;
1577 task->repo = get_submodule_repo_for(spf->r, path, treeish_name);
1579 return task;
1581 cleanup:
1582 fetch_task_free(task);
1583 return NULL;
1586 static struct fetch_task *
1587 get_fetch_task_from_index(struct submodule_parallel_fetch *spf,
1588 struct strbuf *err)
1590 for (; spf->index_count < spf->r->index->cache_nr; spf->index_count++) {
1591 const struct cache_entry *ce =
1592 spf->r->index->cache[spf->index_count];
1593 struct fetch_task *task;
1595 if (!S_ISGITLINK(ce->ce_mode))
1596 continue;
1598 task = fetch_task_create(spf, ce->name, null_oid());
1599 if (!task)
1600 continue;
1602 if (task->repo) {
1603 if (!spf->quiet)
1604 strbuf_addf(err, _("Fetching submodule %s%s\n"),
1605 spf->prefix, ce->name);
1607 spf->index_count++;
1608 return task;
1609 } else {
1610 struct strbuf empty_submodule_path = STRBUF_INIT;
1612 fetch_task_free(task);
1615 * An empty directory is normal,
1616 * the submodule is not initialized
1618 strbuf_addf(&empty_submodule_path, "%s/%s/",
1619 spf->r->worktree,
1620 ce->name);
1621 if (S_ISGITLINK(ce->ce_mode) &&
1622 !is_empty_dir(empty_submodule_path.buf)) {
1623 spf->result = 1;
1624 strbuf_addf(err,
1625 _("Could not access submodule '%s'\n"),
1626 ce->name);
1628 strbuf_release(&empty_submodule_path);
1631 return NULL;
1634 static struct fetch_task *
1635 get_fetch_task_from_changed(struct submodule_parallel_fetch *spf,
1636 struct strbuf *err)
1638 for (; spf->changed_count < spf->changed_submodule_names.nr;
1639 spf->changed_count++) {
1640 struct string_list_item item =
1641 spf->changed_submodule_names.items[spf->changed_count];
1642 struct changed_submodule_data *cs_data = item.util;
1643 struct fetch_task *task;
1645 if (!is_tree_submodule_active(spf->r, cs_data->super_oid,cs_data->path))
1646 continue;
1648 task = fetch_task_create(spf, cs_data->path,
1649 cs_data->super_oid);
1650 if (!task)
1651 continue;
1653 if (!task->repo) {
1654 strbuf_addf(err, _("Could not access submodule '%s' at commit %s\n"),
1655 cs_data->path,
1656 repo_find_unique_abbrev(the_repository, cs_data->super_oid, DEFAULT_ABBREV));
1658 fetch_task_free(task);
1659 continue;
1662 if (!spf->quiet)
1663 strbuf_addf(err,
1664 _("Fetching submodule %s%s at commit %s\n"),
1665 spf->prefix, task->sub->path,
1666 repo_find_unique_abbrev(the_repository, cs_data->super_oid,
1667 DEFAULT_ABBREV));
1669 spf->changed_count++;
1671 * NEEDSWORK: Submodules set/unset a value for
1672 * core.worktree when they are populated/unpopulated by
1673 * "git checkout" (and similar commands, see
1674 * submodule_move_head() and
1675 * connect_work_tree_and_git_dir()), but if the
1676 * submodule is unpopulated in another way (e.g. "git
1677 * rm", "rm -r"), core.worktree will still be set even
1678 * though the directory doesn't exist, and the child
1679 * process will crash while trying to chdir into the
1680 * nonexistent directory.
1682 * In this case, we know that the submodule has no
1683 * working tree, so we can work around this by
1684 * setting "--work-tree=." (--bare does not work because
1685 * worktree settings take precedence over bare-ness).
1686 * However, this is not necessarily true in other cases,
1687 * so a generalized solution is still necessary.
1689 * Possible solutions:
1690 * - teach "git [add|rm]" to unset core.worktree and
1691 * discourage users from removing submodules without
1692 * using a Git command.
1693 * - teach submodule child processes to ignore stale
1694 * core.worktree values.
1696 strvec_push(&task->git_args, "--work-tree=.");
1697 return task;
1699 return NULL;
1702 static int get_next_submodule(struct child_process *cp, struct strbuf *err,
1703 void *data, void **task_cb)
1705 struct submodule_parallel_fetch *spf = data;
1706 struct fetch_task *task =
1707 get_fetch_task_from_index(spf, err);
1708 if (!task)
1709 task = get_fetch_task_from_changed(spf, err);
1711 if (task) {
1712 child_process_init(cp);
1713 cp->dir = task->repo->gitdir;
1714 prepare_submodule_repo_env_in_gitdir(&cp->env);
1715 cp->git_cmd = 1;
1716 strvec_init(&cp->args);
1717 if (task->git_args.nr)
1718 strvec_pushv(&cp->args, task->git_args.v);
1719 strvec_pushv(&cp->args, spf->args.v);
1720 strvec_push(&cp->args, task->default_argv);
1721 strvec_pushf(&cp->args, "--submodule-prefix=%s%s/",
1722 spf->prefix, task->sub->path);
1724 *task_cb = task;
1726 string_list_insert(&spf->seen_submodule_names, task->sub->name);
1727 return 1;
1730 if (spf->oid_fetch_tasks_nr) {
1731 struct fetch_task *task =
1732 spf->oid_fetch_tasks[spf->oid_fetch_tasks_nr - 1];
1733 spf->oid_fetch_tasks_nr--;
1735 child_process_init(cp);
1736 prepare_submodule_repo_env_in_gitdir(&cp->env);
1737 cp->git_cmd = 1;
1738 cp->dir = task->repo->gitdir;
1740 strvec_init(&cp->args);
1741 strvec_pushv(&cp->args, spf->args.v);
1742 strvec_push(&cp->args, "on-demand");
1743 strvec_pushf(&cp->args, "--submodule-prefix=%s%s/",
1744 spf->prefix, task->sub->path);
1746 /* NEEDSWORK: have get_default_remote from submodule--helper */
1747 strvec_push(&cp->args, "origin");
1748 oid_array_for_each_unique(task->commits,
1749 append_oid_to_argv, &cp->args);
1751 *task_cb = task;
1752 return 1;
1755 return 0;
1758 static int fetch_start_failure(struct strbuf *err UNUSED,
1759 void *cb, void *task_cb)
1761 struct submodule_parallel_fetch *spf = cb;
1762 struct fetch_task *task = task_cb;
1764 spf->result = 1;
1766 fetch_task_free(task);
1767 return 0;
1770 static int commit_missing_in_sub(const struct object_id *oid, void *data)
1772 struct repository *subrepo = data;
1774 enum object_type type = oid_object_info(subrepo, oid, NULL);
1776 return type != OBJ_COMMIT;
1779 static int fetch_finish(int retvalue, struct strbuf *err UNUSED,
1780 void *cb, void *task_cb)
1782 struct submodule_parallel_fetch *spf = cb;
1783 struct fetch_task *task = task_cb;
1785 struct string_list_item *it;
1786 struct changed_submodule_data *cs_data;
1788 if (!task || !task->sub)
1789 BUG("callback cookie bogus");
1791 if (retvalue) {
1793 * NEEDSWORK: This indicates that the overall fetch
1794 * failed, even though there may be a subsequent fetch
1795 * by commit hash that might work. It may be a good
1796 * idea to not indicate failure in this case, and only
1797 * indicate failure if the subsequent fetch fails.
1799 spf->result = 1;
1801 strbuf_addf(&spf->submodules_with_errors, "\t%s\n",
1802 task->sub->name);
1805 /* Is this the second time we process this submodule? */
1806 if (task->commits)
1807 goto out;
1809 it = string_list_lookup(&spf->changed_submodule_names, task->sub->name);
1810 if (!it)
1811 /* Could be an unchanged submodule, not contained in the list */
1812 goto out;
1814 cs_data = it->util;
1815 oid_array_filter(&cs_data->new_commits,
1816 commit_missing_in_sub,
1817 task->repo);
1819 /* Are there commits we want, but do not exist? */
1820 if (cs_data->new_commits.nr) {
1821 task->commits = &cs_data->new_commits;
1822 ALLOC_GROW(spf->oid_fetch_tasks,
1823 spf->oid_fetch_tasks_nr + 1,
1824 spf->oid_fetch_tasks_alloc);
1825 spf->oid_fetch_tasks[spf->oid_fetch_tasks_nr] = task;
1826 spf->oid_fetch_tasks_nr++;
1827 return 0;
1830 out:
1831 fetch_task_free(task);
1832 return 0;
1835 int fetch_submodules(struct repository *r,
1836 const struct strvec *options,
1837 const char *prefix, int command_line_option,
1838 int default_option,
1839 int quiet, int max_parallel_jobs)
1841 int i;
1842 struct submodule_parallel_fetch spf = SPF_INIT;
1843 const struct run_process_parallel_opts opts = {
1844 .tr2_category = "submodule",
1845 .tr2_label = "parallel/fetch",
1847 .processes = max_parallel_jobs,
1849 .get_next_task = get_next_submodule,
1850 .start_failure = fetch_start_failure,
1851 .task_finished = fetch_finish,
1852 .data = &spf,
1855 spf.r = r;
1856 spf.command_line_option = command_line_option;
1857 spf.default_option = default_option;
1858 spf.quiet = quiet;
1859 spf.prefix = prefix;
1861 if (!r->worktree)
1862 goto out;
1864 if (repo_read_index(r) < 0)
1865 die(_("index file corrupt"));
1867 strvec_push(&spf.args, "fetch");
1868 for (i = 0; i < options->nr; i++)
1869 strvec_push(&spf.args, options->v[i]);
1870 strvec_push(&spf.args, "--recurse-submodules-default");
1871 /* default value, "--submodule-prefix" and its value are added later */
1873 calculate_changed_submodule_paths(r, &spf.changed_submodule_names);
1874 string_list_sort(&spf.changed_submodule_names);
1875 run_processes_parallel(&opts);
1877 if (spf.submodules_with_errors.len > 0)
1878 fprintf(stderr, _("Errors during submodule fetch:\n%s"),
1879 spf.submodules_with_errors.buf);
1882 strvec_clear(&spf.args);
1883 out:
1884 free_submodules_data(&spf.changed_submodule_names);
1885 string_list_clear(&spf.seen_submodule_names, 0);
1886 strbuf_release(&spf.submodules_with_errors);
1887 free(spf.oid_fetch_tasks);
1888 return spf.result;
1891 unsigned is_submodule_modified(const char *path, int ignore_untracked)
1893 struct child_process cp = CHILD_PROCESS_INIT;
1894 struct strbuf buf = STRBUF_INIT;
1895 FILE *fp;
1896 unsigned dirty_submodule = 0;
1897 const char *git_dir;
1898 int ignore_cp_exit_code = 0;
1900 if (validate_submodule_path(path) < 0)
1901 exit(128);
1903 strbuf_addf(&buf, "%s/.git", path);
1904 git_dir = read_gitfile(buf.buf);
1905 if (!git_dir)
1906 git_dir = buf.buf;
1907 if (!is_git_directory(git_dir)) {
1908 if (is_directory(git_dir))
1909 die(_("'%s' not recognized as a git repository"), git_dir);
1910 strbuf_release(&buf);
1911 /* The submodule is not checked out, so it is not modified */
1912 return 0;
1914 strbuf_reset(&buf);
1916 strvec_pushl(&cp.args, "status", "--porcelain=2", NULL);
1917 if (ignore_untracked)
1918 strvec_push(&cp.args, "-uno");
1920 prepare_submodule_repo_env(&cp.env);
1921 cp.git_cmd = 1;
1922 cp.no_stdin = 1;
1923 cp.out = -1;
1924 cp.dir = path;
1925 if (start_command(&cp))
1926 die(_("Could not run 'git status --porcelain=2' in submodule %s"), path);
1928 fp = xfdopen(cp.out, "r");
1929 while (strbuf_getwholeline(&buf, fp, '\n') != EOF) {
1930 /* regular untracked files */
1931 if (buf.buf[0] == '?')
1932 dirty_submodule |= DIRTY_SUBMODULE_UNTRACKED;
1934 if (buf.buf[0] == 'u' ||
1935 buf.buf[0] == '1' ||
1936 buf.buf[0] == '2') {
1937 /* T = line type, XY = status, SSSS = submodule state */
1938 if (buf.len < strlen("T XY SSSS"))
1939 BUG("invalid status --porcelain=2 line %s",
1940 buf.buf);
1942 if (buf.buf[5] == 'S' && buf.buf[8] == 'U')
1943 /* nested untracked file */
1944 dirty_submodule |= DIRTY_SUBMODULE_UNTRACKED;
1946 if (buf.buf[0] == 'u' ||
1947 buf.buf[0] == '2' ||
1948 memcmp(buf.buf + 5, "S..U", 4))
1949 /* other change */
1950 dirty_submodule |= DIRTY_SUBMODULE_MODIFIED;
1953 if ((dirty_submodule & DIRTY_SUBMODULE_MODIFIED) &&
1954 ((dirty_submodule & DIRTY_SUBMODULE_UNTRACKED) ||
1955 ignore_untracked)) {
1957 * We're not interested in any further information from
1958 * the child any more, neither output nor its exit code.
1960 ignore_cp_exit_code = 1;
1961 break;
1964 fclose(fp);
1966 if (finish_command(&cp) && !ignore_cp_exit_code)
1967 die(_("'git status --porcelain=2' failed in submodule %s"), path);
1969 strbuf_release(&buf);
1970 return dirty_submodule;
1973 int submodule_uses_gitfile(const char *path)
1975 struct child_process cp = CHILD_PROCESS_INIT;
1976 struct strbuf buf = STRBUF_INIT;
1977 const char *git_dir;
1979 if (validate_submodule_path(path) < 0)
1980 exit(128);
1982 strbuf_addf(&buf, "%s/.git", path);
1983 git_dir = read_gitfile(buf.buf);
1984 if (!git_dir) {
1985 strbuf_release(&buf);
1986 return 0;
1988 strbuf_release(&buf);
1990 /* Now test that all nested submodules use a gitfile too */
1991 strvec_pushl(&cp.args,
1992 "submodule", "foreach", "--quiet", "--recursive",
1993 "test -f .git", NULL);
1995 prepare_submodule_repo_env(&cp.env);
1996 cp.git_cmd = 1;
1997 cp.no_stdin = 1;
1998 cp.no_stderr = 1;
1999 cp.no_stdout = 1;
2000 cp.dir = path;
2001 if (run_command(&cp))
2002 return 0;
2004 return 1;
2008 * Check if it is a bad idea to remove a submodule, i.e. if we'd lose data
2009 * when doing so.
2011 * Return 1 if we'd lose data, return 0 if the removal is fine,
2012 * and negative values for errors.
2014 int bad_to_remove_submodule(const char *path, unsigned flags)
2016 ssize_t len;
2017 struct child_process cp = CHILD_PROCESS_INIT;
2018 struct strbuf buf = STRBUF_INIT;
2019 int ret = 0;
2021 if (validate_submodule_path(path) < 0)
2022 exit(128);
2024 if (!file_exists(path) || is_empty_dir(path))
2025 return 0;
2027 if (!submodule_uses_gitfile(path))
2028 return 1;
2030 strvec_pushl(&cp.args, "status", "--porcelain",
2031 "--ignore-submodules=none", NULL);
2033 if (flags & SUBMODULE_REMOVAL_IGNORE_UNTRACKED)
2034 strvec_push(&cp.args, "-uno");
2035 else
2036 strvec_push(&cp.args, "-uall");
2038 if (!(flags & SUBMODULE_REMOVAL_IGNORE_IGNORED_UNTRACKED))
2039 strvec_push(&cp.args, "--ignored");
2041 prepare_submodule_repo_env(&cp.env);
2042 cp.git_cmd = 1;
2043 cp.no_stdin = 1;
2044 cp.out = -1;
2045 cp.dir = path;
2046 if (start_command(&cp)) {
2047 if (flags & SUBMODULE_REMOVAL_DIE_ON_ERROR)
2048 die(_("could not start 'git status' in submodule '%s'"),
2049 path);
2050 ret = -1;
2051 goto out;
2054 len = strbuf_read(&buf, cp.out, 1024);
2055 if (len > 2)
2056 ret = 1;
2057 close(cp.out);
2059 if (finish_command(&cp)) {
2060 if (flags & SUBMODULE_REMOVAL_DIE_ON_ERROR)
2061 die(_("could not run 'git status' in submodule '%s'"),
2062 path);
2063 ret = -1;
2065 out:
2066 strbuf_release(&buf);
2067 return ret;
2070 void submodule_unset_core_worktree(const struct submodule *sub)
2072 struct strbuf config_path = STRBUF_INIT;
2074 if (validate_submodule_path(sub->path) < 0)
2075 exit(128);
2077 submodule_name_to_gitdir(&config_path, the_repository, sub->name);
2078 strbuf_addstr(&config_path, "/config");
2080 if (git_config_set_in_file_gently(config_path.buf, "core.worktree", NULL, NULL))
2081 warning(_("Could not unset core.worktree setting in submodule '%s'"),
2082 sub->path);
2084 strbuf_release(&config_path);
2087 static int submodule_has_dirty_index(const struct submodule *sub)
2089 struct child_process cp = CHILD_PROCESS_INIT;
2091 if (validate_submodule_path(sub->path) < 0)
2092 exit(128);
2094 prepare_submodule_repo_env(&cp.env);
2096 cp.git_cmd = 1;
2097 strvec_pushl(&cp.args, "diff-index", "--quiet",
2098 "--cached", "HEAD", NULL);
2099 cp.no_stdin = 1;
2100 cp.no_stdout = 1;
2101 cp.dir = sub->path;
2102 if (start_command(&cp))
2103 die(_("could not recurse into submodule '%s'"), sub->path);
2105 return finish_command(&cp);
2108 static void submodule_reset_index(const char *path, const char *super_prefix)
2110 struct child_process cp = CHILD_PROCESS_INIT;
2112 if (validate_submodule_path(path) < 0)
2113 exit(128);
2115 prepare_submodule_repo_env(&cp.env);
2117 cp.git_cmd = 1;
2118 cp.no_stdin = 1;
2119 cp.dir = path;
2121 /* TODO: determine if this might overwright untracked files */
2122 strvec_pushl(&cp.args, "read-tree", "-u", "--reset", NULL);
2123 strvec_pushf(&cp.args, "--super-prefix=%s%s/",
2124 (super_prefix ? super_prefix : ""), path);
2126 strvec_push(&cp.args, empty_tree_oid_hex(the_repository->hash_algo));
2128 if (run_command(&cp))
2129 die(_("could not reset submodule index"));
2133 * Moves a submodule at a given path from a given head to another new head.
2134 * For edge cases (a submodule coming into existence or removing a submodule)
2135 * pass NULL for old or new respectively.
2137 int submodule_move_head(const char *path, const char *super_prefix,
2138 const char *old_head, const char *new_head,
2139 unsigned flags)
2141 int ret = 0;
2142 struct child_process cp = CHILD_PROCESS_INIT;
2143 const struct submodule *sub;
2144 int *error_code_ptr, error_code;
2146 if (!is_submodule_active(the_repository, path))
2147 return 0;
2149 if (flags & SUBMODULE_MOVE_HEAD_FORCE)
2151 * Pass non NULL pointer to is_submodule_populated_gently
2152 * to prevent die()-ing. We'll use connect_work_tree_and_git_dir
2153 * to fixup the submodule in the force case later.
2155 error_code_ptr = &error_code;
2156 else
2157 error_code_ptr = NULL;
2159 if (old_head && !is_submodule_populated_gently(path, error_code_ptr))
2160 return 0;
2162 sub = submodule_from_path(the_repository, null_oid(), path);
2164 if (!sub)
2165 BUG("could not get submodule information for '%s'", path);
2167 if (old_head && !(flags & SUBMODULE_MOVE_HEAD_FORCE)) {
2168 /* Check if the submodule has a dirty index. */
2169 if (submodule_has_dirty_index(sub))
2170 return error(_("submodule '%s' has dirty index"), path);
2173 if (!(flags & SUBMODULE_MOVE_HEAD_DRY_RUN)) {
2174 if (old_head) {
2175 if (!submodule_uses_gitfile(path))
2176 absorb_git_dir_into_superproject(path,
2177 super_prefix);
2178 else {
2179 char *dotgit = xstrfmt("%s/.git", path);
2180 char *git_dir = xstrdup(read_gitfile(dotgit));
2182 free(dotgit);
2183 if (validate_submodule_git_dir(git_dir,
2184 sub->name) < 0)
2185 die(_("refusing to create/use '%s' in "
2186 "another submodule's git dir"),
2187 git_dir);
2188 free(git_dir);
2190 } else {
2191 struct strbuf gitdir = STRBUF_INIT;
2192 submodule_name_to_gitdir(&gitdir, the_repository,
2193 sub->name);
2194 if (validate_submodule_git_dir(gitdir.buf,
2195 sub->name) < 0)
2196 die(_("refusing to create/use '%s' in another "
2197 "submodule's git dir"),
2198 gitdir.buf);
2199 connect_work_tree_and_git_dir(path, gitdir.buf, 0);
2200 strbuf_release(&gitdir);
2202 /* make sure the index is clean as well */
2203 submodule_reset_index(path, super_prefix);
2206 if (old_head && (flags & SUBMODULE_MOVE_HEAD_FORCE)) {
2207 struct strbuf gitdir = STRBUF_INIT;
2208 submodule_name_to_gitdir(&gitdir, the_repository,
2209 sub->name);
2210 connect_work_tree_and_git_dir(path, gitdir.buf, 1);
2211 strbuf_release(&gitdir);
2215 prepare_submodule_repo_env(&cp.env);
2217 cp.git_cmd = 1;
2218 cp.no_stdin = 1;
2219 cp.dir = path;
2221 strvec_pushl(&cp.args, "read-tree", "--recurse-submodules", NULL);
2222 strvec_pushf(&cp.args, "--super-prefix=%s%s/",
2223 (super_prefix ? super_prefix : ""), path);
2225 if (flags & SUBMODULE_MOVE_HEAD_DRY_RUN)
2226 strvec_push(&cp.args, "-n");
2227 else
2228 strvec_push(&cp.args, "-u");
2230 if (flags & SUBMODULE_MOVE_HEAD_FORCE)
2231 strvec_push(&cp.args, "--reset");
2232 else
2233 strvec_push(&cp.args, "-m");
2235 if (!(flags & SUBMODULE_MOVE_HEAD_FORCE))
2236 strvec_push(&cp.args, old_head ? old_head : empty_tree_oid_hex(the_repository->hash_algo));
2238 strvec_push(&cp.args, new_head ? new_head : empty_tree_oid_hex(the_repository->hash_algo));
2240 if (run_command(&cp)) {
2241 ret = error(_("Submodule '%s' could not be updated."), path);
2242 goto out;
2245 if (!(flags & SUBMODULE_MOVE_HEAD_DRY_RUN)) {
2246 if (new_head) {
2247 child_process_init(&cp);
2248 /* also set the HEAD accordingly */
2249 cp.git_cmd = 1;
2250 cp.no_stdin = 1;
2251 cp.dir = path;
2253 prepare_submodule_repo_env(&cp.env);
2254 strvec_pushl(&cp.args, "update-ref", "HEAD",
2255 "--no-deref", new_head, NULL);
2257 if (run_command(&cp)) {
2258 ret = -1;
2259 goto out;
2261 } else {
2262 struct strbuf sb = STRBUF_INIT;
2264 strbuf_addf(&sb, "%s/.git", path);
2265 unlink_or_warn(sb.buf);
2266 strbuf_release(&sb);
2268 if (is_empty_dir(path))
2269 rmdir_or_warn(path);
2271 submodule_unset_core_worktree(sub);
2274 out:
2275 return ret;
2278 int validate_submodule_git_dir(char *git_dir, const char *submodule_name)
2280 size_t len = strlen(git_dir), suffix_len = strlen(submodule_name);
2281 char *p;
2282 int ret = 0;
2284 if (len <= suffix_len || (p = git_dir + len - suffix_len)[-1] != '/' ||
2285 strcmp(p, submodule_name))
2286 BUG("submodule name '%s' not a suffix of git dir '%s'",
2287 submodule_name, git_dir);
2290 * We prevent the contents of sibling submodules' git directories to
2291 * clash.
2293 * Example: having a submodule named `hippo` and another one named
2294 * `hippo/hooks` would result in the git directories
2295 * `.git/modules/hippo/` and `.git/modules/hippo/hooks/`, respectively,
2296 * but the latter directory is already designated to contain the hooks
2297 * of the former.
2299 for (; *p; p++) {
2300 if (is_dir_sep(*p)) {
2301 char c = *p;
2303 *p = '\0';
2304 if (is_git_directory(git_dir))
2305 ret = -1;
2306 *p = c;
2308 if (ret < 0)
2309 return error(_("submodule git dir '%s' is "
2310 "inside git dir '%.*s'"),
2311 git_dir,
2312 (int)(p - git_dir), git_dir);
2316 return 0;
2319 int validate_submodule_path(const char *path)
2321 char *p = xstrdup(path);
2322 struct stat st;
2323 int i, ret = 0;
2324 char sep;
2326 for (i = 0; !ret && p[i]; i++) {
2327 if (!is_dir_sep(p[i]))
2328 continue;
2330 sep = p[i];
2331 p[i] = '\0';
2332 /* allow missing components, but no symlinks */
2333 ret = lstat(p, &st) || !S_ISLNK(st.st_mode) ? 0 : -1;
2334 p[i] = sep;
2335 if (ret)
2336 error(_("expected '%.*s' in submodule path '%s' not to "
2337 "be a symbolic link"), i, p, p);
2339 if (!lstat(p, &st) && S_ISLNK(st.st_mode))
2340 ret = error(_("expected submodule path '%s' not to be a "
2341 "symbolic link"), p);
2342 free(p);
2343 return ret;
2348 * Embeds a single submodules git directory into the superprojects git dir,
2349 * non recursively.
2351 static void relocate_single_git_dir_into_superproject(const char *path,
2352 const char *super_prefix)
2354 char *old_git_dir = NULL, *real_old_git_dir = NULL, *real_new_git_dir = NULL;
2355 struct strbuf new_gitdir = STRBUF_INIT;
2356 const struct submodule *sub;
2358 if (validate_submodule_path(path) < 0)
2359 exit(128);
2361 if (submodule_uses_worktrees(path))
2362 die(_("relocate_gitdir for submodule '%s' with "
2363 "more than one worktree not supported"), path);
2365 old_git_dir = xstrfmt("%s/.git", path);
2366 if (read_gitfile(old_git_dir))
2367 /* If it is an actual gitfile, it doesn't need migration. */
2368 return;
2370 real_old_git_dir = real_pathdup(old_git_dir, 1);
2372 sub = submodule_from_path(the_repository, null_oid(), path);
2373 if (!sub)
2374 die(_("could not lookup name for submodule '%s'"), path);
2376 submodule_name_to_gitdir(&new_gitdir, the_repository, sub->name);
2377 if (validate_submodule_git_dir(new_gitdir.buf, sub->name) < 0)
2378 die(_("refusing to move '%s' into an existing git dir"),
2379 real_old_git_dir);
2380 if (safe_create_leading_directories_const(new_gitdir.buf) < 0)
2381 die(_("could not create directory '%s'"), new_gitdir.buf);
2382 real_new_git_dir = real_pathdup(new_gitdir.buf, 1);
2384 fprintf(stderr, _("Migrating git directory of '%s%s' from\n'%s' to\n'%s'\n"),
2385 super_prefix ? super_prefix : "", path,
2386 real_old_git_dir, real_new_git_dir);
2388 relocate_gitdir(path, real_old_git_dir, real_new_git_dir);
2390 free(old_git_dir);
2391 free(real_old_git_dir);
2392 free(real_new_git_dir);
2393 strbuf_release(&new_gitdir);
2396 static void absorb_git_dir_into_superproject_recurse(const char *path,
2397 const char *super_prefix)
2400 struct child_process cp = CHILD_PROCESS_INIT;
2402 if (validate_submodule_path(path) < 0)
2403 exit(128);
2405 cp.dir = path;
2406 cp.git_cmd = 1;
2407 cp.no_stdin = 1;
2408 strvec_pushl(&cp.args, "submodule--helper",
2409 "absorbgitdirs", NULL);
2410 strvec_pushf(&cp.args, "--super-prefix=%s%s/", super_prefix ?
2411 super_prefix : "", path);
2413 prepare_submodule_repo_env(&cp.env);
2414 if (run_command(&cp))
2415 die(_("could not recurse into submodule '%s'"), path);
2419 * Migrate the git directory of the submodule given by path from
2420 * having its git directory within the working tree to the git dir nested
2421 * in its superprojects git dir under modules/.
2423 void absorb_git_dir_into_superproject(const char *path,
2424 const char *super_prefix)
2426 int err_code;
2427 const char *sub_git_dir;
2428 struct strbuf gitdir = STRBUF_INIT;
2430 if (validate_submodule_path(path) < 0)
2431 exit(128);
2433 strbuf_addf(&gitdir, "%s/.git", path);
2434 sub_git_dir = resolve_gitdir_gently(gitdir.buf, &err_code);
2436 /* Not populated? */
2437 if (!sub_git_dir) {
2438 const struct submodule *sub;
2439 struct strbuf sub_gitdir = STRBUF_INIT;
2441 if (err_code == READ_GITFILE_ERR_STAT_FAILED) {
2442 /* unpopulated as expected */
2443 strbuf_release(&gitdir);
2444 return;
2447 if (err_code != READ_GITFILE_ERR_NOT_A_REPO)
2448 /* We don't know what broke here. */
2449 read_gitfile_error_die(err_code, path, NULL);
2452 * Maybe populated, but no git directory was found?
2453 * This can happen if the superproject is a submodule
2454 * itself and was just absorbed. The absorption of the
2455 * superproject did not rewrite the git file links yet,
2456 * fix it now.
2458 sub = submodule_from_path(the_repository, null_oid(), path);
2459 if (!sub)
2460 die(_("could not lookup name for submodule '%s'"), path);
2461 submodule_name_to_gitdir(&sub_gitdir, the_repository, sub->name);
2462 connect_work_tree_and_git_dir(path, sub_gitdir.buf, 0);
2463 strbuf_release(&sub_gitdir);
2464 } else {
2465 /* Is it already absorbed into the superprojects git dir? */
2466 char *real_sub_git_dir = real_pathdup(sub_git_dir, 1);
2467 char *real_common_git_dir = real_pathdup(get_git_common_dir(), 1);
2469 if (!starts_with(real_sub_git_dir, real_common_git_dir))
2470 relocate_single_git_dir_into_superproject(path, super_prefix);
2472 free(real_sub_git_dir);
2473 free(real_common_git_dir);
2475 strbuf_release(&gitdir);
2477 absorb_git_dir_into_superproject_recurse(path, super_prefix);
2480 int get_superproject_working_tree(struct strbuf *buf)
2482 struct child_process cp = CHILD_PROCESS_INIT;
2483 struct strbuf sb = STRBUF_INIT;
2484 struct strbuf one_up = STRBUF_INIT;
2485 char *cwd = xgetcwd();
2486 int ret = 0;
2487 const char *subpath;
2488 int code;
2489 ssize_t len;
2491 if (!is_inside_work_tree())
2493 * FIXME:
2494 * We might have a superproject, but it is harder
2495 * to determine.
2497 return 0;
2499 if (!strbuf_realpath(&one_up, "../", 0))
2500 return 0;
2502 subpath = relative_path(cwd, one_up.buf, &sb);
2503 strbuf_release(&one_up);
2505 prepare_submodule_repo_env(&cp.env);
2506 strvec_pop(&cp.env);
2508 strvec_pushl(&cp.args, "--literal-pathspecs", "-C", "..",
2509 "ls-files", "-z", "--stage", "--full-name", "--",
2510 subpath, NULL);
2511 strbuf_reset(&sb);
2513 cp.no_stdin = 1;
2514 cp.no_stderr = 1;
2515 cp.out = -1;
2516 cp.git_cmd = 1;
2518 if (start_command(&cp))
2519 die(_("could not start ls-files in .."));
2521 len = strbuf_read(&sb, cp.out, PATH_MAX);
2522 close(cp.out);
2524 if (starts_with(sb.buf, "160000")) {
2525 int super_sub_len;
2526 int cwd_len = strlen(cwd);
2527 char *super_sub, *super_wt;
2530 * There is a superproject having this repo as a submodule.
2531 * The format is <mode> SP <hash> SP <stage> TAB <full name> \0,
2532 * We're only interested in the name after the tab.
2534 super_sub = strchr(sb.buf, '\t') + 1;
2535 super_sub_len = strlen(super_sub);
2537 if (super_sub_len > cwd_len ||
2538 strcmp(&cwd[cwd_len - super_sub_len], super_sub))
2539 BUG("returned path string doesn't match cwd?");
2541 super_wt = xstrdup(cwd);
2542 super_wt[cwd_len - super_sub_len] = '\0';
2544 strbuf_realpath(buf, super_wt, 1);
2545 ret = 1;
2546 free(super_wt);
2548 free(cwd);
2549 strbuf_release(&sb);
2551 code = finish_command(&cp);
2553 if (code == 128)
2554 /* '../' is not a git repository */
2555 return 0;
2556 if (code == 0 && len == 0)
2557 /* There is an unrelated git repository at '../' */
2558 return 0;
2559 if (code)
2560 die(_("ls-tree returned unexpected return code %d"), code);
2562 return ret;
2566 * Put the gitdir for a submodule (given relative to the main
2567 * repository worktree) into `buf`, or return -1 on error.
2569 int submodule_to_gitdir(struct strbuf *buf, const char *submodule)
2571 const struct submodule *sub;
2572 const char *git_dir;
2573 int ret = 0;
2575 if (validate_submodule_path(submodule) < 0)
2576 exit(128);
2578 strbuf_reset(buf);
2579 strbuf_addstr(buf, submodule);
2580 strbuf_complete(buf, '/');
2581 strbuf_addstr(buf, ".git");
2583 git_dir = read_gitfile(buf->buf);
2584 if (git_dir) {
2585 strbuf_reset(buf);
2586 strbuf_addstr(buf, git_dir);
2588 if (!is_git_directory(buf->buf)) {
2589 sub = submodule_from_path(the_repository, null_oid(),
2590 submodule);
2591 if (!sub) {
2592 ret = -1;
2593 goto cleanup;
2595 strbuf_reset(buf);
2596 submodule_name_to_gitdir(buf, the_repository, sub->name);
2599 cleanup:
2600 return ret;
2603 void submodule_name_to_gitdir(struct strbuf *buf, struct repository *r,
2604 const char *submodule_name)
2607 * NEEDSWORK: The current way of mapping a submodule's name to
2608 * its location in .git/modules/ has problems with some naming
2609 * schemes. For example, if a submodule is named "foo" and
2610 * another is named "foo/bar" (whether present in the same
2611 * superproject commit or not - the problem will arise if both
2612 * superproject commits have been checked out at any point in
2613 * time), or if two submodule names only have different cases in
2614 * a case-insensitive filesystem.
2616 * There are several solutions, including encoding the path in
2617 * some way, introducing a submodule.<name>.gitdir config in
2618 * .git/config (not .gitmodules) that allows overriding what the
2619 * gitdir of a submodule would be (and teach Git, upon noticing
2620 * a clash, to automatically determine a non-clashing name and
2621 * to write such a config), or introducing a
2622 * submodule.<name>.gitdir config in .gitmodules that repo
2623 * administrators can explicitly set. Nothing has been decided,
2624 * so for now, just append the name at the end of the path.
2626 strbuf_repo_git_path(buf, r, "modules/");
2627 strbuf_addstr(buf, submodule_name);