builtin/reflog: introduce subcommand to list reflogs
[alt-git.git] / submodule.c
blob213da79f66116f3db835036140affb98406a934a
1 #include "git-compat-util.h"
2 #include "abspath.h"
3 #include "repository.h"
4 #include "config.h"
5 #include "submodule-config.h"
6 #include "submodule.h"
7 #include "dir.h"
8 #include "diff.h"
9 #include "commit.h"
10 #include "environment.h"
11 #include "gettext.h"
12 #include "hex.h"
13 #include "revision.h"
14 #include "run-command.h"
15 #include "diffcore.h"
16 #include "refs.h"
17 #include "string-list.h"
18 #include "oid-array.h"
19 #include "strvec.h"
20 #include "thread-utils.h"
21 #include "path.h"
22 #include "remote.h"
23 #include "worktree.h"
24 #include "parse-options.h"
25 #include "object-file.h"
26 #include "object-name.h"
27 #include "object-store-ll.h"
28 #include "commit-reach.h"
29 #include "read-cache-ll.h"
30 #include "setup.h"
31 #include "trace2.h"
33 static int config_update_recurse_submodules = RECURSE_SUBMODULES_OFF;
34 static int initialized_fetch_ref_tips;
35 static struct oid_array ref_tips_before_fetch;
36 static struct oid_array ref_tips_after_fetch;
39 * Check if the .gitmodules file is unmerged. Parsing of the .gitmodules file
40 * will be disabled because we can't guess what might be configured in
41 * .gitmodules unless the user resolves the conflict.
43 int is_gitmodules_unmerged(struct index_state *istate)
45 int pos = index_name_pos(istate, GITMODULES_FILE, strlen(GITMODULES_FILE));
46 if (pos < 0) { /* .gitmodules not found or isn't merged */
47 pos = -1 - pos;
48 if (istate->cache_nr > pos) { /* there is a .gitmodules */
49 const struct cache_entry *ce = istate->cache[pos];
50 if (ce_namelen(ce) == strlen(GITMODULES_FILE) &&
51 !strcmp(ce->name, GITMODULES_FILE))
52 return 1;
56 return 0;
60 * Check if the .gitmodules file is safe to write.
62 * Writing to the .gitmodules file requires that the file exists in the
63 * working tree or, if it doesn't, that a brand new .gitmodules file is going
64 * to be created (i.e. it's neither in the index nor in the current branch).
66 * It is not safe to write to .gitmodules if it's not in the working tree but
67 * it is in the index or in the current branch, because writing new values
68 * (and staging them) would blindly overwrite ALL the old content.
70 int is_writing_gitmodules_ok(void)
72 struct object_id oid;
73 return file_exists(GITMODULES_FILE) ||
74 (repo_get_oid(the_repository, GITMODULES_INDEX, &oid) < 0 && repo_get_oid(the_repository, GITMODULES_HEAD, &oid) < 0);
78 * Check if the .gitmodules file has unstaged modifications. This must be
79 * checked before allowing modifications to the .gitmodules file with the
80 * intention to stage them later, because when continuing we would stage the
81 * modifications the user didn't stage herself too. That might change in a
82 * future version when we learn to stage the changes we do ourselves without
83 * staging any previous modifications.
85 int is_staging_gitmodules_ok(struct index_state *istate)
87 int pos = index_name_pos(istate, GITMODULES_FILE, strlen(GITMODULES_FILE));
89 if ((pos >= 0) && (pos < istate->cache_nr)) {
90 struct stat st;
91 if (lstat(GITMODULES_FILE, &st) == 0 &&
92 ie_modified(istate, istate->cache[pos], &st, 0) & DATA_CHANGED)
93 return 0;
96 return 1;
99 static int for_each_remote_ref_submodule(const char *submodule,
100 each_ref_fn fn, void *cb_data)
102 return refs_for_each_remote_ref(get_submodule_ref_store(submodule),
103 fn, cb_data);
107 * Try to update the "path" entry in the "submodule.<name>" section of the
108 * .gitmodules file. Return 0 only if a .gitmodules file was found, a section
109 * with the correct path=<oldpath> setting was found and we could update it.
111 int update_path_in_gitmodules(const char *oldpath, const char *newpath)
113 struct strbuf entry = STRBUF_INIT;
114 const struct submodule *submodule;
115 int ret;
117 if (!file_exists(GITMODULES_FILE)) /* Do nothing without .gitmodules */
118 return -1;
120 if (is_gitmodules_unmerged(the_repository->index))
121 die(_("Cannot change unmerged .gitmodules, resolve merge conflicts first"));
123 submodule = submodule_from_path(the_repository, null_oid(), oldpath);
124 if (!submodule || !submodule->name) {
125 warning(_("Could not find section in .gitmodules where path=%s"), oldpath);
126 return -1;
128 strbuf_addstr(&entry, "submodule.");
129 strbuf_addstr(&entry, submodule->name);
130 strbuf_addstr(&entry, ".path");
131 ret = config_set_in_gitmodules_file_gently(entry.buf, newpath);
132 strbuf_release(&entry);
133 return ret;
137 * Try to remove the "submodule.<name>" section from .gitmodules where the given
138 * path is configured. Return 0 only if a .gitmodules file was found, a section
139 * with the correct path=<path> setting was found and we could remove it.
141 int remove_path_from_gitmodules(const char *path)
143 struct strbuf sect = STRBUF_INIT;
144 const struct submodule *submodule;
146 if (!file_exists(GITMODULES_FILE)) /* Do nothing without .gitmodules */
147 return -1;
149 if (is_gitmodules_unmerged(the_repository->index))
150 die(_("Cannot change unmerged .gitmodules, resolve merge conflicts first"));
152 submodule = submodule_from_path(the_repository, null_oid(), path);
153 if (!submodule || !submodule->name) {
154 warning(_("Could not find section in .gitmodules where path=%s"), path);
155 return -1;
157 strbuf_addstr(&sect, "submodule.");
158 strbuf_addstr(&sect, submodule->name);
159 if (git_config_rename_section_in_file(GITMODULES_FILE, sect.buf, NULL) < 0) {
160 /* Maybe the user already did that, don't error out here */
161 warning(_("Could not remove .gitmodules entry for %s"), path);
162 strbuf_release(&sect);
163 return -1;
165 strbuf_release(&sect);
166 return 0;
169 void stage_updated_gitmodules(struct index_state *istate)
171 if (add_file_to_index(istate, GITMODULES_FILE, 0))
172 die(_("staging updated .gitmodules failed"));
175 static struct string_list added_submodule_odb_paths = STRING_LIST_INIT_NODUP;
177 void add_submodule_odb_by_path(const char *path)
179 string_list_insert(&added_submodule_odb_paths, xstrdup(path));
182 int register_all_submodule_odb_as_alternates(void)
184 int i;
185 int ret = added_submodule_odb_paths.nr;
187 for (i = 0; i < added_submodule_odb_paths.nr; i++)
188 add_to_alternates_memory(added_submodule_odb_paths.items[i].string);
189 if (ret) {
190 string_list_clear(&added_submodule_odb_paths, 0);
191 trace2_data_intmax("submodule", the_repository,
192 "register_all_submodule_odb_as_alternates/registered", ret);
193 if (git_env_bool("GIT_TEST_FATAL_REGISTER_SUBMODULE_ODB", 0))
194 BUG("register_all_submodule_odb_as_alternates() called");
196 return ret;
199 void set_diffopt_flags_from_submodule_config(struct diff_options *diffopt,
200 const char *path)
202 const struct submodule *submodule = submodule_from_path(the_repository,
203 null_oid(),
204 path);
205 if (submodule) {
206 const char *ignore;
207 char *key;
209 key = xstrfmt("submodule.%s.ignore", submodule->name);
210 if (repo_config_get_string_tmp(the_repository, key, &ignore))
211 ignore = submodule->ignore;
212 free(key);
214 if (ignore)
215 handle_ignore_submodules_arg(diffopt, ignore);
216 else if (is_gitmodules_unmerged(the_repository->index))
217 diffopt->flags.ignore_submodules = 1;
221 /* Cheap function that only determines if we're interested in submodules at all */
222 int git_default_submodule_config(const char *var, const char *value,
223 void *cb UNUSED)
225 if (!strcmp(var, "submodule.recurse")) {
226 int v = git_config_bool(var, value) ?
227 RECURSE_SUBMODULES_ON : RECURSE_SUBMODULES_OFF;
228 config_update_recurse_submodules = v;
230 return 0;
233 int option_parse_recurse_submodules_worktree_updater(const struct option *opt,
234 const char *arg, int unset)
236 if (unset) {
237 config_update_recurse_submodules = RECURSE_SUBMODULES_OFF;
238 return 0;
240 if (arg)
241 config_update_recurse_submodules =
242 parse_update_recurse_submodules_arg(opt->long_name,
243 arg);
244 else
245 config_update_recurse_submodules = RECURSE_SUBMODULES_ON;
247 return 0;
251 * Determine if a submodule has been initialized at a given 'path'
254 * NEEDSWORK: Emit a warning if submodule.active exists, but is valueless,
255 * ie, the config looks like: "[submodule] active\n".
256 * Since that is an invalid pathspec, we should inform the user.
258 int is_tree_submodule_active(struct repository *repo,
259 const struct object_id *treeish_name,
260 const char *path)
262 int ret = 0;
263 char *key = NULL;
264 char *value = NULL;
265 const struct string_list *sl;
266 const struct submodule *module;
268 module = submodule_from_path(repo, treeish_name, path);
270 /* early return if there isn't a path->module mapping */
271 if (!module)
272 return 0;
274 /* submodule.<name>.active is set */
275 key = xstrfmt("submodule.%s.active", module->name);
276 if (!repo_config_get_bool(repo, key, &ret)) {
277 free(key);
278 return ret;
280 free(key);
282 /* submodule.active is set */
283 if (!repo_config_get_string_multi(repo, "submodule.active", &sl)) {
284 struct pathspec ps;
285 struct strvec args = STRVEC_INIT;
286 const struct string_list_item *item;
288 for_each_string_list_item(item, sl) {
289 strvec_push(&args, item->string);
292 parse_pathspec(&ps, 0, 0, NULL, args.v);
293 ret = match_pathspec(repo->index, &ps, path, strlen(path), 0, NULL, 1);
295 strvec_clear(&args);
296 clear_pathspec(&ps);
297 return ret;
300 /* fallback to checking if the URL is set */
301 key = xstrfmt("submodule.%s.url", module->name);
302 ret = !repo_config_get_string(repo, key, &value);
304 free(value);
305 free(key);
306 return ret;
309 int is_submodule_active(struct repository *repo, const char *path)
311 return is_tree_submodule_active(repo, null_oid(), path);
314 int is_submodule_populated_gently(const char *path, int *return_error_code)
316 int ret = 0;
317 char *gitdir = xstrfmt("%s/.git", path);
319 if (resolve_gitdir_gently(gitdir, return_error_code))
320 ret = 1;
322 free(gitdir);
323 return ret;
327 * Dies if the provided 'prefix' corresponds to an unpopulated submodule
329 void die_in_unpopulated_submodule(struct index_state *istate,
330 const char *prefix)
332 int i, prefixlen;
334 if (!prefix)
335 return;
337 prefixlen = strlen(prefix);
339 for (i = 0; i < istate->cache_nr; i++) {
340 struct cache_entry *ce = istate->cache[i];
341 int ce_len = ce_namelen(ce);
343 if (!S_ISGITLINK(ce->ce_mode))
344 continue;
345 if (prefixlen <= ce_len)
346 continue;
347 if (strncmp(ce->name, prefix, ce_len))
348 continue;
349 if (prefix[ce_len] != '/')
350 continue;
352 die(_("in unpopulated submodule '%s'"), ce->name);
357 * Dies if any paths in the provided pathspec descends into a submodule
359 void die_path_inside_submodule(struct index_state *istate,
360 const struct pathspec *ps)
362 int i, j;
364 for (i = 0; i < istate->cache_nr; i++) {
365 struct cache_entry *ce = istate->cache[i];
366 int ce_len = ce_namelen(ce);
368 if (!S_ISGITLINK(ce->ce_mode))
369 continue;
371 for (j = 0; j < ps->nr ; j++) {
372 const struct pathspec_item *item = &ps->items[j];
374 if (item->len <= ce_len)
375 continue;
376 if (item->match[ce_len] != '/')
377 continue;
378 if (strncmp(ce->name, item->match, ce_len))
379 continue;
380 if (item->len == ce_len + 1)
381 continue;
383 die(_("Pathspec '%s' is in submodule '%.*s'"),
384 item->original, ce_len, ce->name);
389 enum submodule_update_type parse_submodule_update_type(const char *value)
391 if (!strcmp(value, "none"))
392 return SM_UPDATE_NONE;
393 else if (!strcmp(value, "checkout"))
394 return SM_UPDATE_CHECKOUT;
395 else if (!strcmp(value, "rebase"))
396 return SM_UPDATE_REBASE;
397 else if (!strcmp(value, "merge"))
398 return SM_UPDATE_MERGE;
399 else if (*value == '!')
400 return SM_UPDATE_COMMAND;
401 else
402 return SM_UPDATE_UNSPECIFIED;
405 int parse_submodule_update_strategy(const char *value,
406 struct submodule_update_strategy *dst)
408 enum submodule_update_type type;
410 free((void*)dst->command);
411 dst->command = NULL;
413 type = parse_submodule_update_type(value);
414 if (type == SM_UPDATE_UNSPECIFIED)
415 return -1;
417 dst->type = type;
418 if (type == SM_UPDATE_COMMAND)
419 dst->command = xstrdup(value + 1);
421 return 0;
424 const char *submodule_update_type_to_string(enum submodule_update_type type)
426 switch (type) {
427 case SM_UPDATE_CHECKOUT:
428 return "checkout";
429 case SM_UPDATE_MERGE:
430 return "merge";
431 case SM_UPDATE_REBASE:
432 return "rebase";
433 case SM_UPDATE_NONE:
434 return "none";
435 case SM_UPDATE_UNSPECIFIED:
436 case SM_UPDATE_COMMAND:
437 BUG("init_submodule() should handle type %d", type);
438 default:
439 BUG("unexpected update strategy type: %d", type);
443 void handle_ignore_submodules_arg(struct diff_options *diffopt,
444 const char *arg)
446 diffopt->flags.ignore_submodule_set = 1;
447 diffopt->flags.ignore_submodules = 0;
448 diffopt->flags.ignore_untracked_in_submodules = 0;
449 diffopt->flags.ignore_dirty_submodules = 0;
451 if (!strcmp(arg, "all"))
452 diffopt->flags.ignore_submodules = 1;
453 else if (!strcmp(arg, "untracked"))
454 diffopt->flags.ignore_untracked_in_submodules = 1;
455 else if (!strcmp(arg, "dirty"))
456 diffopt->flags.ignore_dirty_submodules = 1;
457 else if (strcmp(arg, "none"))
458 die(_("bad --ignore-submodules argument: %s"), arg);
460 * Please update _git_status() in git-completion.bash when you
461 * add new options
465 static int prepare_submodule_diff_summary(struct repository *r, struct rev_info *rev,
466 const char *path,
467 struct commit *left, struct commit *right,
468 struct commit_list *merge_bases)
470 struct commit_list *list;
472 repo_init_revisions(r, rev, NULL);
473 setup_revisions(0, NULL, rev, NULL);
474 rev->left_right = 1;
475 rev->first_parent_only = 1;
476 left->object.flags |= SYMMETRIC_LEFT;
477 add_pending_object(rev, &left->object, path);
478 add_pending_object(rev, &right->object, path);
479 for (list = merge_bases; list; list = list->next) {
480 list->item->object.flags |= UNINTERESTING;
481 add_pending_object(rev, &list->item->object,
482 oid_to_hex(&list->item->object.oid));
484 return prepare_revision_walk(rev);
487 static void print_submodule_diff_summary(struct repository *r, struct rev_info *rev, struct diff_options *o)
489 static const char format[] = " %m %s";
490 struct strbuf sb = STRBUF_INIT;
491 struct commit *commit;
493 while ((commit = get_revision(rev))) {
494 struct pretty_print_context ctx = {0};
495 ctx.date_mode = rev->date_mode;
496 ctx.output_encoding = get_log_output_encoding();
497 strbuf_setlen(&sb, 0);
498 repo_format_commit_message(r, commit, format, &sb,
499 &ctx);
500 strbuf_addch(&sb, '\n');
501 if (commit->object.flags & SYMMETRIC_LEFT)
502 diff_emit_submodule_del(o, sb.buf);
503 else
504 diff_emit_submodule_add(o, sb.buf);
506 strbuf_release(&sb);
509 void prepare_submodule_repo_env(struct strvec *out)
511 prepare_other_repo_env(out, DEFAULT_GIT_DIR_ENVIRONMENT);
514 static void prepare_submodule_repo_env_in_gitdir(struct strvec *out)
516 prepare_other_repo_env(out, ".");
520 * Initialize a repository struct for a submodule based on the provided 'path'.
522 * Returns the repository struct on success,
523 * NULL when the submodule is not present.
525 static struct repository *open_submodule(const char *path)
527 struct strbuf sb = STRBUF_INIT;
528 struct repository *out = xmalloc(sizeof(*out));
530 if (submodule_to_gitdir(&sb, path) || repo_init(out, sb.buf, NULL)) {
531 strbuf_release(&sb);
532 free(out);
533 return NULL;
536 /* Mark it as a submodule */
537 out->submodule_prefix = xstrdup(path);
539 strbuf_release(&sb);
540 return out;
544 * Helper function to display the submodule header line prior to the full
545 * summary output.
547 * If it can locate the submodule git directory it will create a repository
548 * handle for the submodule and lookup both the left and right commits and
549 * put them into the left and right pointers.
551 static void show_submodule_header(struct diff_options *o,
552 const char *path,
553 struct object_id *one, struct object_id *two,
554 unsigned dirty_submodule,
555 struct repository *sub,
556 struct commit **left, struct commit **right,
557 struct commit_list **merge_bases)
559 const char *message = NULL;
560 struct strbuf sb = STRBUF_INIT;
561 int fast_forward = 0, fast_backward = 0;
563 if (dirty_submodule & DIRTY_SUBMODULE_UNTRACKED)
564 diff_emit_submodule_untracked(o, path);
566 if (dirty_submodule & DIRTY_SUBMODULE_MODIFIED)
567 diff_emit_submodule_modified(o, path);
569 if (is_null_oid(one))
570 message = "(new submodule)";
571 else if (is_null_oid(two))
572 message = "(submodule deleted)";
574 if (!sub) {
575 if (!message)
576 message = "(commits not present)";
577 goto output_header;
581 * Attempt to lookup the commit references, and determine if this is
582 * a fast forward or fast backwards update.
584 *left = lookup_commit_reference(sub, one);
585 *right = lookup_commit_reference(sub, two);
588 * Warn about missing commits in the submodule project, but only if
589 * they aren't null.
591 if ((!is_null_oid(one) && !*left) ||
592 (!is_null_oid(two) && !*right))
593 message = "(commits not present)";
595 *merge_bases = repo_get_merge_bases(sub, *left, *right);
596 if (*merge_bases) {
597 if ((*merge_bases)->item == *left)
598 fast_forward = 1;
599 else if ((*merge_bases)->item == *right)
600 fast_backward = 1;
603 if (oideq(one, two)) {
604 strbuf_release(&sb);
605 return;
608 output_header:
609 strbuf_addf(&sb, "Submodule %s ", path);
610 strbuf_add_unique_abbrev(&sb, one, DEFAULT_ABBREV);
611 strbuf_addstr(&sb, (fast_backward || fast_forward) ? ".." : "...");
612 strbuf_add_unique_abbrev(&sb, two, DEFAULT_ABBREV);
613 if (message)
614 strbuf_addf(&sb, " %s\n", message);
615 else
616 strbuf_addf(&sb, "%s:\n", fast_backward ? " (rewind)" : "");
617 diff_emit_submodule_header(o, sb.buf);
619 strbuf_release(&sb);
622 void show_submodule_diff_summary(struct diff_options *o, const char *path,
623 struct object_id *one, struct object_id *two,
624 unsigned dirty_submodule)
626 struct rev_info rev = REV_INFO_INIT;
627 struct commit *left = NULL, *right = NULL;
628 struct commit_list *merge_bases = NULL;
629 struct repository *sub;
631 sub = open_submodule(path);
632 show_submodule_header(o, path, one, two, dirty_submodule,
633 sub, &left, &right, &merge_bases);
636 * If we don't have both a left and a right pointer, there is no
637 * reason to try and display a summary. The header line should contain
638 * all the information the user needs.
640 if (!left || !right || !sub)
641 goto out;
643 /* Treat revision walker failure the same as missing commits */
644 if (prepare_submodule_diff_summary(sub, &rev, path, left, right, merge_bases)) {
645 diff_emit_submodule_error(o, "(revision walker failed)\n");
646 goto out;
649 print_submodule_diff_summary(sub, &rev, o);
651 out:
652 free_commit_list(merge_bases);
653 release_revisions(&rev);
654 clear_commit_marks(left, ~0);
655 clear_commit_marks(right, ~0);
656 if (sub) {
657 repo_clear(sub);
658 free(sub);
662 void show_submodule_inline_diff(struct diff_options *o, const char *path,
663 struct object_id *one, struct object_id *two,
664 unsigned dirty_submodule)
666 const struct object_id *old_oid = the_hash_algo->empty_tree, *new_oid = the_hash_algo->empty_tree;
667 struct commit *left = NULL, *right = NULL;
668 struct commit_list *merge_bases = NULL;
669 struct child_process cp = CHILD_PROCESS_INIT;
670 struct strbuf sb = STRBUF_INIT;
671 struct repository *sub;
673 sub = open_submodule(path);
674 show_submodule_header(o, path, one, two, dirty_submodule,
675 sub, &left, &right, &merge_bases);
677 /* We need a valid left and right commit to display a difference */
678 if (!(left || is_null_oid(one)) ||
679 !(right || is_null_oid(two)))
680 goto done;
682 if (left)
683 old_oid = one;
684 if (right)
685 new_oid = two;
687 cp.git_cmd = 1;
688 cp.dir = path;
689 cp.out = -1;
690 cp.no_stdin = 1;
692 /* TODO: other options may need to be passed here. */
693 strvec_pushl(&cp.args, "diff", "--submodule=diff", NULL);
694 strvec_pushf(&cp.args, "--color=%s", want_color(o->use_color) ?
695 "always" : "never");
697 if (o->flags.reverse_diff) {
698 strvec_pushf(&cp.args, "--src-prefix=%s%s/",
699 o->b_prefix, path);
700 strvec_pushf(&cp.args, "--dst-prefix=%s%s/",
701 o->a_prefix, path);
702 } else {
703 strvec_pushf(&cp.args, "--src-prefix=%s%s/",
704 o->a_prefix, path);
705 strvec_pushf(&cp.args, "--dst-prefix=%s%s/",
706 o->b_prefix, path);
708 strvec_push(&cp.args, oid_to_hex(old_oid));
710 * If the submodule has modified content, we will diff against the
711 * work tree, under the assumption that the user has asked for the
712 * diff format and wishes to actually see all differences even if they
713 * haven't yet been committed to the submodule yet.
715 if (!(dirty_submodule & DIRTY_SUBMODULE_MODIFIED))
716 strvec_push(&cp.args, oid_to_hex(new_oid));
718 prepare_submodule_repo_env(&cp.env);
720 if (!is_directory(path)) {
721 /* fall back to absorbed git dir, if any */
722 if (!sub)
723 goto done;
724 cp.dir = sub->gitdir;
725 strvec_push(&cp.env, GIT_DIR_ENVIRONMENT "=.");
726 strvec_push(&cp.env, GIT_WORK_TREE_ENVIRONMENT "=.");
729 if (start_command(&cp)) {
730 diff_emit_submodule_error(o, "(diff failed)\n");
731 goto done;
734 while (strbuf_getwholeline_fd(&sb, cp.out, '\n') != EOF)
735 diff_emit_submodule_pipethrough(o, sb.buf, sb.len);
737 if (finish_command(&cp))
738 diff_emit_submodule_error(o, "(diff failed)\n");
740 done:
741 strbuf_release(&sb);
742 free_commit_list(merge_bases);
743 if (left)
744 clear_commit_marks(left, ~0);
745 if (right)
746 clear_commit_marks(right, ~0);
747 if (sub) {
748 repo_clear(sub);
749 free(sub);
753 int should_update_submodules(void)
755 return config_update_recurse_submodules == RECURSE_SUBMODULES_ON;
758 const struct submodule *submodule_from_ce(const struct cache_entry *ce)
760 if (!S_ISGITLINK(ce->ce_mode))
761 return NULL;
763 if (!should_update_submodules())
764 return NULL;
766 return submodule_from_path(the_repository, null_oid(), ce->name);
770 struct collect_changed_submodules_cb_data {
771 struct repository *repo;
772 struct string_list *changed;
773 const struct object_id *commit_oid;
777 * this would normally be two functions: default_name_from_path() and
778 * path_from_default_name(). Since the default name is the same as
779 * the submodule path we can get away with just one function which only
780 * checks whether there is a submodule in the working directory at that
781 * location.
783 static const char *default_name_or_path(const char *path_or_name)
785 int error_code;
787 if (!is_submodule_populated_gently(path_or_name, &error_code))
788 return NULL;
790 return path_or_name;
794 * Holds relevant information for a changed submodule. Used as the .util
795 * member of the changed submodule name string_list_item.
797 * (super_oid, path) allows the submodule config to be read from _some_
798 * .gitmodules file. We store this information the first time we find a
799 * superproject commit that points to the submodule, but this is
800 * arbitrary - we can choose any (super_oid, path) that matches the
801 * submodule's name.
803 * NEEDSWORK: Storing an arbitrary commit is undesirable because we can't
804 * guarantee that we're reading the commit that the user would expect. A better
805 * scheme would be to just fetch a submodule by its name. This requires two
806 * steps:
807 * - Create a function that behaves like repo_submodule_init(), but accepts a
808 * submodule name instead of treeish_name and path. This should be easy
809 * because repo_submodule_init() internally uses the submodule's name.
811 * - Replace most instances of 'struct submodule' (which is the .gitmodules
812 * config) with just the submodule name. This is OK because we expect
813 * submodule settings to be stored in .git/config (via "git submodule init"),
814 * not .gitmodules. This also lets us delete get_non_gitmodules_submodule(),
815 * which constructs a bogus 'struct submodule' for the sake of giving a
816 * placeholder name to a gitlink.
818 struct changed_submodule_data {
820 * The first superproject commit in the rev walk that points to
821 * the submodule.
823 const struct object_id *super_oid;
825 * Path to the submodule in the superproject commit referenced
826 * by 'super_oid'.
828 char *path;
829 /* The submodule commits that have changed in the rev walk. */
830 struct oid_array new_commits;
833 static void changed_submodule_data_clear(struct changed_submodule_data *cs_data)
835 oid_array_clear(&cs_data->new_commits);
836 free(cs_data->path);
839 static void collect_changed_submodules_cb(struct diff_queue_struct *q,
840 struct diff_options *options UNUSED,
841 void *data)
843 struct collect_changed_submodules_cb_data *me = data;
844 struct string_list *changed = me->changed;
845 const struct object_id *commit_oid = me->commit_oid;
846 int i;
848 for (i = 0; i < q->nr; i++) {
849 struct diff_filepair *p = q->queue[i];
850 const struct submodule *submodule;
851 const char *name;
852 struct string_list_item *item;
853 struct changed_submodule_data *cs_data;
855 if (!S_ISGITLINK(p->two->mode))
856 continue;
858 submodule = submodule_from_path(me->repo,
859 commit_oid, p->two->path);
860 if (submodule)
861 name = submodule->name;
862 else {
863 name = default_name_or_path(p->two->path);
864 /* make sure name does not collide with existing one */
865 if (name)
866 submodule = submodule_from_name(me->repo,
867 commit_oid, name);
868 if (submodule) {
869 warning(_("Submodule in commit %s at path: "
870 "'%s' collides with a submodule named "
871 "the same. Skipping it."),
872 oid_to_hex(commit_oid), p->two->path);
873 name = NULL;
877 if (!name)
878 continue;
880 item = string_list_insert(changed, name);
881 if (item->util)
882 cs_data = item->util;
883 else {
884 item->util = xcalloc(1, sizeof(struct changed_submodule_data));
885 cs_data = item->util;
886 cs_data->super_oid = commit_oid;
887 cs_data->path = xstrdup(p->two->path);
889 oid_array_append(&cs_data->new_commits, &p->two->oid);
894 * Collect the paths of submodules in 'changed' which have changed based on
895 * the revisions as specified in 'argv'. Each entry in 'changed' will also
896 * have a corresponding 'struct oid_array' (in the 'util' field) which lists
897 * what the submodule pointers were updated to during the change.
899 static void collect_changed_submodules(struct repository *r,
900 struct string_list *changed,
901 struct strvec *argv)
903 struct rev_info rev;
904 const struct commit *commit;
905 int save_warning;
906 struct setup_revision_opt s_r_opt = {
907 .assume_dashdash = 1,
910 save_warning = warn_on_object_refname_ambiguity;
911 warn_on_object_refname_ambiguity = 0;
912 repo_init_revisions(r, &rev, NULL);
913 setup_revisions(argv->nr, argv->v, &rev, &s_r_opt);
914 warn_on_object_refname_ambiguity = save_warning;
915 if (prepare_revision_walk(&rev))
916 die(_("revision walk setup failed"));
918 while ((commit = get_revision(&rev))) {
919 struct rev_info diff_rev;
920 struct collect_changed_submodules_cb_data data;
921 data.repo = r;
922 data.changed = changed;
923 data.commit_oid = &commit->object.oid;
925 repo_init_revisions(r, &diff_rev, NULL);
926 diff_rev.diffopt.output_format |= DIFF_FORMAT_CALLBACK;
927 diff_rev.diffopt.format_callback = collect_changed_submodules_cb;
928 diff_rev.diffopt.format_callback_data = &data;
929 diff_rev.dense_combined_merges = 1;
930 diff_tree_combined_merge(commit, &diff_rev);
931 release_revisions(&diff_rev);
934 reset_revision_walk();
935 release_revisions(&rev);
938 static void free_submodules_data(struct string_list *submodules)
940 struct string_list_item *item;
941 for_each_string_list_item(item, submodules)
942 changed_submodule_data_clear(item->util);
944 string_list_clear(submodules, 1);
947 static int has_remote(const char *refname UNUSED,
948 const struct object_id *oid UNUSED,
949 int flags UNUSED, void *cb_data UNUSED)
951 return 1;
954 static int append_oid_to_argv(const struct object_id *oid, void *data)
956 struct strvec *argv = data;
957 strvec_push(argv, oid_to_hex(oid));
958 return 0;
961 struct has_commit_data {
962 struct repository *repo;
963 int result;
964 const char *path;
965 const struct object_id *super_oid;
968 static int check_has_commit(const struct object_id *oid, void *data)
970 struct has_commit_data *cb = data;
971 struct repository subrepo;
972 enum object_type type;
974 if (repo_submodule_init(&subrepo, cb->repo, cb->path, cb->super_oid)) {
975 cb->result = 0;
976 /* subrepo failed to init, so don't clean it up. */
977 return 0;
980 type = oid_object_info(&subrepo, oid, NULL);
982 switch (type) {
983 case OBJ_COMMIT:
984 goto cleanup;
985 case OBJ_BAD:
987 * Object is missing or invalid. If invalid, an error message
988 * has already been printed.
990 cb->result = 0;
991 goto cleanup;
992 default:
993 die(_("submodule entry '%s' (%s) is a %s, not a commit"),
994 cb->path, oid_to_hex(oid), type_name(type));
996 cleanup:
997 repo_clear(&subrepo);
998 return 0;
1001 static int submodule_has_commits(struct repository *r,
1002 const char *path,
1003 const struct object_id *super_oid,
1004 struct oid_array *commits)
1006 struct has_commit_data has_commit = {
1007 .repo = r,
1008 .result = 1,
1009 .path = path,
1010 .super_oid = super_oid
1013 oid_array_for_each_unique(commits, check_has_commit, &has_commit);
1015 if (has_commit.result) {
1017 * Even if the submodule is checked out and the commit is
1018 * present, make sure it exists in the submodule's object store
1019 * and that it is reachable from a ref.
1021 struct child_process cp = CHILD_PROCESS_INIT;
1022 struct strbuf out = STRBUF_INIT;
1024 strvec_pushl(&cp.args, "rev-list", "-n", "1", NULL);
1025 oid_array_for_each_unique(commits, append_oid_to_argv, &cp.args);
1026 strvec_pushl(&cp.args, "--not", "--all", NULL);
1028 prepare_submodule_repo_env(&cp.env);
1029 cp.git_cmd = 1;
1030 cp.no_stdin = 1;
1031 cp.dir = path;
1033 if (capture_command(&cp, &out, GIT_MAX_HEXSZ + 1) || out.len)
1034 has_commit.result = 0;
1036 strbuf_release(&out);
1039 return has_commit.result;
1042 static int submodule_needs_pushing(struct repository *r,
1043 const char *path,
1044 struct oid_array *commits)
1046 if (!submodule_has_commits(r, path, null_oid(), commits))
1048 * NOTE: We do consider it safe to return "no" here. The
1049 * correct answer would be "We do not know" instead of
1050 * "No push needed", but it is quite hard to change
1051 * the submodule pointer without having the submodule
1052 * around. If a user did however change the submodules
1053 * without having the submodule around, this indicates
1054 * an expert who knows what they are doing or a
1055 * maintainer integrating work from other people. In
1056 * both cases it should be safe to skip this check.
1058 return 0;
1060 if (for_each_remote_ref_submodule(path, has_remote, NULL) > 0) {
1061 struct child_process cp = CHILD_PROCESS_INIT;
1062 struct strbuf buf = STRBUF_INIT;
1063 int needs_pushing = 0;
1065 strvec_push(&cp.args, "rev-list");
1066 oid_array_for_each_unique(commits, append_oid_to_argv, &cp.args);
1067 strvec_pushl(&cp.args, "--not", "--remotes", "-n", "1" , NULL);
1069 prepare_submodule_repo_env(&cp.env);
1070 cp.git_cmd = 1;
1071 cp.no_stdin = 1;
1072 cp.out = -1;
1073 cp.dir = path;
1074 if (start_command(&cp))
1075 die(_("Could not run 'git rev-list <commits> --not --remotes -n 1' command in submodule %s"),
1076 path);
1077 if (strbuf_read(&buf, cp.out, the_hash_algo->hexsz + 1))
1078 needs_pushing = 1;
1079 finish_command(&cp);
1080 close(cp.out);
1081 strbuf_release(&buf);
1082 return needs_pushing;
1085 return 0;
1088 int find_unpushed_submodules(struct repository *r,
1089 struct oid_array *commits,
1090 const char *remotes_name,
1091 struct string_list *needs_pushing)
1093 struct string_list submodules = STRING_LIST_INIT_DUP;
1094 struct string_list_item *name;
1095 struct strvec argv = STRVEC_INIT;
1097 /* argv.v[0] will be ignored by setup_revisions */
1098 strvec_push(&argv, "find_unpushed_submodules");
1099 oid_array_for_each_unique(commits, append_oid_to_argv, &argv);
1100 strvec_push(&argv, "--not");
1101 strvec_pushf(&argv, "--remotes=%s", remotes_name);
1103 collect_changed_submodules(r, &submodules, &argv);
1105 for_each_string_list_item(name, &submodules) {
1106 struct changed_submodule_data *cs_data = name->util;
1107 const struct submodule *submodule;
1108 const char *path = NULL;
1110 submodule = submodule_from_name(r, null_oid(), name->string);
1111 if (submodule)
1112 path = submodule->path;
1113 else
1114 path = default_name_or_path(name->string);
1116 if (!path)
1117 continue;
1119 if (submodule_needs_pushing(r, path, &cs_data->new_commits))
1120 string_list_insert(needs_pushing, path);
1123 free_submodules_data(&submodules);
1124 strvec_clear(&argv);
1126 return needs_pushing->nr;
1129 static int push_submodule(const char *path,
1130 const struct remote *remote,
1131 const struct refspec *rs,
1132 const struct string_list *push_options,
1133 int dry_run)
1135 if (for_each_remote_ref_submodule(path, has_remote, NULL) > 0) {
1136 struct child_process cp = CHILD_PROCESS_INIT;
1137 strvec_push(&cp.args, "push");
1139 * When recursing into a submodule, treat any "only" configurations as "on-
1140 * demand", since "only" would not work (we need all submodules to be pushed
1141 * in order to be able to push the superproject).
1143 strvec_push(&cp.args, "--recurse-submodules=only-is-on-demand");
1144 if (dry_run)
1145 strvec_push(&cp.args, "--dry-run");
1147 if (push_options && push_options->nr) {
1148 const struct string_list_item *item;
1149 for_each_string_list_item(item, push_options)
1150 strvec_pushf(&cp.args, "--push-option=%s",
1151 item->string);
1154 if (remote->origin != REMOTE_UNCONFIGURED) {
1155 int i;
1156 strvec_push(&cp.args, remote->name);
1157 for (i = 0; i < rs->raw_nr; i++)
1158 strvec_push(&cp.args, rs->raw[i]);
1161 prepare_submodule_repo_env(&cp.env);
1162 cp.git_cmd = 1;
1163 cp.no_stdin = 1;
1164 cp.dir = path;
1165 if (run_command(&cp))
1166 return 0;
1167 close(cp.out);
1170 return 1;
1174 * Perform a check in the submodule to see if the remote and refspec work.
1175 * Die if the submodule can't be pushed.
1177 static void submodule_push_check(const char *path, const char *head,
1178 const struct remote *remote,
1179 const struct refspec *rs)
1181 struct child_process cp = CHILD_PROCESS_INIT;
1182 int i;
1184 strvec_push(&cp.args, "submodule--helper");
1185 strvec_push(&cp.args, "push-check");
1186 strvec_push(&cp.args, head);
1187 strvec_push(&cp.args, remote->name);
1189 for (i = 0; i < rs->raw_nr; i++)
1190 strvec_push(&cp.args, rs->raw[i]);
1192 prepare_submodule_repo_env(&cp.env);
1193 cp.git_cmd = 1;
1194 cp.no_stdin = 1;
1195 cp.no_stdout = 1;
1196 cp.dir = path;
1199 * Simply indicate if 'submodule--helper push-check' failed.
1200 * More detailed error information will be provided by the
1201 * child process.
1203 if (run_command(&cp))
1204 die(_("process for submodule '%s' failed"), path);
1207 int push_unpushed_submodules(struct repository *r,
1208 struct oid_array *commits,
1209 const struct remote *remote,
1210 const struct refspec *rs,
1211 const struct string_list *push_options,
1212 int dry_run)
1214 int i, ret = 1;
1215 struct string_list needs_pushing = STRING_LIST_INIT_DUP;
1217 if (!find_unpushed_submodules(r, commits,
1218 remote->name, &needs_pushing))
1219 return 1;
1222 * Verify that the remote and refspec can be propagated to all
1223 * submodules. This check can be skipped if the remote and refspec
1224 * won't be propagated due to the remote being unconfigured (e.g. a URL
1225 * instead of a remote name).
1227 if (remote->origin != REMOTE_UNCONFIGURED) {
1228 char *head;
1229 struct object_id head_oid;
1231 head = resolve_refdup("HEAD", 0, &head_oid, NULL);
1232 if (!head)
1233 die(_("Failed to resolve HEAD as a valid ref."));
1235 for (i = 0; i < needs_pushing.nr; i++)
1236 submodule_push_check(needs_pushing.items[i].string,
1237 head, remote, rs);
1238 free(head);
1241 /* Actually push the submodules */
1242 for (i = 0; i < needs_pushing.nr; i++) {
1243 const char *path = needs_pushing.items[i].string;
1244 fprintf(stderr, _("Pushing submodule '%s'\n"), path);
1245 if (!push_submodule(path, remote, rs,
1246 push_options, dry_run)) {
1247 fprintf(stderr, _("Unable to push submodule '%s'\n"), path);
1248 ret = 0;
1252 string_list_clear(&needs_pushing, 0);
1254 return ret;
1257 static int append_oid_to_array(const char *ref UNUSED,
1258 const struct object_id *oid,
1259 int flags UNUSED, void *data)
1261 struct oid_array *array = data;
1262 oid_array_append(array, oid);
1263 return 0;
1266 void check_for_new_submodule_commits(struct object_id *oid)
1268 if (!initialized_fetch_ref_tips) {
1269 for_each_ref(append_oid_to_array, &ref_tips_before_fetch);
1270 initialized_fetch_ref_tips = 1;
1273 oid_array_append(&ref_tips_after_fetch, oid);
1277 * Returns 1 if there is at least one submodule gitdir in
1278 * $GIT_DIR/modules and 0 otherwise. This follows
1279 * submodule_name_to_gitdir(), which looks for submodules in
1280 * $GIT_DIR/modules, not $GIT_COMMON_DIR.
1282 * A submodule can be moved to $GIT_DIR/modules manually by running "git
1283 * submodule absorbgitdirs", or it may be initialized there by "git
1284 * submodule update".
1286 static int repo_has_absorbed_submodules(struct repository *r)
1288 int ret;
1289 struct strbuf buf = STRBUF_INIT;
1291 strbuf_repo_git_path(&buf, r, "modules/");
1292 ret = file_exists(buf.buf) && !is_empty_dir(buf.buf);
1293 strbuf_release(&buf);
1294 return ret;
1297 static void calculate_changed_submodule_paths(struct repository *r,
1298 struct string_list *changed_submodule_names)
1300 struct strvec argv = STRVEC_INIT;
1301 struct string_list_item *name;
1303 /* No need to check if no submodules would be fetched */
1304 if (!submodule_from_path(r, NULL, NULL) &&
1305 !repo_has_absorbed_submodules(r))
1306 return;
1308 strvec_push(&argv, "--"); /* argv[0] program name */
1309 oid_array_for_each_unique(&ref_tips_after_fetch,
1310 append_oid_to_argv, &argv);
1311 strvec_push(&argv, "--not");
1312 oid_array_for_each_unique(&ref_tips_before_fetch,
1313 append_oid_to_argv, &argv);
1316 * Collect all submodules (whether checked out or not) for which new
1317 * commits have been recorded upstream in "changed_submodule_names".
1319 collect_changed_submodules(r, changed_submodule_names, &argv);
1321 for_each_string_list_item(name, changed_submodule_names) {
1322 struct changed_submodule_data *cs_data = name->util;
1323 const struct submodule *submodule;
1324 const char *path = NULL;
1326 submodule = submodule_from_name(r, null_oid(), name->string);
1327 if (submodule)
1328 path = submodule->path;
1329 else
1330 path = default_name_or_path(name->string);
1332 if (!path)
1333 continue;
1335 if (submodule_has_commits(r, path, null_oid(), &cs_data->new_commits)) {
1336 changed_submodule_data_clear(cs_data);
1337 *name->string = '\0';
1341 string_list_remove_empty_items(changed_submodule_names, 1);
1343 strvec_clear(&argv);
1344 oid_array_clear(&ref_tips_before_fetch);
1345 oid_array_clear(&ref_tips_after_fetch);
1346 initialized_fetch_ref_tips = 0;
1349 int submodule_touches_in_range(struct repository *r,
1350 struct object_id *excl_oid,
1351 struct object_id *incl_oid)
1353 struct string_list subs = STRING_LIST_INIT_DUP;
1354 struct strvec args = STRVEC_INIT;
1355 int ret;
1357 /* No need to check if there are no submodules configured */
1358 if (!submodule_from_path(r, NULL, NULL))
1359 return 0;
1361 strvec_push(&args, "--"); /* args[0] program name */
1362 strvec_push(&args, oid_to_hex(incl_oid));
1363 if (!is_null_oid(excl_oid)) {
1364 strvec_push(&args, "--not");
1365 strvec_push(&args, oid_to_hex(excl_oid));
1368 collect_changed_submodules(r, &subs, &args);
1369 ret = subs.nr;
1371 strvec_clear(&args);
1373 free_submodules_data(&subs);
1374 return ret;
1377 struct submodule_parallel_fetch {
1379 * The index of the last index entry processed by
1380 * get_fetch_task_from_index().
1382 int index_count;
1384 * The index of the last string_list entry processed by
1385 * get_fetch_task_from_changed().
1387 int changed_count;
1388 struct strvec args;
1389 struct repository *r;
1390 const char *prefix;
1391 int command_line_option;
1392 int default_option;
1393 int quiet;
1394 int result;
1397 * Names of submodules that have new commits. Generated by
1398 * walking the newly fetched superproject commits.
1400 struct string_list changed_submodule_names;
1402 * Names of submodules that have already been processed. Lets us
1403 * avoid fetching the same submodule more than once.
1405 struct string_list seen_submodule_names;
1407 /* Pending fetches by OIDs */
1408 struct fetch_task **oid_fetch_tasks;
1409 int oid_fetch_tasks_nr, oid_fetch_tasks_alloc;
1411 struct strbuf submodules_with_errors;
1413 #define SPF_INIT { \
1414 .args = STRVEC_INIT, \
1415 .changed_submodule_names = STRING_LIST_INIT_DUP, \
1416 .seen_submodule_names = STRING_LIST_INIT_DUP, \
1417 .submodules_with_errors = STRBUF_INIT, \
1420 static int get_fetch_recurse_config(const struct submodule *submodule,
1421 struct submodule_parallel_fetch *spf)
1423 if (spf->command_line_option != RECURSE_SUBMODULES_DEFAULT)
1424 return spf->command_line_option;
1426 if (submodule) {
1427 char *key;
1428 const char *value;
1430 int fetch_recurse = submodule->fetch_recurse;
1431 key = xstrfmt("submodule.%s.fetchRecurseSubmodules", submodule->name);
1432 if (!repo_config_get_string_tmp(spf->r, key, &value)) {
1433 fetch_recurse = parse_fetch_recurse_submodules_arg(key, value);
1435 free(key);
1437 if (fetch_recurse != RECURSE_SUBMODULES_NONE)
1438 /* local config overrules everything except commandline */
1439 return fetch_recurse;
1442 return spf->default_option;
1446 * Fetch in progress (if callback data) or
1447 * pending (if in oid_fetch_tasks in struct submodule_parallel_fetch)
1449 struct fetch_task {
1450 struct repository *repo;
1451 const struct submodule *sub;
1452 unsigned free_sub : 1; /* Do we need to free the submodule? */
1453 const char *default_argv; /* The default fetch mode. */
1454 struct strvec git_args; /* Args for the child git process. */
1456 struct oid_array *commits; /* Ensure these commits are fetched */
1460 * When a submodule is not defined in .gitmodules, we cannot access it
1461 * via the regular submodule-config. Create a fake submodule, which we can
1462 * work on.
1464 static const struct submodule *get_non_gitmodules_submodule(const char *path)
1466 struct submodule *ret = NULL;
1467 const char *name = default_name_or_path(path);
1469 if (!name)
1470 return NULL;
1472 ret = xmalloc(sizeof(*ret));
1473 memset(ret, 0, sizeof(*ret));
1474 ret->path = name;
1475 ret->name = name;
1477 return (const struct submodule *) ret;
1480 static void fetch_task_release(struct fetch_task *p)
1482 if (p->free_sub)
1483 free((void*)p->sub);
1484 p->free_sub = 0;
1485 p->sub = NULL;
1487 if (p->repo)
1488 repo_clear(p->repo);
1489 FREE_AND_NULL(p->repo);
1491 strvec_clear(&p->git_args);
1494 static struct repository *get_submodule_repo_for(struct repository *r,
1495 const char *path,
1496 const struct object_id *treeish_name)
1498 struct repository *ret = xmalloc(sizeof(*ret));
1500 if (repo_submodule_init(ret, r, path, treeish_name)) {
1501 free(ret);
1502 return NULL;
1505 return ret;
1508 static struct fetch_task *fetch_task_create(struct submodule_parallel_fetch *spf,
1509 const char *path,
1510 const struct object_id *treeish_name)
1512 struct fetch_task *task = xmalloc(sizeof(*task));
1513 memset(task, 0, sizeof(*task));
1515 task->sub = submodule_from_path(spf->r, treeish_name, path);
1517 if (!task->sub) {
1519 * No entry in .gitmodules? Technically not a submodule,
1520 * but historically we supported repositories that happen to be
1521 * in-place where a gitlink is. Keep supporting them.
1523 task->sub = get_non_gitmodules_submodule(path);
1524 if (!task->sub)
1525 goto cleanup;
1527 task->free_sub = 1;
1530 if (string_list_lookup(&spf->seen_submodule_names, task->sub->name))
1531 goto cleanup;
1533 switch (get_fetch_recurse_config(task->sub, spf))
1535 default:
1536 case RECURSE_SUBMODULES_DEFAULT:
1537 case RECURSE_SUBMODULES_ON_DEMAND:
1538 if (!task->sub ||
1539 !string_list_lookup(
1540 &spf->changed_submodule_names,
1541 task->sub->name))
1542 goto cleanup;
1543 task->default_argv = "on-demand";
1544 break;
1545 case RECURSE_SUBMODULES_ON:
1546 task->default_argv = "yes";
1547 break;
1548 case RECURSE_SUBMODULES_OFF:
1549 goto cleanup;
1552 task->repo = get_submodule_repo_for(spf->r, path, treeish_name);
1554 return task;
1556 cleanup:
1557 fetch_task_release(task);
1558 free(task);
1559 return NULL;
1562 static struct fetch_task *
1563 get_fetch_task_from_index(struct submodule_parallel_fetch *spf,
1564 struct strbuf *err)
1566 for (; spf->index_count < spf->r->index->cache_nr; spf->index_count++) {
1567 const struct cache_entry *ce =
1568 spf->r->index->cache[spf->index_count];
1569 struct fetch_task *task;
1571 if (!S_ISGITLINK(ce->ce_mode))
1572 continue;
1574 task = fetch_task_create(spf, ce->name, null_oid());
1575 if (!task)
1576 continue;
1578 if (task->repo) {
1579 if (!spf->quiet)
1580 strbuf_addf(err, _("Fetching submodule %s%s\n"),
1581 spf->prefix, ce->name);
1583 spf->index_count++;
1584 return task;
1585 } else {
1586 struct strbuf empty_submodule_path = STRBUF_INIT;
1588 fetch_task_release(task);
1589 free(task);
1592 * An empty directory is normal,
1593 * the submodule is not initialized
1595 strbuf_addf(&empty_submodule_path, "%s/%s/",
1596 spf->r->worktree,
1597 ce->name);
1598 if (S_ISGITLINK(ce->ce_mode) &&
1599 !is_empty_dir(empty_submodule_path.buf)) {
1600 spf->result = 1;
1601 strbuf_addf(err,
1602 _("Could not access submodule '%s'\n"),
1603 ce->name);
1605 strbuf_release(&empty_submodule_path);
1608 return NULL;
1611 static struct fetch_task *
1612 get_fetch_task_from_changed(struct submodule_parallel_fetch *spf,
1613 struct strbuf *err)
1615 for (; spf->changed_count < spf->changed_submodule_names.nr;
1616 spf->changed_count++) {
1617 struct string_list_item item =
1618 spf->changed_submodule_names.items[spf->changed_count];
1619 struct changed_submodule_data *cs_data = item.util;
1620 struct fetch_task *task;
1622 if (!is_tree_submodule_active(spf->r, cs_data->super_oid,cs_data->path))
1623 continue;
1625 task = fetch_task_create(spf, cs_data->path,
1626 cs_data->super_oid);
1627 if (!task)
1628 continue;
1630 if (!task->repo) {
1631 strbuf_addf(err, _("Could not access submodule '%s' at commit %s\n"),
1632 cs_data->path,
1633 repo_find_unique_abbrev(the_repository, cs_data->super_oid, DEFAULT_ABBREV));
1635 fetch_task_release(task);
1636 free(task);
1637 continue;
1640 if (!spf->quiet)
1641 strbuf_addf(err,
1642 _("Fetching submodule %s%s at commit %s\n"),
1643 spf->prefix, task->sub->path,
1644 repo_find_unique_abbrev(the_repository, cs_data->super_oid,
1645 DEFAULT_ABBREV));
1647 spf->changed_count++;
1649 * NEEDSWORK: Submodules set/unset a value for
1650 * core.worktree when they are populated/unpopulated by
1651 * "git checkout" (and similar commands, see
1652 * submodule_move_head() and
1653 * connect_work_tree_and_git_dir()), but if the
1654 * submodule is unpopulated in another way (e.g. "git
1655 * rm", "rm -r"), core.worktree will still be set even
1656 * though the directory doesn't exist, and the child
1657 * process will crash while trying to chdir into the
1658 * nonexistent directory.
1660 * In this case, we know that the submodule has no
1661 * working tree, so we can work around this by
1662 * setting "--work-tree=." (--bare does not work because
1663 * worktree settings take precedence over bare-ness).
1664 * However, this is not necessarily true in other cases,
1665 * so a generalized solution is still necessary.
1667 * Possible solutions:
1668 * - teach "git [add|rm]" to unset core.worktree and
1669 * discourage users from removing submodules without
1670 * using a Git command.
1671 * - teach submodule child processes to ignore stale
1672 * core.worktree values.
1674 strvec_push(&task->git_args, "--work-tree=.");
1675 return task;
1677 return NULL;
1680 static int get_next_submodule(struct child_process *cp, struct strbuf *err,
1681 void *data, void **task_cb)
1683 struct submodule_parallel_fetch *spf = data;
1684 struct fetch_task *task =
1685 get_fetch_task_from_index(spf, err);
1686 if (!task)
1687 task = get_fetch_task_from_changed(spf, err);
1689 if (task) {
1690 struct strbuf submodule_prefix = STRBUF_INIT;
1692 child_process_init(cp);
1693 cp->dir = task->repo->gitdir;
1694 prepare_submodule_repo_env_in_gitdir(&cp->env);
1695 cp->git_cmd = 1;
1696 strvec_init(&cp->args);
1697 if (task->git_args.nr)
1698 strvec_pushv(&cp->args, task->git_args.v);
1699 strvec_pushv(&cp->args, spf->args.v);
1700 strvec_push(&cp->args, task->default_argv);
1701 strvec_push(&cp->args, "--submodule-prefix");
1703 strbuf_addf(&submodule_prefix, "%s%s/",
1704 spf->prefix,
1705 task->sub->path);
1706 strvec_push(&cp->args, submodule_prefix.buf);
1707 *task_cb = task;
1709 strbuf_release(&submodule_prefix);
1710 string_list_insert(&spf->seen_submodule_names, task->sub->name);
1711 return 1;
1714 if (spf->oid_fetch_tasks_nr) {
1715 struct fetch_task *task =
1716 spf->oid_fetch_tasks[spf->oid_fetch_tasks_nr - 1];
1717 struct strbuf submodule_prefix = STRBUF_INIT;
1718 spf->oid_fetch_tasks_nr--;
1720 strbuf_addf(&submodule_prefix, "%s%s/",
1721 spf->prefix, task->sub->path);
1723 child_process_init(cp);
1724 prepare_submodule_repo_env_in_gitdir(&cp->env);
1725 cp->git_cmd = 1;
1726 cp->dir = task->repo->gitdir;
1728 strvec_init(&cp->args);
1729 strvec_pushv(&cp->args, spf->args.v);
1730 strvec_push(&cp->args, "on-demand");
1731 strvec_push(&cp->args, "--submodule-prefix");
1732 strvec_push(&cp->args, submodule_prefix.buf);
1734 /* NEEDSWORK: have get_default_remote from submodule--helper */
1735 strvec_push(&cp->args, "origin");
1736 oid_array_for_each_unique(task->commits,
1737 append_oid_to_argv, &cp->args);
1739 *task_cb = task;
1740 strbuf_release(&submodule_prefix);
1741 return 1;
1744 return 0;
1747 static int fetch_start_failure(struct strbuf *err UNUSED,
1748 void *cb, void *task_cb)
1750 struct submodule_parallel_fetch *spf = cb;
1751 struct fetch_task *task = task_cb;
1753 spf->result = 1;
1755 fetch_task_release(task);
1756 return 0;
1759 static int commit_missing_in_sub(const struct object_id *oid, void *data)
1761 struct repository *subrepo = data;
1763 enum object_type type = oid_object_info(subrepo, oid, NULL);
1765 return type != OBJ_COMMIT;
1768 static int fetch_finish(int retvalue, struct strbuf *err UNUSED,
1769 void *cb, void *task_cb)
1771 struct submodule_parallel_fetch *spf = cb;
1772 struct fetch_task *task = task_cb;
1774 struct string_list_item *it;
1775 struct changed_submodule_data *cs_data;
1777 if (!task || !task->sub)
1778 BUG("callback cookie bogus");
1780 if (retvalue) {
1782 * NEEDSWORK: This indicates that the overall fetch
1783 * failed, even though there may be a subsequent fetch
1784 * by commit hash that might work. It may be a good
1785 * idea to not indicate failure in this case, and only
1786 * indicate failure if the subsequent fetch fails.
1788 spf->result = 1;
1790 strbuf_addf(&spf->submodules_with_errors, "\t%s\n",
1791 task->sub->name);
1794 /* Is this the second time we process this submodule? */
1795 if (task->commits)
1796 goto out;
1798 it = string_list_lookup(&spf->changed_submodule_names, task->sub->name);
1799 if (!it)
1800 /* Could be an unchanged submodule, not contained in the list */
1801 goto out;
1803 cs_data = it->util;
1804 oid_array_filter(&cs_data->new_commits,
1805 commit_missing_in_sub,
1806 task->repo);
1808 /* Are there commits we want, but do not exist? */
1809 if (cs_data->new_commits.nr) {
1810 task->commits = &cs_data->new_commits;
1811 ALLOC_GROW(spf->oid_fetch_tasks,
1812 spf->oid_fetch_tasks_nr + 1,
1813 spf->oid_fetch_tasks_alloc);
1814 spf->oid_fetch_tasks[spf->oid_fetch_tasks_nr] = task;
1815 spf->oid_fetch_tasks_nr++;
1816 return 0;
1819 out:
1820 fetch_task_release(task);
1822 return 0;
1825 int fetch_submodules(struct repository *r,
1826 const struct strvec *options,
1827 const char *prefix, int command_line_option,
1828 int default_option,
1829 int quiet, int max_parallel_jobs)
1831 int i;
1832 struct submodule_parallel_fetch spf = SPF_INIT;
1833 const struct run_process_parallel_opts opts = {
1834 .tr2_category = "submodule",
1835 .tr2_label = "parallel/fetch",
1837 .processes = max_parallel_jobs,
1839 .get_next_task = get_next_submodule,
1840 .start_failure = fetch_start_failure,
1841 .task_finished = fetch_finish,
1842 .data = &spf,
1845 spf.r = r;
1846 spf.command_line_option = command_line_option;
1847 spf.default_option = default_option;
1848 spf.quiet = quiet;
1849 spf.prefix = prefix;
1851 if (!r->worktree)
1852 goto out;
1854 if (repo_read_index(r) < 0)
1855 die(_("index file corrupt"));
1857 strvec_push(&spf.args, "fetch");
1858 for (i = 0; i < options->nr; i++)
1859 strvec_push(&spf.args, options->v[i]);
1860 strvec_push(&spf.args, "--recurse-submodules-default");
1861 /* default value, "--submodule-prefix" and its value are added later */
1863 calculate_changed_submodule_paths(r, &spf.changed_submodule_names);
1864 string_list_sort(&spf.changed_submodule_names);
1865 run_processes_parallel(&opts);
1867 if (spf.submodules_with_errors.len > 0)
1868 fprintf(stderr, _("Errors during submodule fetch:\n%s"),
1869 spf.submodules_with_errors.buf);
1872 strvec_clear(&spf.args);
1873 out:
1874 free_submodules_data(&spf.changed_submodule_names);
1875 return spf.result;
1878 unsigned is_submodule_modified(const char *path, int ignore_untracked)
1880 struct child_process cp = CHILD_PROCESS_INIT;
1881 struct strbuf buf = STRBUF_INIT;
1882 FILE *fp;
1883 unsigned dirty_submodule = 0;
1884 const char *git_dir;
1885 int ignore_cp_exit_code = 0;
1887 strbuf_addf(&buf, "%s/.git", path);
1888 git_dir = read_gitfile(buf.buf);
1889 if (!git_dir)
1890 git_dir = buf.buf;
1891 if (!is_git_directory(git_dir)) {
1892 if (is_directory(git_dir))
1893 die(_("'%s' not recognized as a git repository"), git_dir);
1894 strbuf_release(&buf);
1895 /* The submodule is not checked out, so it is not modified */
1896 return 0;
1898 strbuf_reset(&buf);
1900 strvec_pushl(&cp.args, "status", "--porcelain=2", NULL);
1901 if (ignore_untracked)
1902 strvec_push(&cp.args, "-uno");
1904 prepare_submodule_repo_env(&cp.env);
1905 cp.git_cmd = 1;
1906 cp.no_stdin = 1;
1907 cp.out = -1;
1908 cp.dir = path;
1909 if (start_command(&cp))
1910 die(_("Could not run 'git status --porcelain=2' in submodule %s"), path);
1912 fp = xfdopen(cp.out, "r");
1913 while (strbuf_getwholeline(&buf, fp, '\n') != EOF) {
1914 /* regular untracked files */
1915 if (buf.buf[0] == '?')
1916 dirty_submodule |= DIRTY_SUBMODULE_UNTRACKED;
1918 if (buf.buf[0] == 'u' ||
1919 buf.buf[0] == '1' ||
1920 buf.buf[0] == '2') {
1921 /* T = line type, XY = status, SSSS = submodule state */
1922 if (buf.len < strlen("T XY SSSS"))
1923 BUG("invalid status --porcelain=2 line %s",
1924 buf.buf);
1926 if (buf.buf[5] == 'S' && buf.buf[8] == 'U')
1927 /* nested untracked file */
1928 dirty_submodule |= DIRTY_SUBMODULE_UNTRACKED;
1930 if (buf.buf[0] == 'u' ||
1931 buf.buf[0] == '2' ||
1932 memcmp(buf.buf + 5, "S..U", 4))
1933 /* other change */
1934 dirty_submodule |= DIRTY_SUBMODULE_MODIFIED;
1937 if ((dirty_submodule & DIRTY_SUBMODULE_MODIFIED) &&
1938 ((dirty_submodule & DIRTY_SUBMODULE_UNTRACKED) ||
1939 ignore_untracked)) {
1941 * We're not interested in any further information from
1942 * the child any more, neither output nor its exit code.
1944 ignore_cp_exit_code = 1;
1945 break;
1948 fclose(fp);
1950 if (finish_command(&cp) && !ignore_cp_exit_code)
1951 die(_("'git status --porcelain=2' failed in submodule %s"), path);
1953 strbuf_release(&buf);
1954 return dirty_submodule;
1957 int submodule_uses_gitfile(const char *path)
1959 struct child_process cp = CHILD_PROCESS_INIT;
1960 struct strbuf buf = STRBUF_INIT;
1961 const char *git_dir;
1963 strbuf_addf(&buf, "%s/.git", path);
1964 git_dir = read_gitfile(buf.buf);
1965 if (!git_dir) {
1966 strbuf_release(&buf);
1967 return 0;
1969 strbuf_release(&buf);
1971 /* Now test that all nested submodules use a gitfile too */
1972 strvec_pushl(&cp.args,
1973 "submodule", "foreach", "--quiet", "--recursive",
1974 "test -f .git", NULL);
1976 prepare_submodule_repo_env(&cp.env);
1977 cp.git_cmd = 1;
1978 cp.no_stdin = 1;
1979 cp.no_stderr = 1;
1980 cp.no_stdout = 1;
1981 cp.dir = path;
1982 if (run_command(&cp))
1983 return 0;
1985 return 1;
1989 * Check if it is a bad idea to remove a submodule, i.e. if we'd lose data
1990 * when doing so.
1992 * Return 1 if we'd lose data, return 0 if the removal is fine,
1993 * and negative values for errors.
1995 int bad_to_remove_submodule(const char *path, unsigned flags)
1997 ssize_t len;
1998 struct child_process cp = CHILD_PROCESS_INIT;
1999 struct strbuf buf = STRBUF_INIT;
2000 int ret = 0;
2002 if (!file_exists(path) || is_empty_dir(path))
2003 return 0;
2005 if (!submodule_uses_gitfile(path))
2006 return 1;
2008 strvec_pushl(&cp.args, "status", "--porcelain",
2009 "--ignore-submodules=none", NULL);
2011 if (flags & SUBMODULE_REMOVAL_IGNORE_UNTRACKED)
2012 strvec_push(&cp.args, "-uno");
2013 else
2014 strvec_push(&cp.args, "-uall");
2016 if (!(flags & SUBMODULE_REMOVAL_IGNORE_IGNORED_UNTRACKED))
2017 strvec_push(&cp.args, "--ignored");
2019 prepare_submodule_repo_env(&cp.env);
2020 cp.git_cmd = 1;
2021 cp.no_stdin = 1;
2022 cp.out = -1;
2023 cp.dir = path;
2024 if (start_command(&cp)) {
2025 if (flags & SUBMODULE_REMOVAL_DIE_ON_ERROR)
2026 die(_("could not start 'git status' in submodule '%s'"),
2027 path);
2028 ret = -1;
2029 goto out;
2032 len = strbuf_read(&buf, cp.out, 1024);
2033 if (len > 2)
2034 ret = 1;
2035 close(cp.out);
2037 if (finish_command(&cp)) {
2038 if (flags & SUBMODULE_REMOVAL_DIE_ON_ERROR)
2039 die(_("could not run 'git status' in submodule '%s'"),
2040 path);
2041 ret = -1;
2043 out:
2044 strbuf_release(&buf);
2045 return ret;
2048 void submodule_unset_core_worktree(const struct submodule *sub)
2050 struct strbuf config_path = STRBUF_INIT;
2052 submodule_name_to_gitdir(&config_path, the_repository, sub->name);
2053 strbuf_addstr(&config_path, "/config");
2055 if (git_config_set_in_file_gently(config_path.buf, "core.worktree", NULL))
2056 warning(_("Could not unset core.worktree setting in submodule '%s'"),
2057 sub->path);
2059 strbuf_release(&config_path);
2062 static int submodule_has_dirty_index(const struct submodule *sub)
2064 struct child_process cp = CHILD_PROCESS_INIT;
2066 prepare_submodule_repo_env(&cp.env);
2068 cp.git_cmd = 1;
2069 strvec_pushl(&cp.args, "diff-index", "--quiet",
2070 "--cached", "HEAD", NULL);
2071 cp.no_stdin = 1;
2072 cp.no_stdout = 1;
2073 cp.dir = sub->path;
2074 if (start_command(&cp))
2075 die(_("could not recurse into submodule '%s'"), sub->path);
2077 return finish_command(&cp);
2080 static void submodule_reset_index(const char *path, const char *super_prefix)
2082 struct child_process cp = CHILD_PROCESS_INIT;
2083 prepare_submodule_repo_env(&cp.env);
2085 cp.git_cmd = 1;
2086 cp.no_stdin = 1;
2087 cp.dir = path;
2089 /* TODO: determine if this might overwright untracked files */
2090 strvec_pushl(&cp.args, "read-tree", "-u", "--reset", NULL);
2091 strvec_pushf(&cp.args, "--super-prefix=%s%s/",
2092 (super_prefix ? super_prefix : ""), path);
2094 strvec_push(&cp.args, empty_tree_oid_hex());
2096 if (run_command(&cp))
2097 die(_("could not reset submodule index"));
2101 * Moves a submodule at a given path from a given head to another new head.
2102 * For edge cases (a submodule coming into existence or removing a submodule)
2103 * pass NULL for old or new respectively.
2105 int submodule_move_head(const char *path, const char *super_prefix,
2106 const char *old_head, const char *new_head,
2107 unsigned flags)
2109 int ret = 0;
2110 struct child_process cp = CHILD_PROCESS_INIT;
2111 const struct submodule *sub;
2112 int *error_code_ptr, error_code;
2114 if (!is_submodule_active(the_repository, path))
2115 return 0;
2117 if (flags & SUBMODULE_MOVE_HEAD_FORCE)
2119 * Pass non NULL pointer to is_submodule_populated_gently
2120 * to prevent die()-ing. We'll use connect_work_tree_and_git_dir
2121 * to fixup the submodule in the force case later.
2123 error_code_ptr = &error_code;
2124 else
2125 error_code_ptr = NULL;
2127 if (old_head && !is_submodule_populated_gently(path, error_code_ptr))
2128 return 0;
2130 sub = submodule_from_path(the_repository, null_oid(), path);
2132 if (!sub)
2133 BUG("could not get submodule information for '%s'", path);
2135 if (old_head && !(flags & SUBMODULE_MOVE_HEAD_FORCE)) {
2136 /* Check if the submodule has a dirty index. */
2137 if (submodule_has_dirty_index(sub))
2138 return error(_("submodule '%s' has dirty index"), path);
2141 if (!(flags & SUBMODULE_MOVE_HEAD_DRY_RUN)) {
2142 if (old_head) {
2143 if (!submodule_uses_gitfile(path))
2144 absorb_git_dir_into_superproject(path,
2145 super_prefix);
2146 } else {
2147 struct strbuf gitdir = STRBUF_INIT;
2148 submodule_name_to_gitdir(&gitdir, the_repository,
2149 sub->name);
2150 connect_work_tree_and_git_dir(path, gitdir.buf, 0);
2151 strbuf_release(&gitdir);
2153 /* make sure the index is clean as well */
2154 submodule_reset_index(path, super_prefix);
2157 if (old_head && (flags & SUBMODULE_MOVE_HEAD_FORCE)) {
2158 struct strbuf gitdir = STRBUF_INIT;
2159 submodule_name_to_gitdir(&gitdir, the_repository,
2160 sub->name);
2161 connect_work_tree_and_git_dir(path, gitdir.buf, 1);
2162 strbuf_release(&gitdir);
2166 prepare_submodule_repo_env(&cp.env);
2168 cp.git_cmd = 1;
2169 cp.no_stdin = 1;
2170 cp.dir = path;
2172 strvec_pushl(&cp.args, "read-tree", "--recurse-submodules", NULL);
2173 strvec_pushf(&cp.args, "--super-prefix=%s%s/",
2174 (super_prefix ? super_prefix : ""), path);
2176 if (flags & SUBMODULE_MOVE_HEAD_DRY_RUN)
2177 strvec_push(&cp.args, "-n");
2178 else
2179 strvec_push(&cp.args, "-u");
2181 if (flags & SUBMODULE_MOVE_HEAD_FORCE)
2182 strvec_push(&cp.args, "--reset");
2183 else
2184 strvec_push(&cp.args, "-m");
2186 if (!(flags & SUBMODULE_MOVE_HEAD_FORCE))
2187 strvec_push(&cp.args, old_head ? old_head : empty_tree_oid_hex());
2189 strvec_push(&cp.args, new_head ? new_head : empty_tree_oid_hex());
2191 if (run_command(&cp)) {
2192 ret = error(_("Submodule '%s' could not be updated."), path);
2193 goto out;
2196 if (!(flags & SUBMODULE_MOVE_HEAD_DRY_RUN)) {
2197 if (new_head) {
2198 child_process_init(&cp);
2199 /* also set the HEAD accordingly */
2200 cp.git_cmd = 1;
2201 cp.no_stdin = 1;
2202 cp.dir = path;
2204 prepare_submodule_repo_env(&cp.env);
2205 strvec_pushl(&cp.args, "update-ref", "HEAD",
2206 "--no-deref", new_head, NULL);
2208 if (run_command(&cp)) {
2209 ret = -1;
2210 goto out;
2212 } else {
2213 struct strbuf sb = STRBUF_INIT;
2215 strbuf_addf(&sb, "%s/.git", path);
2216 unlink_or_warn(sb.buf);
2217 strbuf_release(&sb);
2219 if (is_empty_dir(path))
2220 rmdir_or_warn(path);
2222 submodule_unset_core_worktree(sub);
2225 out:
2226 return ret;
2229 int validate_submodule_git_dir(char *git_dir, const char *submodule_name)
2231 size_t len = strlen(git_dir), suffix_len = strlen(submodule_name);
2232 char *p;
2233 int ret = 0;
2235 if (len <= suffix_len || (p = git_dir + len - suffix_len)[-1] != '/' ||
2236 strcmp(p, submodule_name))
2237 BUG("submodule name '%s' not a suffix of git dir '%s'",
2238 submodule_name, git_dir);
2241 * We prevent the contents of sibling submodules' git directories to
2242 * clash.
2244 * Example: having a submodule named `hippo` and another one named
2245 * `hippo/hooks` would result in the git directories
2246 * `.git/modules/hippo/` and `.git/modules/hippo/hooks/`, respectively,
2247 * but the latter directory is already designated to contain the hooks
2248 * of the former.
2250 for (; *p; p++) {
2251 if (is_dir_sep(*p)) {
2252 char c = *p;
2254 *p = '\0';
2255 if (is_git_directory(git_dir))
2256 ret = -1;
2257 *p = c;
2259 if (ret < 0)
2260 return error(_("submodule git dir '%s' is "
2261 "inside git dir '%.*s'"),
2262 git_dir,
2263 (int)(p - git_dir), git_dir);
2267 return 0;
2271 * Embeds a single submodules git directory into the superprojects git dir,
2272 * non recursively.
2274 static void relocate_single_git_dir_into_superproject(const char *path,
2275 const char *super_prefix)
2277 char *old_git_dir = NULL, *real_old_git_dir = NULL, *real_new_git_dir = NULL;
2278 struct strbuf new_gitdir = STRBUF_INIT;
2279 const struct submodule *sub;
2281 if (submodule_uses_worktrees(path))
2282 die(_("relocate_gitdir for submodule '%s' with "
2283 "more than one worktree not supported"), path);
2285 old_git_dir = xstrfmt("%s/.git", path);
2286 if (read_gitfile(old_git_dir))
2287 /* If it is an actual gitfile, it doesn't need migration. */
2288 return;
2290 real_old_git_dir = real_pathdup(old_git_dir, 1);
2292 sub = submodule_from_path(the_repository, null_oid(), path);
2293 if (!sub)
2294 die(_("could not lookup name for submodule '%s'"), path);
2296 submodule_name_to_gitdir(&new_gitdir, the_repository, sub->name);
2297 if (validate_submodule_git_dir(new_gitdir.buf, sub->name) < 0)
2298 die(_("refusing to move '%s' into an existing git dir"),
2299 real_old_git_dir);
2300 if (safe_create_leading_directories_const(new_gitdir.buf) < 0)
2301 die(_("could not create directory '%s'"), new_gitdir.buf);
2302 real_new_git_dir = real_pathdup(new_gitdir.buf, 1);
2304 fprintf(stderr, _("Migrating git directory of '%s%s' from\n'%s' to\n'%s'\n"),
2305 super_prefix ? super_prefix : "", path,
2306 real_old_git_dir, real_new_git_dir);
2308 relocate_gitdir(path, real_old_git_dir, real_new_git_dir);
2310 free(old_git_dir);
2311 free(real_old_git_dir);
2312 free(real_new_git_dir);
2313 strbuf_release(&new_gitdir);
2316 static void absorb_git_dir_into_superproject_recurse(const char *path,
2317 const char *super_prefix)
2320 struct child_process cp = CHILD_PROCESS_INIT;
2322 cp.dir = path;
2323 cp.git_cmd = 1;
2324 cp.no_stdin = 1;
2325 strvec_pushl(&cp.args, "submodule--helper",
2326 "absorbgitdirs", NULL);
2327 strvec_pushf(&cp.args, "--super-prefix=%s%s/", super_prefix ?
2328 super_prefix : "", path);
2330 prepare_submodule_repo_env(&cp.env);
2331 if (run_command(&cp))
2332 die(_("could not recurse into submodule '%s'"), path);
2336 * Migrate the git directory of the submodule given by path from
2337 * having its git directory within the working tree to the git dir nested
2338 * in its superprojects git dir under modules/.
2340 void absorb_git_dir_into_superproject(const char *path,
2341 const char *super_prefix)
2343 int err_code;
2344 const char *sub_git_dir;
2345 struct strbuf gitdir = STRBUF_INIT;
2346 strbuf_addf(&gitdir, "%s/.git", path);
2347 sub_git_dir = resolve_gitdir_gently(gitdir.buf, &err_code);
2349 /* Not populated? */
2350 if (!sub_git_dir) {
2351 const struct submodule *sub;
2352 struct strbuf sub_gitdir = STRBUF_INIT;
2354 if (err_code == READ_GITFILE_ERR_STAT_FAILED) {
2355 /* unpopulated as expected */
2356 strbuf_release(&gitdir);
2357 return;
2360 if (err_code != READ_GITFILE_ERR_NOT_A_REPO)
2361 /* We don't know what broke here. */
2362 read_gitfile_error_die(err_code, path, NULL);
2365 * Maybe populated, but no git directory was found?
2366 * This can happen if the superproject is a submodule
2367 * itself and was just absorbed. The absorption of the
2368 * superproject did not rewrite the git file links yet,
2369 * fix it now.
2371 sub = submodule_from_path(the_repository, null_oid(), path);
2372 if (!sub)
2373 die(_("could not lookup name for submodule '%s'"), path);
2374 submodule_name_to_gitdir(&sub_gitdir, the_repository, sub->name);
2375 connect_work_tree_and_git_dir(path, sub_gitdir.buf, 0);
2376 strbuf_release(&sub_gitdir);
2377 } else {
2378 /* Is it already absorbed into the superprojects git dir? */
2379 char *real_sub_git_dir = real_pathdup(sub_git_dir, 1);
2380 char *real_common_git_dir = real_pathdup(get_git_common_dir(), 1);
2382 if (!starts_with(real_sub_git_dir, real_common_git_dir))
2383 relocate_single_git_dir_into_superproject(path, super_prefix);
2385 free(real_sub_git_dir);
2386 free(real_common_git_dir);
2388 strbuf_release(&gitdir);
2390 absorb_git_dir_into_superproject_recurse(path, super_prefix);
2393 int get_superproject_working_tree(struct strbuf *buf)
2395 struct child_process cp = CHILD_PROCESS_INIT;
2396 struct strbuf sb = STRBUF_INIT;
2397 struct strbuf one_up = STRBUF_INIT;
2398 char *cwd = xgetcwd();
2399 int ret = 0;
2400 const char *subpath;
2401 int code;
2402 ssize_t len;
2404 if (!is_inside_work_tree())
2406 * FIXME:
2407 * We might have a superproject, but it is harder
2408 * to determine.
2410 return 0;
2412 if (!strbuf_realpath(&one_up, "../", 0))
2413 return 0;
2415 subpath = relative_path(cwd, one_up.buf, &sb);
2416 strbuf_release(&one_up);
2418 prepare_submodule_repo_env(&cp.env);
2419 strvec_pop(&cp.env);
2421 strvec_pushl(&cp.args, "--literal-pathspecs", "-C", "..",
2422 "ls-files", "-z", "--stage", "--full-name", "--",
2423 subpath, NULL);
2424 strbuf_reset(&sb);
2426 cp.no_stdin = 1;
2427 cp.no_stderr = 1;
2428 cp.out = -1;
2429 cp.git_cmd = 1;
2431 if (start_command(&cp))
2432 die(_("could not start ls-files in .."));
2434 len = strbuf_read(&sb, cp.out, PATH_MAX);
2435 close(cp.out);
2437 if (starts_with(sb.buf, "160000")) {
2438 int super_sub_len;
2439 int cwd_len = strlen(cwd);
2440 char *super_sub, *super_wt;
2443 * There is a superproject having this repo as a submodule.
2444 * The format is <mode> SP <hash> SP <stage> TAB <full name> \0,
2445 * We're only interested in the name after the tab.
2447 super_sub = strchr(sb.buf, '\t') + 1;
2448 super_sub_len = strlen(super_sub);
2450 if (super_sub_len > cwd_len ||
2451 strcmp(&cwd[cwd_len - super_sub_len], super_sub))
2452 BUG("returned path string doesn't match cwd?");
2454 super_wt = xstrdup(cwd);
2455 super_wt[cwd_len - super_sub_len] = '\0';
2457 strbuf_realpath(buf, super_wt, 1);
2458 ret = 1;
2459 free(super_wt);
2461 free(cwd);
2462 strbuf_release(&sb);
2464 code = finish_command(&cp);
2466 if (code == 128)
2467 /* '../' is not a git repository */
2468 return 0;
2469 if (code == 0 && len == 0)
2470 /* There is an unrelated git repository at '../' */
2471 return 0;
2472 if (code)
2473 die(_("ls-tree returned unexpected return code %d"), code);
2475 return ret;
2479 * Put the gitdir for a submodule (given relative to the main
2480 * repository worktree) into `buf`, or return -1 on error.
2482 int submodule_to_gitdir(struct strbuf *buf, const char *submodule)
2484 const struct submodule *sub;
2485 const char *git_dir;
2486 int ret = 0;
2488 strbuf_reset(buf);
2489 strbuf_addstr(buf, submodule);
2490 strbuf_complete(buf, '/');
2491 strbuf_addstr(buf, ".git");
2493 git_dir = read_gitfile(buf->buf);
2494 if (git_dir) {
2495 strbuf_reset(buf);
2496 strbuf_addstr(buf, git_dir);
2498 if (!is_git_directory(buf->buf)) {
2499 sub = submodule_from_path(the_repository, null_oid(),
2500 submodule);
2501 if (!sub) {
2502 ret = -1;
2503 goto cleanup;
2505 strbuf_reset(buf);
2506 submodule_name_to_gitdir(buf, the_repository, sub->name);
2509 cleanup:
2510 return ret;
2513 void submodule_name_to_gitdir(struct strbuf *buf, struct repository *r,
2514 const char *submodule_name)
2517 * NEEDSWORK: The current way of mapping a submodule's name to
2518 * its location in .git/modules/ has problems with some naming
2519 * schemes. For example, if a submodule is named "foo" and
2520 * another is named "foo/bar" (whether present in the same
2521 * superproject commit or not - the problem will arise if both
2522 * superproject commits have been checked out at any point in
2523 * time), or if two submodule names only have different cases in
2524 * a case-insensitive filesystem.
2526 * There are several solutions, including encoding the path in
2527 * some way, introducing a submodule.<name>.gitdir config in
2528 * .git/config (not .gitmodules) that allows overriding what the
2529 * gitdir of a submodule would be (and teach Git, upon noticing
2530 * a clash, to automatically determine a non-clashing name and
2531 * to write such a config), or introducing a
2532 * submodule.<name>.gitdir config in .gitmodules that repo
2533 * administrators can explicitly set. Nothing has been decided,
2534 * so for now, just append the name at the end of the path.
2536 strbuf_repo_git_path(buf, r, "modules/");
2537 strbuf_addstr(buf, submodule_name);