wrapper.h: move declarations for wrapper.c functions from cache.h
[git/debian.git] / submodule.c
blob13ff333f68cf08f668754a9089584847bff88038
1 #include "cache.h"
2 #include "abspath.h"
3 #include "alloc.h"
4 #include "repository.h"
5 #include "config.h"
6 #include "submodule-config.h"
7 #include "submodule.h"
8 #include "dir.h"
9 #include "diff.h"
10 #include "commit.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 "blob.h"
21 #include "thread-utils.h"
22 #include "quote.h"
23 #include "remote.h"
24 #include "worktree.h"
25 #include "parse-options.h"
26 #include "object-store.h"
27 #include "commit-reach.h"
28 #include "shallow.h"
30 static int config_update_recurse_submodules = RECURSE_SUBMODULES_OFF;
31 static int initialized_fetch_ref_tips;
32 static struct oid_array ref_tips_before_fetch;
33 static struct oid_array ref_tips_after_fetch;
36 * Check if the .gitmodules file is unmerged. Parsing of the .gitmodules file
37 * will be disabled because we can't guess what might be configured in
38 * .gitmodules unless the user resolves the conflict.
40 int is_gitmodules_unmerged(struct index_state *istate)
42 int pos = index_name_pos(istate, GITMODULES_FILE, strlen(GITMODULES_FILE));
43 if (pos < 0) { /* .gitmodules not found or isn't merged */
44 pos = -1 - pos;
45 if (istate->cache_nr > pos) { /* there is a .gitmodules */
46 const struct cache_entry *ce = istate->cache[pos];
47 if (ce_namelen(ce) == strlen(GITMODULES_FILE) &&
48 !strcmp(ce->name, GITMODULES_FILE))
49 return 1;
53 return 0;
57 * Check if the .gitmodules file is safe to write.
59 * Writing to the .gitmodules file requires that the file exists in the
60 * working tree or, if it doesn't, that a brand new .gitmodules file is going
61 * to be created (i.e. it's neither in the index nor in the current branch).
63 * It is not safe to write to .gitmodules if it's not in the working tree but
64 * it is in the index or in the current branch, because writing new values
65 * (and staging them) would blindly overwrite ALL the old content.
67 int is_writing_gitmodules_ok(void)
69 struct object_id oid;
70 return file_exists(GITMODULES_FILE) ||
71 (get_oid(GITMODULES_INDEX, &oid) < 0 && get_oid(GITMODULES_HEAD, &oid) < 0);
75 * Check if the .gitmodules file has unstaged modifications. This must be
76 * checked before allowing modifications to the .gitmodules file with the
77 * intention to stage them later, because when continuing we would stage the
78 * modifications the user didn't stage herself too. That might change in a
79 * future version when we learn to stage the changes we do ourselves without
80 * staging any previous modifications.
82 int is_staging_gitmodules_ok(struct index_state *istate)
84 int pos = index_name_pos(istate, GITMODULES_FILE, strlen(GITMODULES_FILE));
86 if ((pos >= 0) && (pos < istate->cache_nr)) {
87 struct stat st;
88 if (lstat(GITMODULES_FILE, &st) == 0 &&
89 ie_modified(istate, istate->cache[pos], &st, 0) & DATA_CHANGED)
90 return 0;
93 return 1;
96 static int for_each_remote_ref_submodule(const char *submodule,
97 each_ref_fn fn, void *cb_data)
99 return refs_for_each_remote_ref(get_submodule_ref_store(submodule),
100 fn, cb_data);
104 * Try to update the "path" entry in the "submodule.<name>" section of the
105 * .gitmodules file. Return 0 only if a .gitmodules file was found, a section
106 * with the correct path=<oldpath> setting was found and we could update it.
108 int update_path_in_gitmodules(const char *oldpath, const char *newpath)
110 struct strbuf entry = STRBUF_INIT;
111 const struct submodule *submodule;
112 int ret;
114 if (!file_exists(GITMODULES_FILE)) /* Do nothing without .gitmodules */
115 return -1;
117 if (is_gitmodules_unmerged(the_repository->index))
118 die(_("Cannot change unmerged .gitmodules, resolve merge conflicts first"));
120 submodule = submodule_from_path(the_repository, null_oid(), oldpath);
121 if (!submodule || !submodule->name) {
122 warning(_("Could not find section in .gitmodules where path=%s"), oldpath);
123 return -1;
125 strbuf_addstr(&entry, "submodule.");
126 strbuf_addstr(&entry, submodule->name);
127 strbuf_addstr(&entry, ".path");
128 ret = config_set_in_gitmodules_file_gently(entry.buf, newpath);
129 strbuf_release(&entry);
130 return ret;
134 * Try to remove the "submodule.<name>" section from .gitmodules where the given
135 * path is configured. Return 0 only if a .gitmodules file was found, a section
136 * with the correct path=<path> setting was found and we could remove it.
138 int remove_path_from_gitmodules(const char *path)
140 struct strbuf sect = STRBUF_INIT;
141 const struct submodule *submodule;
143 if (!file_exists(GITMODULES_FILE)) /* Do nothing without .gitmodules */
144 return -1;
146 if (is_gitmodules_unmerged(the_repository->index))
147 die(_("Cannot change unmerged .gitmodules, resolve merge conflicts first"));
149 submodule = submodule_from_path(the_repository, null_oid(), path);
150 if (!submodule || !submodule->name) {
151 warning(_("Could not find section in .gitmodules where path=%s"), path);
152 return -1;
154 strbuf_addstr(&sect, "submodule.");
155 strbuf_addstr(&sect, submodule->name);
156 if (git_config_rename_section_in_file(GITMODULES_FILE, sect.buf, NULL) < 0) {
157 /* Maybe the user already did that, don't error out here */
158 warning(_("Could not remove .gitmodules entry for %s"), path);
159 strbuf_release(&sect);
160 return -1;
162 strbuf_release(&sect);
163 return 0;
166 void stage_updated_gitmodules(struct index_state *istate)
168 if (add_file_to_index(istate, GITMODULES_FILE, 0))
169 die(_("staging updated .gitmodules failed"));
172 static struct string_list added_submodule_odb_paths = STRING_LIST_INIT_NODUP;
174 void add_submodule_odb_by_path(const char *path)
176 string_list_insert(&added_submodule_odb_paths, xstrdup(path));
179 int register_all_submodule_odb_as_alternates(void)
181 int i;
182 int ret = added_submodule_odb_paths.nr;
184 for (i = 0; i < added_submodule_odb_paths.nr; i++)
185 add_to_alternates_memory(added_submodule_odb_paths.items[i].string);
186 if (ret) {
187 string_list_clear(&added_submodule_odb_paths, 0);
188 trace2_data_intmax("submodule", the_repository,
189 "register_all_submodule_odb_as_alternates/registered", ret);
190 if (git_env_bool("GIT_TEST_FATAL_REGISTER_SUBMODULE_ODB", 0))
191 BUG("register_all_submodule_odb_as_alternates() called");
193 return ret;
196 void set_diffopt_flags_from_submodule_config(struct diff_options *diffopt,
197 const char *path)
199 const struct submodule *submodule = submodule_from_path(the_repository,
200 null_oid(),
201 path);
202 if (submodule) {
203 const char *ignore;
204 char *key;
206 key = xstrfmt("submodule.%s.ignore", submodule->name);
207 if (repo_config_get_string_tmp(the_repository, key, &ignore))
208 ignore = submodule->ignore;
209 free(key);
211 if (ignore)
212 handle_ignore_submodules_arg(diffopt, ignore);
213 else if (is_gitmodules_unmerged(the_repository->index))
214 diffopt->flags.ignore_submodules = 1;
218 /* Cheap function that only determines if we're interested in submodules at all */
219 int git_default_submodule_config(const char *var, const char *value,
220 void *cb UNUSED)
222 if (!strcmp(var, "submodule.recurse")) {
223 int v = git_config_bool(var, value) ?
224 RECURSE_SUBMODULES_ON : RECURSE_SUBMODULES_OFF;
225 config_update_recurse_submodules = v;
227 return 0;
230 int option_parse_recurse_submodules_worktree_updater(const struct option *opt,
231 const char *arg, int unset)
233 if (unset) {
234 config_update_recurse_submodules = RECURSE_SUBMODULES_OFF;
235 return 0;
237 if (arg)
238 config_update_recurse_submodules =
239 parse_update_recurse_submodules_arg(opt->long_name,
240 arg);
241 else
242 config_update_recurse_submodules = RECURSE_SUBMODULES_ON;
244 return 0;
248 * Determine if a submodule has been initialized at a given 'path'
251 * NEEDSWORK: Emit a warning if submodule.active exists, but is valueless,
252 * ie, the config looks like: "[submodule] active\n".
253 * Since that is an invalid pathspec, we should inform the user.
255 int is_tree_submodule_active(struct repository *repo,
256 const struct object_id *treeish_name,
257 const char *path)
259 int ret = 0;
260 char *key = NULL;
261 char *value = NULL;
262 const struct string_list *sl;
263 const struct submodule *module;
265 module = submodule_from_path(repo, treeish_name, path);
267 /* early return if there isn't a path->module mapping */
268 if (!module)
269 return 0;
271 /* submodule.<name>.active is set */
272 key = xstrfmt("submodule.%s.active", module->name);
273 if (!repo_config_get_bool(repo, key, &ret)) {
274 free(key);
275 return ret;
277 free(key);
279 /* submodule.active is set */
280 sl = repo_config_get_value_multi(repo, "submodule.active");
281 if (sl) {
282 struct pathspec ps;
283 struct strvec args = STRVEC_INIT;
284 const struct string_list_item *item;
286 for_each_string_list_item(item, sl) {
287 strvec_push(&args, item->string);
290 parse_pathspec(&ps, 0, 0, NULL, args.v);
291 ret = match_pathspec(repo->index, &ps, path, strlen(path), 0, NULL, 1);
293 strvec_clear(&args);
294 clear_pathspec(&ps);
295 return ret;
298 /* fallback to checking if the URL is set */
299 key = xstrfmt("submodule.%s.url", module->name);
300 ret = !repo_config_get_string(repo, key, &value);
302 free(value);
303 free(key);
304 return ret;
307 int is_submodule_active(struct repository *repo, const char *path)
309 return is_tree_submodule_active(repo, null_oid(), path);
312 int is_submodule_populated_gently(const char *path, int *return_error_code)
314 int ret = 0;
315 char *gitdir = xstrfmt("%s/.git", path);
317 if (resolve_gitdir_gently(gitdir, return_error_code))
318 ret = 1;
320 free(gitdir);
321 return ret;
325 * Dies if the provided 'prefix' corresponds to an unpopulated submodule
327 void die_in_unpopulated_submodule(struct index_state *istate,
328 const char *prefix)
330 int i, prefixlen;
332 if (!prefix)
333 return;
335 prefixlen = strlen(prefix);
337 for (i = 0; i < istate->cache_nr; i++) {
338 struct cache_entry *ce = istate->cache[i];
339 int ce_len = ce_namelen(ce);
341 if (!S_ISGITLINK(ce->ce_mode))
342 continue;
343 if (prefixlen <= ce_len)
344 continue;
345 if (strncmp(ce->name, prefix, ce_len))
346 continue;
347 if (prefix[ce_len] != '/')
348 continue;
350 die(_("in unpopulated submodule '%s'"), ce->name);
355 * Dies if any paths in the provided pathspec descends into a submodule
357 void die_path_inside_submodule(struct index_state *istate,
358 const struct pathspec *ps)
360 int i, j;
362 for (i = 0; i < istate->cache_nr; i++) {
363 struct cache_entry *ce = istate->cache[i];
364 int ce_len = ce_namelen(ce);
366 if (!S_ISGITLINK(ce->ce_mode))
367 continue;
369 for (j = 0; j < ps->nr ; j++) {
370 const struct pathspec_item *item = &ps->items[j];
372 if (item->len <= ce_len)
373 continue;
374 if (item->match[ce_len] != '/')
375 continue;
376 if (strncmp(ce->name, item->match, ce_len))
377 continue;
378 if (item->len == ce_len + 1)
379 continue;
381 die(_("Pathspec '%s' is in submodule '%.*s'"),
382 item->original, ce_len, ce->name);
387 enum submodule_update_type parse_submodule_update_type(const char *value)
389 if (!strcmp(value, "none"))
390 return SM_UPDATE_NONE;
391 else if (!strcmp(value, "checkout"))
392 return SM_UPDATE_CHECKOUT;
393 else if (!strcmp(value, "rebase"))
394 return SM_UPDATE_REBASE;
395 else if (!strcmp(value, "merge"))
396 return SM_UPDATE_MERGE;
397 else if (*value == '!')
398 return SM_UPDATE_COMMAND;
399 else
400 return SM_UPDATE_UNSPECIFIED;
403 int parse_submodule_update_strategy(const char *value,
404 struct submodule_update_strategy *dst)
406 enum submodule_update_type type;
408 free((void*)dst->command);
409 dst->command = NULL;
411 type = parse_submodule_update_type(value);
412 if (type == SM_UPDATE_UNSPECIFIED)
413 return -1;
415 dst->type = type;
416 if (type == SM_UPDATE_COMMAND)
417 dst->command = xstrdup(value + 1);
419 return 0;
422 const char *submodule_update_type_to_string(enum submodule_update_type type)
424 switch (type) {
425 case SM_UPDATE_CHECKOUT:
426 return "checkout";
427 case SM_UPDATE_MERGE:
428 return "merge";
429 case SM_UPDATE_REBASE:
430 return "rebase";
431 case SM_UPDATE_NONE:
432 return "none";
433 case SM_UPDATE_UNSPECIFIED:
434 case SM_UPDATE_COMMAND:
435 BUG("init_submodule() should handle type %d", type);
436 default:
437 BUG("unexpected update strategy type: %d", type);
441 void handle_ignore_submodules_arg(struct diff_options *diffopt,
442 const char *arg)
444 diffopt->flags.ignore_submodule_set = 1;
445 diffopt->flags.ignore_submodules = 0;
446 diffopt->flags.ignore_untracked_in_submodules = 0;
447 diffopt->flags.ignore_dirty_submodules = 0;
449 if (!strcmp(arg, "all"))
450 diffopt->flags.ignore_submodules = 1;
451 else if (!strcmp(arg, "untracked"))
452 diffopt->flags.ignore_untracked_in_submodules = 1;
453 else if (!strcmp(arg, "dirty"))
454 diffopt->flags.ignore_dirty_submodules = 1;
455 else if (strcmp(arg, "none"))
456 die(_("bad --ignore-submodules argument: %s"), arg);
458 * Please update _git_status() in git-completion.bash when you
459 * add new options
463 static int prepare_submodule_diff_summary(struct repository *r, struct rev_info *rev,
464 const char *path,
465 struct commit *left, struct commit *right,
466 struct commit_list *merge_bases)
468 struct commit_list *list;
470 repo_init_revisions(r, rev, NULL);
471 setup_revisions(0, NULL, rev, NULL);
472 rev->left_right = 1;
473 rev->first_parent_only = 1;
474 left->object.flags |= SYMMETRIC_LEFT;
475 add_pending_object(rev, &left->object, path);
476 add_pending_object(rev, &right->object, path);
477 for (list = merge_bases; list; list = list->next) {
478 list->item->object.flags |= UNINTERESTING;
479 add_pending_object(rev, &list->item->object,
480 oid_to_hex(&list->item->object.oid));
482 return prepare_revision_walk(rev);
485 static void print_submodule_diff_summary(struct repository *r, struct rev_info *rev, struct diff_options *o)
487 static const char format[] = " %m %s";
488 struct strbuf sb = STRBUF_INIT;
489 struct commit *commit;
491 while ((commit = get_revision(rev))) {
492 struct pretty_print_context ctx = {0};
493 ctx.date_mode = rev->date_mode;
494 ctx.output_encoding = get_log_output_encoding();
495 strbuf_setlen(&sb, 0);
496 repo_format_commit_message(r, commit, format, &sb,
497 &ctx);
498 strbuf_addch(&sb, '\n');
499 if (commit->object.flags & SYMMETRIC_LEFT)
500 diff_emit_submodule_del(o, sb.buf);
501 else
502 diff_emit_submodule_add(o, sb.buf);
504 strbuf_release(&sb);
507 void prepare_submodule_repo_env(struct strvec *out)
509 prepare_other_repo_env(out, DEFAULT_GIT_DIR_ENVIRONMENT);
512 static void prepare_submodule_repo_env_in_gitdir(struct strvec *out)
514 prepare_other_repo_env(out, ".");
518 * Initialize a repository struct for a submodule based on the provided 'path'.
520 * Returns the repository struct on success,
521 * NULL when the submodule is not present.
523 static struct repository *open_submodule(const char *path)
525 struct strbuf sb = STRBUF_INIT;
526 struct repository *out = xmalloc(sizeof(*out));
528 if (submodule_to_gitdir(&sb, path) || repo_init(out, sb.buf, NULL)) {
529 strbuf_release(&sb);
530 free(out);
531 return NULL;
534 /* Mark it as a submodule */
535 out->submodule_prefix = xstrdup(path);
537 strbuf_release(&sb);
538 return out;
542 * Helper function to display the submodule header line prior to the full
543 * summary output.
545 * If it can locate the submodule git directory it will create a repository
546 * handle for the submodule and lookup both the left and right commits and
547 * put them into the left and right pointers.
549 static void show_submodule_header(struct diff_options *o,
550 const char *path,
551 struct object_id *one, struct object_id *two,
552 unsigned dirty_submodule,
553 struct repository *sub,
554 struct commit **left, struct commit **right,
555 struct commit_list **merge_bases)
557 const char *message = NULL;
558 struct strbuf sb = STRBUF_INIT;
559 int fast_forward = 0, fast_backward = 0;
561 if (dirty_submodule & DIRTY_SUBMODULE_UNTRACKED)
562 diff_emit_submodule_untracked(o, path);
564 if (dirty_submodule & DIRTY_SUBMODULE_MODIFIED)
565 diff_emit_submodule_modified(o, path);
567 if (is_null_oid(one))
568 message = "(new submodule)";
569 else if (is_null_oid(two))
570 message = "(submodule deleted)";
572 if (!sub) {
573 if (!message)
574 message = "(commits not present)";
575 goto output_header;
579 * Attempt to lookup the commit references, and determine if this is
580 * a fast forward or fast backwards update.
582 *left = lookup_commit_reference(sub, one);
583 *right = lookup_commit_reference(sub, two);
586 * Warn about missing commits in the submodule project, but only if
587 * they aren't null.
589 if ((!is_null_oid(one) && !*left) ||
590 (!is_null_oid(two) && !*right))
591 message = "(commits not present)";
593 *merge_bases = repo_get_merge_bases(sub, *left, *right);
594 if (*merge_bases) {
595 if ((*merge_bases)->item == *left)
596 fast_forward = 1;
597 else if ((*merge_bases)->item == *right)
598 fast_backward = 1;
601 if (oideq(one, two)) {
602 strbuf_release(&sb);
603 return;
606 output_header:
607 strbuf_addf(&sb, "Submodule %s ", path);
608 strbuf_add_unique_abbrev(&sb, one, DEFAULT_ABBREV);
609 strbuf_addstr(&sb, (fast_backward || fast_forward) ? ".." : "...");
610 strbuf_add_unique_abbrev(&sb, two, DEFAULT_ABBREV);
611 if (message)
612 strbuf_addf(&sb, " %s\n", message);
613 else
614 strbuf_addf(&sb, "%s:\n", fast_backward ? " (rewind)" : "");
615 diff_emit_submodule_header(o, sb.buf);
617 strbuf_release(&sb);
620 void show_submodule_diff_summary(struct diff_options *o, const char *path,
621 struct object_id *one, struct object_id *two,
622 unsigned dirty_submodule)
624 struct rev_info rev = REV_INFO_INIT;
625 struct commit *left = NULL, *right = NULL;
626 struct commit_list *merge_bases = NULL;
627 struct repository *sub;
629 sub = open_submodule(path);
630 show_submodule_header(o, path, one, two, dirty_submodule,
631 sub, &left, &right, &merge_bases);
634 * If we don't have both a left and a right pointer, there is no
635 * reason to try and display a summary. The header line should contain
636 * all the information the user needs.
638 if (!left || !right || !sub)
639 goto out;
641 /* Treat revision walker failure the same as missing commits */
642 if (prepare_submodule_diff_summary(sub, &rev, path, left, right, merge_bases)) {
643 diff_emit_submodule_error(o, "(revision walker failed)\n");
644 goto out;
647 print_submodule_diff_summary(sub, &rev, o);
649 out:
650 free_commit_list(merge_bases);
651 release_revisions(&rev);
652 clear_commit_marks(left, ~0);
653 clear_commit_marks(right, ~0);
654 if (sub) {
655 repo_clear(sub);
656 free(sub);
660 void show_submodule_inline_diff(struct diff_options *o, const char *path,
661 struct object_id *one, struct object_id *two,
662 unsigned dirty_submodule)
664 const struct object_id *old_oid = the_hash_algo->empty_tree, *new_oid = the_hash_algo->empty_tree;
665 struct commit *left = NULL, *right = NULL;
666 struct commit_list *merge_bases = NULL;
667 struct child_process cp = CHILD_PROCESS_INIT;
668 struct strbuf sb = STRBUF_INIT;
669 struct repository *sub;
671 sub = open_submodule(path);
672 show_submodule_header(o, path, one, two, dirty_submodule,
673 sub, &left, &right, &merge_bases);
675 /* We need a valid left and right commit to display a difference */
676 if (!(left || is_null_oid(one)) ||
677 !(right || is_null_oid(two)))
678 goto done;
680 if (left)
681 old_oid = one;
682 if (right)
683 new_oid = two;
685 cp.git_cmd = 1;
686 cp.dir = path;
687 cp.out = -1;
688 cp.no_stdin = 1;
690 /* TODO: other options may need to be passed here. */
691 strvec_pushl(&cp.args, "diff", "--submodule=diff", NULL);
692 strvec_pushf(&cp.args, "--color=%s", want_color(o->use_color) ?
693 "always" : "never");
695 if (o->flags.reverse_diff) {
696 strvec_pushf(&cp.args, "--src-prefix=%s%s/",
697 o->b_prefix, path);
698 strvec_pushf(&cp.args, "--dst-prefix=%s%s/",
699 o->a_prefix, path);
700 } else {
701 strvec_pushf(&cp.args, "--src-prefix=%s%s/",
702 o->a_prefix, path);
703 strvec_pushf(&cp.args, "--dst-prefix=%s%s/",
704 o->b_prefix, path);
706 strvec_push(&cp.args, oid_to_hex(old_oid));
708 * If the submodule has modified content, we will diff against the
709 * work tree, under the assumption that the user has asked for the
710 * diff format and wishes to actually see all differences even if they
711 * haven't yet been committed to the submodule yet.
713 if (!(dirty_submodule & DIRTY_SUBMODULE_MODIFIED))
714 strvec_push(&cp.args, oid_to_hex(new_oid));
716 prepare_submodule_repo_env(&cp.env);
718 if (!is_directory(path)) {
719 /* fall back to absorbed git dir, if any */
720 if (!sub)
721 goto done;
722 cp.dir = sub->gitdir;
723 strvec_push(&cp.env, GIT_DIR_ENVIRONMENT "=.");
724 strvec_push(&cp.env, GIT_WORK_TREE_ENVIRONMENT "=.");
727 if (start_command(&cp)) {
728 diff_emit_submodule_error(o, "(diff failed)\n");
729 goto done;
732 while (strbuf_getwholeline_fd(&sb, cp.out, '\n') != EOF)
733 diff_emit_submodule_pipethrough(o, sb.buf, sb.len);
735 if (finish_command(&cp))
736 diff_emit_submodule_error(o, "(diff failed)\n");
738 done:
739 strbuf_release(&sb);
740 free_commit_list(merge_bases);
741 if (left)
742 clear_commit_marks(left, ~0);
743 if (right)
744 clear_commit_marks(right, ~0);
745 if (sub) {
746 repo_clear(sub);
747 free(sub);
751 int should_update_submodules(void)
753 return config_update_recurse_submodules == RECURSE_SUBMODULES_ON;
756 const struct submodule *submodule_from_ce(const struct cache_entry *ce)
758 if (!S_ISGITLINK(ce->ce_mode))
759 return NULL;
761 if (!should_update_submodules())
762 return NULL;
764 return submodule_from_path(the_repository, null_oid(), ce->name);
768 struct collect_changed_submodules_cb_data {
769 struct repository *repo;
770 struct string_list *changed;
771 const struct object_id *commit_oid;
775 * this would normally be two functions: default_name_from_path() and
776 * path_from_default_name(). Since the default name is the same as
777 * the submodule path we can get away with just one function which only
778 * checks whether there is a submodule in the working directory at that
779 * location.
781 static const char *default_name_or_path(const char *path_or_name)
783 int error_code;
785 if (!is_submodule_populated_gently(path_or_name, &error_code))
786 return NULL;
788 return path_or_name;
792 * Holds relevant information for a changed submodule. Used as the .util
793 * member of the changed submodule name string_list_item.
795 * (super_oid, path) allows the submodule config to be read from _some_
796 * .gitmodules file. We store this information the first time we find a
797 * superproject commit that points to the submodule, but this is
798 * arbitrary - we can choose any (super_oid, path) that matches the
799 * submodule's name.
801 * NEEDSWORK: Storing an arbitrary commit is undesirable because we can't
802 * guarantee that we're reading the commit that the user would expect. A better
803 * scheme would be to just fetch a submodule by its name. This requires two
804 * steps:
805 * - Create a function that behaves like repo_submodule_init(), but accepts a
806 * submodule name instead of treeish_name and path. This should be easy
807 * because repo_submodule_init() internally uses the submodule's name.
809 * - Replace most instances of 'struct submodule' (which is the .gitmodules
810 * config) with just the submodule name. This is OK because we expect
811 * submodule settings to be stored in .git/config (via "git submodule init"),
812 * not .gitmodules. This also lets us delete get_non_gitmodules_submodule(),
813 * which constructs a bogus 'struct submodule' for the sake of giving a
814 * placeholder name to a gitlink.
816 struct changed_submodule_data {
818 * The first superproject commit in the rev walk that points to
819 * the submodule.
821 const struct object_id *super_oid;
823 * Path to the submodule in the superproject commit referenced
824 * by 'super_oid'.
826 char *path;
827 /* The submodule commits that have changed in the rev walk. */
828 struct oid_array new_commits;
831 static void changed_submodule_data_clear(struct changed_submodule_data *cs_data)
833 oid_array_clear(&cs_data->new_commits);
834 free(cs_data->path);
837 static void collect_changed_submodules_cb(struct diff_queue_struct *q,
838 struct diff_options *options UNUSED,
839 void *data)
841 struct collect_changed_submodules_cb_data *me = data;
842 struct string_list *changed = me->changed;
843 const struct object_id *commit_oid = me->commit_oid;
844 int i;
846 for (i = 0; i < q->nr; i++) {
847 struct diff_filepair *p = q->queue[i];
848 const struct submodule *submodule;
849 const char *name;
850 struct string_list_item *item;
851 struct changed_submodule_data *cs_data;
853 if (!S_ISGITLINK(p->two->mode))
854 continue;
856 submodule = submodule_from_path(me->repo,
857 commit_oid, p->two->path);
858 if (submodule)
859 name = submodule->name;
860 else {
861 name = default_name_or_path(p->two->path);
862 /* make sure name does not collide with existing one */
863 if (name)
864 submodule = submodule_from_name(me->repo,
865 commit_oid, name);
866 if (submodule) {
867 warning(_("Submodule in commit %s at path: "
868 "'%s' collides with a submodule named "
869 "the same. Skipping it."),
870 oid_to_hex(commit_oid), p->two->path);
871 name = NULL;
875 if (!name)
876 continue;
878 item = string_list_insert(changed, name);
879 if (item->util)
880 cs_data = item->util;
881 else {
882 item->util = xcalloc(1, sizeof(struct changed_submodule_data));
883 cs_data = item->util;
884 cs_data->super_oid = commit_oid;
885 cs_data->path = xstrdup(p->two->path);
887 oid_array_append(&cs_data->new_commits, &p->two->oid);
892 * Collect the paths of submodules in 'changed' which have changed based on
893 * the revisions as specified in 'argv'. Each entry in 'changed' will also
894 * have a corresponding 'struct oid_array' (in the 'util' field) which lists
895 * what the submodule pointers were updated to during the change.
897 static void collect_changed_submodules(struct repository *r,
898 struct string_list *changed,
899 struct strvec *argv)
901 struct rev_info rev;
902 const struct commit *commit;
903 int save_warning;
904 struct setup_revision_opt s_r_opt = {
905 .assume_dashdash = 1,
908 save_warning = warn_on_object_refname_ambiguity;
909 warn_on_object_refname_ambiguity = 0;
910 repo_init_revisions(r, &rev, NULL);
911 setup_revisions(argv->nr, argv->v, &rev, &s_r_opt);
912 warn_on_object_refname_ambiguity = save_warning;
913 if (prepare_revision_walk(&rev))
914 die(_("revision walk setup failed"));
916 while ((commit = get_revision(&rev))) {
917 struct rev_info diff_rev;
918 struct collect_changed_submodules_cb_data data;
919 data.repo = r;
920 data.changed = changed;
921 data.commit_oid = &commit->object.oid;
923 repo_init_revisions(r, &diff_rev, NULL);
924 diff_rev.diffopt.output_format |= DIFF_FORMAT_CALLBACK;
925 diff_rev.diffopt.format_callback = collect_changed_submodules_cb;
926 diff_rev.diffopt.format_callback_data = &data;
927 diff_rev.dense_combined_merges = 1;
928 diff_tree_combined_merge(commit, &diff_rev);
929 release_revisions(&diff_rev);
932 reset_revision_walk();
933 release_revisions(&rev);
936 static void free_submodules_data(struct string_list *submodules)
938 struct string_list_item *item;
939 for_each_string_list_item(item, submodules)
940 changed_submodule_data_clear(item->util);
942 string_list_clear(submodules, 1);
945 static int has_remote(const char *refname UNUSED,
946 const struct object_id *oid UNUSED,
947 int flags UNUSED, void *cb_data UNUSED)
949 return 1;
952 static int append_oid_to_argv(const struct object_id *oid, void *data)
954 struct strvec *argv = data;
955 strvec_push(argv, oid_to_hex(oid));
956 return 0;
959 struct has_commit_data {
960 struct repository *repo;
961 int result;
962 const char *path;
963 const struct object_id *super_oid;
966 static int check_has_commit(const struct object_id *oid, void *data)
968 struct has_commit_data *cb = data;
969 struct repository subrepo;
970 enum object_type type;
972 if (repo_submodule_init(&subrepo, cb->repo, cb->path, cb->super_oid)) {
973 cb->result = 0;
974 /* subrepo failed to init, so don't clean it up. */
975 return 0;
978 type = oid_object_info(&subrepo, oid, NULL);
980 switch (type) {
981 case OBJ_COMMIT:
982 goto cleanup;
983 case OBJ_BAD:
985 * Object is missing or invalid. If invalid, an error message
986 * has already been printed.
988 cb->result = 0;
989 goto cleanup;
990 default:
991 die(_("submodule entry '%s' (%s) is a %s, not a commit"),
992 cb->path, oid_to_hex(oid), type_name(type));
994 cleanup:
995 repo_clear(&subrepo);
996 return 0;
999 static int submodule_has_commits(struct repository *r,
1000 const char *path,
1001 const struct object_id *super_oid,
1002 struct oid_array *commits)
1004 struct has_commit_data has_commit = {
1005 .repo = r,
1006 .result = 1,
1007 .path = path,
1008 .super_oid = super_oid
1011 oid_array_for_each_unique(commits, check_has_commit, &has_commit);
1013 if (has_commit.result) {
1015 * Even if the submodule is checked out and the commit is
1016 * present, make sure it exists in the submodule's object store
1017 * and that it is reachable from a ref.
1019 struct child_process cp = CHILD_PROCESS_INIT;
1020 struct strbuf out = STRBUF_INIT;
1022 strvec_pushl(&cp.args, "rev-list", "-n", "1", NULL);
1023 oid_array_for_each_unique(commits, append_oid_to_argv, &cp.args);
1024 strvec_pushl(&cp.args, "--not", "--all", NULL);
1026 prepare_submodule_repo_env(&cp.env);
1027 cp.git_cmd = 1;
1028 cp.no_stdin = 1;
1029 cp.dir = path;
1031 if (capture_command(&cp, &out, GIT_MAX_HEXSZ + 1) || out.len)
1032 has_commit.result = 0;
1034 strbuf_release(&out);
1037 return has_commit.result;
1040 static int submodule_needs_pushing(struct repository *r,
1041 const char *path,
1042 struct oid_array *commits)
1044 if (!submodule_has_commits(r, path, null_oid(), commits))
1046 * NOTE: We do consider it safe to return "no" here. The
1047 * correct answer would be "We do not know" instead of
1048 * "No push needed", but it is quite hard to change
1049 * the submodule pointer without having the submodule
1050 * around. If a user did however change the submodules
1051 * without having the submodule around, this indicates
1052 * an expert who knows what they are doing or a
1053 * maintainer integrating work from other people. In
1054 * both cases it should be safe to skip this check.
1056 return 0;
1058 if (for_each_remote_ref_submodule(path, has_remote, NULL) > 0) {
1059 struct child_process cp = CHILD_PROCESS_INIT;
1060 struct strbuf buf = STRBUF_INIT;
1061 int needs_pushing = 0;
1063 strvec_push(&cp.args, "rev-list");
1064 oid_array_for_each_unique(commits, append_oid_to_argv, &cp.args);
1065 strvec_pushl(&cp.args, "--not", "--remotes", "-n", "1" , NULL);
1067 prepare_submodule_repo_env(&cp.env);
1068 cp.git_cmd = 1;
1069 cp.no_stdin = 1;
1070 cp.out = -1;
1071 cp.dir = path;
1072 if (start_command(&cp))
1073 die(_("Could not run 'git rev-list <commits> --not --remotes -n 1' command in submodule %s"),
1074 path);
1075 if (strbuf_read(&buf, cp.out, the_hash_algo->hexsz + 1))
1076 needs_pushing = 1;
1077 finish_command(&cp);
1078 close(cp.out);
1079 strbuf_release(&buf);
1080 return needs_pushing;
1083 return 0;
1086 int find_unpushed_submodules(struct repository *r,
1087 struct oid_array *commits,
1088 const char *remotes_name,
1089 struct string_list *needs_pushing)
1091 struct string_list submodules = STRING_LIST_INIT_DUP;
1092 struct string_list_item *name;
1093 struct strvec argv = STRVEC_INIT;
1095 /* argv.v[0] will be ignored by setup_revisions */
1096 strvec_push(&argv, "find_unpushed_submodules");
1097 oid_array_for_each_unique(commits, append_oid_to_argv, &argv);
1098 strvec_push(&argv, "--not");
1099 strvec_pushf(&argv, "--remotes=%s", remotes_name);
1101 collect_changed_submodules(r, &submodules, &argv);
1103 for_each_string_list_item(name, &submodules) {
1104 struct changed_submodule_data *cs_data = name->util;
1105 const struct submodule *submodule;
1106 const char *path = NULL;
1108 submodule = submodule_from_name(r, null_oid(), name->string);
1109 if (submodule)
1110 path = submodule->path;
1111 else
1112 path = default_name_or_path(name->string);
1114 if (!path)
1115 continue;
1117 if (submodule_needs_pushing(r, path, &cs_data->new_commits))
1118 string_list_insert(needs_pushing, path);
1121 free_submodules_data(&submodules);
1122 strvec_clear(&argv);
1124 return needs_pushing->nr;
1127 static int push_submodule(const char *path,
1128 const struct remote *remote,
1129 const struct refspec *rs,
1130 const struct string_list *push_options,
1131 int dry_run)
1133 if (for_each_remote_ref_submodule(path, has_remote, NULL) > 0) {
1134 struct child_process cp = CHILD_PROCESS_INIT;
1135 strvec_push(&cp.args, "push");
1137 * When recursing into a submodule, treat any "only" configurations as "on-
1138 * demand", since "only" would not work (we need all submodules to be pushed
1139 * in order to be able to push the superproject).
1141 strvec_push(&cp.args, "--recurse-submodules=only-is-on-demand");
1142 if (dry_run)
1143 strvec_push(&cp.args, "--dry-run");
1145 if (push_options && push_options->nr) {
1146 const struct string_list_item *item;
1147 for_each_string_list_item(item, push_options)
1148 strvec_pushf(&cp.args, "--push-option=%s",
1149 item->string);
1152 if (remote->origin != REMOTE_UNCONFIGURED) {
1153 int i;
1154 strvec_push(&cp.args, remote->name);
1155 for (i = 0; i < rs->raw_nr; i++)
1156 strvec_push(&cp.args, rs->raw[i]);
1159 prepare_submodule_repo_env(&cp.env);
1160 cp.git_cmd = 1;
1161 cp.no_stdin = 1;
1162 cp.dir = path;
1163 if (run_command(&cp))
1164 return 0;
1165 close(cp.out);
1168 return 1;
1172 * Perform a check in the submodule to see if the remote and refspec work.
1173 * Die if the submodule can't be pushed.
1175 static void submodule_push_check(const char *path, const char *head,
1176 const struct remote *remote,
1177 const struct refspec *rs)
1179 struct child_process cp = CHILD_PROCESS_INIT;
1180 int i;
1182 strvec_push(&cp.args, "submodule--helper");
1183 strvec_push(&cp.args, "push-check");
1184 strvec_push(&cp.args, head);
1185 strvec_push(&cp.args, remote->name);
1187 for (i = 0; i < rs->raw_nr; i++)
1188 strvec_push(&cp.args, rs->raw[i]);
1190 prepare_submodule_repo_env(&cp.env);
1191 cp.git_cmd = 1;
1192 cp.no_stdin = 1;
1193 cp.no_stdout = 1;
1194 cp.dir = path;
1197 * Simply indicate if 'submodule--helper push-check' failed.
1198 * More detailed error information will be provided by the
1199 * child process.
1201 if (run_command(&cp))
1202 die(_("process for submodule '%s' failed"), path);
1205 int push_unpushed_submodules(struct repository *r,
1206 struct oid_array *commits,
1207 const struct remote *remote,
1208 const struct refspec *rs,
1209 const struct string_list *push_options,
1210 int dry_run)
1212 int i, ret = 1;
1213 struct string_list needs_pushing = STRING_LIST_INIT_DUP;
1215 if (!find_unpushed_submodules(r, commits,
1216 remote->name, &needs_pushing))
1217 return 1;
1220 * Verify that the remote and refspec can be propagated to all
1221 * submodules. This check can be skipped if the remote and refspec
1222 * won't be propagated due to the remote being unconfigured (e.g. a URL
1223 * instead of a remote name).
1225 if (remote->origin != REMOTE_UNCONFIGURED) {
1226 char *head;
1227 struct object_id head_oid;
1229 head = resolve_refdup("HEAD", 0, &head_oid, NULL);
1230 if (!head)
1231 die(_("Failed to resolve HEAD as a valid ref."));
1233 for (i = 0; i < needs_pushing.nr; i++)
1234 submodule_push_check(needs_pushing.items[i].string,
1235 head, remote, rs);
1236 free(head);
1239 /* Actually push the submodules */
1240 for (i = 0; i < needs_pushing.nr; i++) {
1241 const char *path = needs_pushing.items[i].string;
1242 fprintf(stderr, _("Pushing submodule '%s'\n"), path);
1243 if (!push_submodule(path, remote, rs,
1244 push_options, dry_run)) {
1245 fprintf(stderr, _("Unable to push submodule '%s'\n"), path);
1246 ret = 0;
1250 string_list_clear(&needs_pushing, 0);
1252 return ret;
1255 static int append_oid_to_array(const char *ref UNUSED,
1256 const struct object_id *oid,
1257 int flags UNUSED, void *data)
1259 struct oid_array *array = data;
1260 oid_array_append(array, oid);
1261 return 0;
1264 void check_for_new_submodule_commits(struct object_id *oid)
1266 if (!initialized_fetch_ref_tips) {
1267 for_each_ref(append_oid_to_array, &ref_tips_before_fetch);
1268 initialized_fetch_ref_tips = 1;
1271 oid_array_append(&ref_tips_after_fetch, oid);
1275 * Returns 1 if there is at least one submodule gitdir in
1276 * $GIT_DIR/modules and 0 otherwise. This follows
1277 * submodule_name_to_gitdir(), which looks for submodules in
1278 * $GIT_DIR/modules, not $GIT_COMMON_DIR.
1280 * A submodule can be moved to $GIT_DIR/modules manually by running "git
1281 * submodule absorbgitdirs", or it may be initialized there by "git
1282 * submodule update".
1284 static int repo_has_absorbed_submodules(struct repository *r)
1286 int ret;
1287 struct strbuf buf = STRBUF_INIT;
1289 strbuf_repo_git_path(&buf, r, "modules/");
1290 ret = file_exists(buf.buf) && !is_empty_dir(buf.buf);
1291 strbuf_release(&buf);
1292 return ret;
1295 static void calculate_changed_submodule_paths(struct repository *r,
1296 struct string_list *changed_submodule_names)
1298 struct strvec argv = STRVEC_INIT;
1299 struct string_list_item *name;
1301 /* No need to check if no submodules would be fetched */
1302 if (!submodule_from_path(r, NULL, NULL) &&
1303 !repo_has_absorbed_submodules(r))
1304 return;
1306 strvec_push(&argv, "--"); /* argv[0] program name */
1307 oid_array_for_each_unique(&ref_tips_after_fetch,
1308 append_oid_to_argv, &argv);
1309 strvec_push(&argv, "--not");
1310 oid_array_for_each_unique(&ref_tips_before_fetch,
1311 append_oid_to_argv, &argv);
1314 * Collect all submodules (whether checked out or not) for which new
1315 * commits have been recorded upstream in "changed_submodule_names".
1317 collect_changed_submodules(r, changed_submodule_names, &argv);
1319 for_each_string_list_item(name, changed_submodule_names) {
1320 struct changed_submodule_data *cs_data = name->util;
1321 const struct submodule *submodule;
1322 const char *path = NULL;
1324 submodule = submodule_from_name(r, null_oid(), name->string);
1325 if (submodule)
1326 path = submodule->path;
1327 else
1328 path = default_name_or_path(name->string);
1330 if (!path)
1331 continue;
1333 if (submodule_has_commits(r, path, null_oid(), &cs_data->new_commits)) {
1334 changed_submodule_data_clear(cs_data);
1335 *name->string = '\0';
1339 string_list_remove_empty_items(changed_submodule_names, 1);
1341 strvec_clear(&argv);
1342 oid_array_clear(&ref_tips_before_fetch);
1343 oid_array_clear(&ref_tips_after_fetch);
1344 initialized_fetch_ref_tips = 0;
1347 int submodule_touches_in_range(struct repository *r,
1348 struct object_id *excl_oid,
1349 struct object_id *incl_oid)
1351 struct string_list subs = STRING_LIST_INIT_DUP;
1352 struct strvec args = STRVEC_INIT;
1353 int ret;
1355 /* No need to check if there are no submodules configured */
1356 if (!submodule_from_path(r, NULL, NULL))
1357 return 0;
1359 strvec_push(&args, "--"); /* args[0] program name */
1360 strvec_push(&args, oid_to_hex(incl_oid));
1361 if (!is_null_oid(excl_oid)) {
1362 strvec_push(&args, "--not");
1363 strvec_push(&args, oid_to_hex(excl_oid));
1366 collect_changed_submodules(r, &subs, &args);
1367 ret = subs.nr;
1369 strvec_clear(&args);
1371 free_submodules_data(&subs);
1372 return ret;
1375 struct submodule_parallel_fetch {
1377 * The index of the last index entry processed by
1378 * get_fetch_task_from_index().
1380 int index_count;
1382 * The index of the last string_list entry processed by
1383 * get_fetch_task_from_changed().
1385 int changed_count;
1386 struct strvec args;
1387 struct repository *r;
1388 const char *prefix;
1389 int command_line_option;
1390 int default_option;
1391 int quiet;
1392 int result;
1395 * Names of submodules that have new commits. Generated by
1396 * walking the newly fetched superproject commits.
1398 struct string_list changed_submodule_names;
1400 * Names of submodules that have already been processed. Lets us
1401 * avoid fetching the same submodule more than once.
1403 struct string_list seen_submodule_names;
1405 /* Pending fetches by OIDs */
1406 struct fetch_task **oid_fetch_tasks;
1407 int oid_fetch_tasks_nr, oid_fetch_tasks_alloc;
1409 struct strbuf submodules_with_errors;
1411 #define SPF_INIT { \
1412 .args = STRVEC_INIT, \
1413 .changed_submodule_names = STRING_LIST_INIT_DUP, \
1414 .seen_submodule_names = STRING_LIST_INIT_DUP, \
1415 .submodules_with_errors = STRBUF_INIT, \
1418 static int get_fetch_recurse_config(const struct submodule *submodule,
1419 struct submodule_parallel_fetch *spf)
1421 if (spf->command_line_option != RECURSE_SUBMODULES_DEFAULT)
1422 return spf->command_line_option;
1424 if (submodule) {
1425 char *key;
1426 const char *value;
1428 int fetch_recurse = submodule->fetch_recurse;
1429 key = xstrfmt("submodule.%s.fetchRecurseSubmodules", submodule->name);
1430 if (!repo_config_get_string_tmp(spf->r, key, &value)) {
1431 fetch_recurse = parse_fetch_recurse_submodules_arg(key, value);
1433 free(key);
1435 if (fetch_recurse != RECURSE_SUBMODULES_NONE)
1436 /* local config overrules everything except commandline */
1437 return fetch_recurse;
1440 return spf->default_option;
1444 * Fetch in progress (if callback data) or
1445 * pending (if in oid_fetch_tasks in struct submodule_parallel_fetch)
1447 struct fetch_task {
1448 struct repository *repo;
1449 const struct submodule *sub;
1450 unsigned free_sub : 1; /* Do we need to free the submodule? */
1451 const char *default_argv; /* The default fetch mode. */
1452 struct strvec git_args; /* Args for the child git process. */
1454 struct oid_array *commits; /* Ensure these commits are fetched */
1458 * When a submodule is not defined in .gitmodules, we cannot access it
1459 * via the regular submodule-config. Create a fake submodule, which we can
1460 * work on.
1462 static const struct submodule *get_non_gitmodules_submodule(const char *path)
1464 struct submodule *ret = NULL;
1465 const char *name = default_name_or_path(path);
1467 if (!name)
1468 return NULL;
1470 ret = xmalloc(sizeof(*ret));
1471 memset(ret, 0, sizeof(*ret));
1472 ret->path = name;
1473 ret->name = name;
1475 return (const struct submodule *) ret;
1478 static void fetch_task_release(struct fetch_task *p)
1480 if (p->free_sub)
1481 free((void*)p->sub);
1482 p->free_sub = 0;
1483 p->sub = NULL;
1485 if (p->repo)
1486 repo_clear(p->repo);
1487 FREE_AND_NULL(p->repo);
1489 strvec_clear(&p->git_args);
1492 static struct repository *get_submodule_repo_for(struct repository *r,
1493 const char *path,
1494 const struct object_id *treeish_name)
1496 struct repository *ret = xmalloc(sizeof(*ret));
1498 if (repo_submodule_init(ret, r, path, treeish_name)) {
1499 free(ret);
1500 return NULL;
1503 return ret;
1506 static struct fetch_task *fetch_task_create(struct submodule_parallel_fetch *spf,
1507 const char *path,
1508 const struct object_id *treeish_name)
1510 struct fetch_task *task = xmalloc(sizeof(*task));
1511 memset(task, 0, sizeof(*task));
1513 task->sub = submodule_from_path(spf->r, treeish_name, path);
1515 if (!task->sub) {
1517 * No entry in .gitmodules? Technically not a submodule,
1518 * but historically we supported repositories that happen to be
1519 * in-place where a gitlink is. Keep supporting them.
1521 task->sub = get_non_gitmodules_submodule(path);
1522 if (!task->sub)
1523 goto cleanup;
1525 task->free_sub = 1;
1528 if (string_list_lookup(&spf->seen_submodule_names, task->sub->name))
1529 goto cleanup;
1531 switch (get_fetch_recurse_config(task->sub, spf))
1533 default:
1534 case RECURSE_SUBMODULES_DEFAULT:
1535 case RECURSE_SUBMODULES_ON_DEMAND:
1536 if (!task->sub ||
1537 !string_list_lookup(
1538 &spf->changed_submodule_names,
1539 task->sub->name))
1540 goto cleanup;
1541 task->default_argv = "on-demand";
1542 break;
1543 case RECURSE_SUBMODULES_ON:
1544 task->default_argv = "yes";
1545 break;
1546 case RECURSE_SUBMODULES_OFF:
1547 goto cleanup;
1550 task->repo = get_submodule_repo_for(spf->r, path, treeish_name);
1552 return task;
1554 cleanup:
1555 fetch_task_release(task);
1556 free(task);
1557 return NULL;
1560 static struct fetch_task *
1561 get_fetch_task_from_index(struct submodule_parallel_fetch *spf,
1562 struct strbuf *err)
1564 for (; spf->index_count < spf->r->index->cache_nr; spf->index_count++) {
1565 const struct cache_entry *ce =
1566 spf->r->index->cache[spf->index_count];
1567 struct fetch_task *task;
1569 if (!S_ISGITLINK(ce->ce_mode))
1570 continue;
1572 task = fetch_task_create(spf, ce->name, null_oid());
1573 if (!task)
1574 continue;
1576 if (task->repo) {
1577 if (!spf->quiet)
1578 strbuf_addf(err, _("Fetching submodule %s%s\n"),
1579 spf->prefix, ce->name);
1581 spf->index_count++;
1582 return task;
1583 } else {
1584 struct strbuf empty_submodule_path = STRBUF_INIT;
1586 fetch_task_release(task);
1587 free(task);
1590 * An empty directory is normal,
1591 * the submodule is not initialized
1593 strbuf_addf(&empty_submodule_path, "%s/%s/",
1594 spf->r->worktree,
1595 ce->name);
1596 if (S_ISGITLINK(ce->ce_mode) &&
1597 !is_empty_dir(empty_submodule_path.buf)) {
1598 spf->result = 1;
1599 strbuf_addf(err,
1600 _("Could not access submodule '%s'\n"),
1601 ce->name);
1603 strbuf_release(&empty_submodule_path);
1606 return NULL;
1609 static struct fetch_task *
1610 get_fetch_task_from_changed(struct submodule_parallel_fetch *spf,
1611 struct strbuf *err)
1613 for (; spf->changed_count < spf->changed_submodule_names.nr;
1614 spf->changed_count++) {
1615 struct string_list_item item =
1616 spf->changed_submodule_names.items[spf->changed_count];
1617 struct changed_submodule_data *cs_data = item.util;
1618 struct fetch_task *task;
1620 if (!is_tree_submodule_active(spf->r, cs_data->super_oid,cs_data->path))
1621 continue;
1623 task = fetch_task_create(spf, cs_data->path,
1624 cs_data->super_oid);
1625 if (!task)
1626 continue;
1628 if (!task->repo) {
1629 strbuf_addf(err, _("Could not access submodule '%s' at commit %s\n"),
1630 cs_data->path,
1631 find_unique_abbrev(cs_data->super_oid, DEFAULT_ABBREV));
1633 fetch_task_release(task);
1634 free(task);
1635 continue;
1638 if (!spf->quiet)
1639 strbuf_addf(err,
1640 _("Fetching submodule %s%s at commit %s\n"),
1641 spf->prefix, task->sub->path,
1642 find_unique_abbrev(cs_data->super_oid,
1643 DEFAULT_ABBREV));
1645 spf->changed_count++;
1647 * NEEDSWORK: Submodules set/unset a value for
1648 * core.worktree when they are populated/unpopulated by
1649 * "git checkout" (and similar commands, see
1650 * submodule_move_head() and
1651 * connect_work_tree_and_git_dir()), but if the
1652 * submodule is unpopulated in another way (e.g. "git
1653 * rm", "rm -r"), core.worktree will still be set even
1654 * though the directory doesn't exist, and the child
1655 * process will crash while trying to chdir into the
1656 * nonexistent directory.
1658 * In this case, we know that the submodule has no
1659 * working tree, so we can work around this by
1660 * setting "--work-tree=." (--bare does not work because
1661 * worktree settings take precedence over bare-ness).
1662 * However, this is not necessarily true in other cases,
1663 * so a generalized solution is still necessary.
1665 * Possible solutions:
1666 * - teach "git [add|rm]" to unset core.worktree and
1667 * discourage users from removing submodules without
1668 * using a Git command.
1669 * - teach submodule child processes to ignore stale
1670 * core.worktree values.
1672 strvec_push(&task->git_args, "--work-tree=.");
1673 return task;
1675 return NULL;
1678 static int get_next_submodule(struct child_process *cp, struct strbuf *err,
1679 void *data, void **task_cb)
1681 struct submodule_parallel_fetch *spf = data;
1682 struct fetch_task *task =
1683 get_fetch_task_from_index(spf, err);
1684 if (!task)
1685 task = get_fetch_task_from_changed(spf, err);
1687 if (task) {
1688 struct strbuf submodule_prefix = STRBUF_INIT;
1690 child_process_init(cp);
1691 cp->dir = task->repo->gitdir;
1692 prepare_submodule_repo_env_in_gitdir(&cp->env);
1693 cp->git_cmd = 1;
1694 strvec_init(&cp->args);
1695 if (task->git_args.nr)
1696 strvec_pushv(&cp->args, task->git_args.v);
1697 strvec_pushv(&cp->args, spf->args.v);
1698 strvec_push(&cp->args, task->default_argv);
1699 strvec_push(&cp->args, "--submodule-prefix");
1701 strbuf_addf(&submodule_prefix, "%s%s/",
1702 spf->prefix,
1703 task->sub->path);
1704 strvec_push(&cp->args, submodule_prefix.buf);
1705 *task_cb = task;
1707 strbuf_release(&submodule_prefix);
1708 string_list_insert(&spf->seen_submodule_names, task->sub->name);
1709 return 1;
1712 if (spf->oid_fetch_tasks_nr) {
1713 struct fetch_task *task =
1714 spf->oid_fetch_tasks[spf->oid_fetch_tasks_nr - 1];
1715 struct strbuf submodule_prefix = STRBUF_INIT;
1716 spf->oid_fetch_tasks_nr--;
1718 strbuf_addf(&submodule_prefix, "%s%s/",
1719 spf->prefix, task->sub->path);
1721 child_process_init(cp);
1722 prepare_submodule_repo_env_in_gitdir(&cp->env);
1723 cp->git_cmd = 1;
1724 cp->dir = task->repo->gitdir;
1726 strvec_init(&cp->args);
1727 strvec_pushv(&cp->args, spf->args.v);
1728 strvec_push(&cp->args, "on-demand");
1729 strvec_push(&cp->args, "--submodule-prefix");
1730 strvec_push(&cp->args, submodule_prefix.buf);
1732 /* NEEDSWORK: have get_default_remote from submodule--helper */
1733 strvec_push(&cp->args, "origin");
1734 oid_array_for_each_unique(task->commits,
1735 append_oid_to_argv, &cp->args);
1737 *task_cb = task;
1738 strbuf_release(&submodule_prefix);
1739 return 1;
1742 return 0;
1745 static int fetch_start_failure(struct strbuf *err UNUSED,
1746 void *cb, void *task_cb)
1748 struct submodule_parallel_fetch *spf = cb;
1749 struct fetch_task *task = task_cb;
1751 spf->result = 1;
1753 fetch_task_release(task);
1754 return 0;
1757 static int commit_missing_in_sub(const struct object_id *oid, void *data)
1759 struct repository *subrepo = data;
1761 enum object_type type = oid_object_info(subrepo, oid, NULL);
1763 return type != OBJ_COMMIT;
1766 static int fetch_finish(int retvalue, struct strbuf *err UNUSED,
1767 void *cb, void *task_cb)
1769 struct submodule_parallel_fetch *spf = cb;
1770 struct fetch_task *task = task_cb;
1772 struct string_list_item *it;
1773 struct changed_submodule_data *cs_data;
1775 if (!task || !task->sub)
1776 BUG("callback cookie bogus");
1778 if (retvalue) {
1780 * NEEDSWORK: This indicates that the overall fetch
1781 * failed, even though there may be a subsequent fetch
1782 * by commit hash that might work. It may be a good
1783 * idea to not indicate failure in this case, and only
1784 * indicate failure if the subsequent fetch fails.
1786 spf->result = 1;
1788 strbuf_addf(&spf->submodules_with_errors, "\t%s\n",
1789 task->sub->name);
1792 /* Is this the second time we process this submodule? */
1793 if (task->commits)
1794 goto out;
1796 it = string_list_lookup(&spf->changed_submodule_names, task->sub->name);
1797 if (!it)
1798 /* Could be an unchanged submodule, not contained in the list */
1799 goto out;
1801 cs_data = it->util;
1802 oid_array_filter(&cs_data->new_commits,
1803 commit_missing_in_sub,
1804 task->repo);
1806 /* Are there commits we want, but do not exist? */
1807 if (cs_data->new_commits.nr) {
1808 task->commits = &cs_data->new_commits;
1809 ALLOC_GROW(spf->oid_fetch_tasks,
1810 spf->oid_fetch_tasks_nr + 1,
1811 spf->oid_fetch_tasks_alloc);
1812 spf->oid_fetch_tasks[spf->oid_fetch_tasks_nr] = task;
1813 spf->oid_fetch_tasks_nr++;
1814 return 0;
1817 out:
1818 fetch_task_release(task);
1820 return 0;
1823 int fetch_submodules(struct repository *r,
1824 const struct strvec *options,
1825 const char *prefix, int command_line_option,
1826 int default_option,
1827 int quiet, int max_parallel_jobs)
1829 int i;
1830 struct submodule_parallel_fetch spf = SPF_INIT;
1831 const struct run_process_parallel_opts opts = {
1832 .tr2_category = "submodule",
1833 .tr2_label = "parallel/fetch",
1835 .processes = max_parallel_jobs,
1837 .get_next_task = get_next_submodule,
1838 .start_failure = fetch_start_failure,
1839 .task_finished = fetch_finish,
1840 .data = &spf,
1843 spf.r = r;
1844 spf.command_line_option = command_line_option;
1845 spf.default_option = default_option;
1846 spf.quiet = quiet;
1847 spf.prefix = prefix;
1849 if (!r->worktree)
1850 goto out;
1852 if (repo_read_index(r) < 0)
1853 die(_("index file corrupt"));
1855 strvec_push(&spf.args, "fetch");
1856 for (i = 0; i < options->nr; i++)
1857 strvec_push(&spf.args, options->v[i]);
1858 strvec_push(&spf.args, "--recurse-submodules-default");
1859 /* default value, "--submodule-prefix" and its value are added later */
1861 calculate_changed_submodule_paths(r, &spf.changed_submodule_names);
1862 string_list_sort(&spf.changed_submodule_names);
1863 run_processes_parallel(&opts);
1865 if (spf.submodules_with_errors.len > 0)
1866 fprintf(stderr, _("Errors during submodule fetch:\n%s"),
1867 spf.submodules_with_errors.buf);
1870 strvec_clear(&spf.args);
1871 out:
1872 free_submodules_data(&spf.changed_submodule_names);
1873 return spf.result;
1876 unsigned is_submodule_modified(const char *path, int ignore_untracked)
1878 struct child_process cp = CHILD_PROCESS_INIT;
1879 struct strbuf buf = STRBUF_INIT;
1880 FILE *fp;
1881 unsigned dirty_submodule = 0;
1882 const char *git_dir;
1883 int ignore_cp_exit_code = 0;
1885 strbuf_addf(&buf, "%s/.git", path);
1886 git_dir = read_gitfile(buf.buf);
1887 if (!git_dir)
1888 git_dir = buf.buf;
1889 if (!is_git_directory(git_dir)) {
1890 if (is_directory(git_dir))
1891 die(_("'%s' not recognized as a git repository"), git_dir);
1892 strbuf_release(&buf);
1893 /* The submodule is not checked out, so it is not modified */
1894 return 0;
1896 strbuf_reset(&buf);
1898 strvec_pushl(&cp.args, "status", "--porcelain=2", NULL);
1899 if (ignore_untracked)
1900 strvec_push(&cp.args, "-uno");
1902 prepare_submodule_repo_env(&cp.env);
1903 cp.git_cmd = 1;
1904 cp.no_stdin = 1;
1905 cp.out = -1;
1906 cp.dir = path;
1907 if (start_command(&cp))
1908 die(_("Could not run 'git status --porcelain=2' in submodule %s"), path);
1910 fp = xfdopen(cp.out, "r");
1911 while (strbuf_getwholeline(&buf, fp, '\n') != EOF) {
1912 /* regular untracked files */
1913 if (buf.buf[0] == '?')
1914 dirty_submodule |= DIRTY_SUBMODULE_UNTRACKED;
1916 if (buf.buf[0] == 'u' ||
1917 buf.buf[0] == '1' ||
1918 buf.buf[0] == '2') {
1919 /* T = line type, XY = status, SSSS = submodule state */
1920 if (buf.len < strlen("T XY SSSS"))
1921 BUG("invalid status --porcelain=2 line %s",
1922 buf.buf);
1924 if (buf.buf[5] == 'S' && buf.buf[8] == 'U')
1925 /* nested untracked file */
1926 dirty_submodule |= DIRTY_SUBMODULE_UNTRACKED;
1928 if (buf.buf[0] == 'u' ||
1929 buf.buf[0] == '2' ||
1930 memcmp(buf.buf + 5, "S..U", 4))
1931 /* other change */
1932 dirty_submodule |= DIRTY_SUBMODULE_MODIFIED;
1935 if ((dirty_submodule & DIRTY_SUBMODULE_MODIFIED) &&
1936 ((dirty_submodule & DIRTY_SUBMODULE_UNTRACKED) ||
1937 ignore_untracked)) {
1939 * We're not interested in any further information from
1940 * the child any more, neither output nor its exit code.
1942 ignore_cp_exit_code = 1;
1943 break;
1946 fclose(fp);
1948 if (finish_command(&cp) && !ignore_cp_exit_code)
1949 die(_("'git status --porcelain=2' failed in submodule %s"), path);
1951 strbuf_release(&buf);
1952 return dirty_submodule;
1955 int submodule_uses_gitfile(const char *path)
1957 struct child_process cp = CHILD_PROCESS_INIT;
1958 struct strbuf buf = STRBUF_INIT;
1959 const char *git_dir;
1961 strbuf_addf(&buf, "%s/.git", path);
1962 git_dir = read_gitfile(buf.buf);
1963 if (!git_dir) {
1964 strbuf_release(&buf);
1965 return 0;
1967 strbuf_release(&buf);
1969 /* Now test that all nested submodules use a gitfile too */
1970 strvec_pushl(&cp.args,
1971 "submodule", "foreach", "--quiet", "--recursive",
1972 "test -f .git", NULL);
1974 prepare_submodule_repo_env(&cp.env);
1975 cp.git_cmd = 1;
1976 cp.no_stdin = 1;
1977 cp.no_stderr = 1;
1978 cp.no_stdout = 1;
1979 cp.dir = path;
1980 if (run_command(&cp))
1981 return 0;
1983 return 1;
1987 * Check if it is a bad idea to remove a submodule, i.e. if we'd lose data
1988 * when doing so.
1990 * Return 1 if we'd lose data, return 0 if the removal is fine,
1991 * and negative values for errors.
1993 int bad_to_remove_submodule(const char *path, unsigned flags)
1995 ssize_t len;
1996 struct child_process cp = CHILD_PROCESS_INIT;
1997 struct strbuf buf = STRBUF_INIT;
1998 int ret = 0;
2000 if (!file_exists(path) || is_empty_dir(path))
2001 return 0;
2003 if (!submodule_uses_gitfile(path))
2004 return 1;
2006 strvec_pushl(&cp.args, "status", "--porcelain",
2007 "--ignore-submodules=none", NULL);
2009 if (flags & SUBMODULE_REMOVAL_IGNORE_UNTRACKED)
2010 strvec_push(&cp.args, "-uno");
2011 else
2012 strvec_push(&cp.args, "-uall");
2014 if (!(flags & SUBMODULE_REMOVAL_IGNORE_IGNORED_UNTRACKED))
2015 strvec_push(&cp.args, "--ignored");
2017 prepare_submodule_repo_env(&cp.env);
2018 cp.git_cmd = 1;
2019 cp.no_stdin = 1;
2020 cp.out = -1;
2021 cp.dir = path;
2022 if (start_command(&cp)) {
2023 if (flags & SUBMODULE_REMOVAL_DIE_ON_ERROR)
2024 die(_("could not start 'git status' in submodule '%s'"),
2025 path);
2026 ret = -1;
2027 goto out;
2030 len = strbuf_read(&buf, cp.out, 1024);
2031 if (len > 2)
2032 ret = 1;
2033 close(cp.out);
2035 if (finish_command(&cp)) {
2036 if (flags & SUBMODULE_REMOVAL_DIE_ON_ERROR)
2037 die(_("could not run 'git status' in submodule '%s'"),
2038 path);
2039 ret = -1;
2041 out:
2042 strbuf_release(&buf);
2043 return ret;
2046 void submodule_unset_core_worktree(const struct submodule *sub)
2048 struct strbuf config_path = STRBUF_INIT;
2050 submodule_name_to_gitdir(&config_path, the_repository, sub->name);
2051 strbuf_addstr(&config_path, "/config");
2053 if (git_config_set_in_file_gently(config_path.buf, "core.worktree", NULL))
2054 warning(_("Could not unset core.worktree setting in submodule '%s'"),
2055 sub->path);
2057 strbuf_release(&config_path);
2060 static int submodule_has_dirty_index(const struct submodule *sub)
2062 struct child_process cp = CHILD_PROCESS_INIT;
2064 prepare_submodule_repo_env(&cp.env);
2066 cp.git_cmd = 1;
2067 strvec_pushl(&cp.args, "diff-index", "--quiet",
2068 "--cached", "HEAD", NULL);
2069 cp.no_stdin = 1;
2070 cp.no_stdout = 1;
2071 cp.dir = sub->path;
2072 if (start_command(&cp))
2073 die(_("could not recurse into submodule '%s'"), sub->path);
2075 return finish_command(&cp);
2078 static void submodule_reset_index(const char *path, const char *super_prefix)
2080 struct child_process cp = CHILD_PROCESS_INIT;
2081 prepare_submodule_repo_env(&cp.env);
2083 cp.git_cmd = 1;
2084 cp.no_stdin = 1;
2085 cp.dir = path;
2087 /* TODO: determine if this might overwright untracked files */
2088 strvec_pushl(&cp.args, "read-tree", "-u", "--reset", NULL);
2089 strvec_pushf(&cp.args, "--super-prefix=%s%s/",
2090 (super_prefix ? super_prefix : ""), path);
2092 strvec_push(&cp.args, empty_tree_oid_hex());
2094 if (run_command(&cp))
2095 die(_("could not reset submodule index"));
2099 * Moves a submodule at a given path from a given head to another new head.
2100 * For edge cases (a submodule coming into existence or removing a submodule)
2101 * pass NULL for old or new respectively.
2103 int submodule_move_head(const char *path, const char *super_prefix,
2104 const char *old_head, const char *new_head,
2105 unsigned flags)
2107 int ret = 0;
2108 struct child_process cp = CHILD_PROCESS_INIT;
2109 const struct submodule *sub;
2110 int *error_code_ptr, error_code;
2112 if (!is_submodule_active(the_repository, path))
2113 return 0;
2115 if (flags & SUBMODULE_MOVE_HEAD_FORCE)
2117 * Pass non NULL pointer to is_submodule_populated_gently
2118 * to prevent die()-ing. We'll use connect_work_tree_and_git_dir
2119 * to fixup the submodule in the force case later.
2121 error_code_ptr = &error_code;
2122 else
2123 error_code_ptr = NULL;
2125 if (old_head && !is_submodule_populated_gently(path, error_code_ptr))
2126 return 0;
2128 sub = submodule_from_path(the_repository, null_oid(), path);
2130 if (!sub)
2131 BUG("could not get submodule information for '%s'", path);
2133 if (old_head && !(flags & SUBMODULE_MOVE_HEAD_FORCE)) {
2134 /* Check if the submodule has a dirty index. */
2135 if (submodule_has_dirty_index(sub))
2136 return error(_("submodule '%s' has dirty index"), path);
2139 if (!(flags & SUBMODULE_MOVE_HEAD_DRY_RUN)) {
2140 if (old_head) {
2141 if (!submodule_uses_gitfile(path))
2142 absorb_git_dir_into_superproject(path,
2143 super_prefix);
2144 } else {
2145 struct strbuf gitdir = STRBUF_INIT;
2146 submodule_name_to_gitdir(&gitdir, the_repository,
2147 sub->name);
2148 connect_work_tree_and_git_dir(path, gitdir.buf, 0);
2149 strbuf_release(&gitdir);
2151 /* make sure the index is clean as well */
2152 submodule_reset_index(path, super_prefix);
2155 if (old_head && (flags & SUBMODULE_MOVE_HEAD_FORCE)) {
2156 struct strbuf gitdir = STRBUF_INIT;
2157 submodule_name_to_gitdir(&gitdir, the_repository,
2158 sub->name);
2159 connect_work_tree_and_git_dir(path, gitdir.buf, 1);
2160 strbuf_release(&gitdir);
2164 prepare_submodule_repo_env(&cp.env);
2166 cp.git_cmd = 1;
2167 cp.no_stdin = 1;
2168 cp.dir = path;
2170 strvec_pushl(&cp.args, "read-tree", "--recurse-submodules", NULL);
2171 strvec_pushf(&cp.args, "--super-prefix=%s%s/",
2172 (super_prefix ? super_prefix : ""), path);
2174 if (flags & SUBMODULE_MOVE_HEAD_DRY_RUN)
2175 strvec_push(&cp.args, "-n");
2176 else
2177 strvec_push(&cp.args, "-u");
2179 if (flags & SUBMODULE_MOVE_HEAD_FORCE)
2180 strvec_push(&cp.args, "--reset");
2181 else
2182 strvec_push(&cp.args, "-m");
2184 if (!(flags & SUBMODULE_MOVE_HEAD_FORCE))
2185 strvec_push(&cp.args, old_head ? old_head : empty_tree_oid_hex());
2187 strvec_push(&cp.args, new_head ? new_head : empty_tree_oid_hex());
2189 if (run_command(&cp)) {
2190 ret = error(_("Submodule '%s' could not be updated."), path);
2191 goto out;
2194 if (!(flags & SUBMODULE_MOVE_HEAD_DRY_RUN)) {
2195 if (new_head) {
2196 child_process_init(&cp);
2197 /* also set the HEAD accordingly */
2198 cp.git_cmd = 1;
2199 cp.no_stdin = 1;
2200 cp.dir = path;
2202 prepare_submodule_repo_env(&cp.env);
2203 strvec_pushl(&cp.args, "update-ref", "HEAD",
2204 "--no-deref", new_head, NULL);
2206 if (run_command(&cp)) {
2207 ret = -1;
2208 goto out;
2210 } else {
2211 struct strbuf sb = STRBUF_INIT;
2213 strbuf_addf(&sb, "%s/.git", path);
2214 unlink_or_warn(sb.buf);
2215 strbuf_release(&sb);
2217 if (is_empty_dir(path))
2218 rmdir_or_warn(path);
2220 submodule_unset_core_worktree(sub);
2223 out:
2224 return ret;
2227 int validate_submodule_git_dir(char *git_dir, const char *submodule_name)
2229 size_t len = strlen(git_dir), suffix_len = strlen(submodule_name);
2230 char *p;
2231 int ret = 0;
2233 if (len <= suffix_len || (p = git_dir + len - suffix_len)[-1] != '/' ||
2234 strcmp(p, submodule_name))
2235 BUG("submodule name '%s' not a suffix of git dir '%s'",
2236 submodule_name, git_dir);
2239 * We prevent the contents of sibling submodules' git directories to
2240 * clash.
2242 * Example: having a submodule named `hippo` and another one named
2243 * `hippo/hooks` would result in the git directories
2244 * `.git/modules/hippo/` and `.git/modules/hippo/hooks/`, respectively,
2245 * but the latter directory is already designated to contain the hooks
2246 * of the former.
2248 for (; *p; p++) {
2249 if (is_dir_sep(*p)) {
2250 char c = *p;
2252 *p = '\0';
2253 if (is_git_directory(git_dir))
2254 ret = -1;
2255 *p = c;
2257 if (ret < 0)
2258 return error(_("submodule git dir '%s' is "
2259 "inside git dir '%.*s'"),
2260 git_dir,
2261 (int)(p - git_dir), git_dir);
2265 return 0;
2269 * Embeds a single submodules git directory into the superprojects git dir,
2270 * non recursively.
2272 static void relocate_single_git_dir_into_superproject(const char *path,
2273 const char *super_prefix)
2275 char *old_git_dir = NULL, *real_old_git_dir = NULL, *real_new_git_dir = NULL;
2276 struct strbuf new_gitdir = STRBUF_INIT;
2277 const struct submodule *sub;
2279 if (submodule_uses_worktrees(path))
2280 die(_("relocate_gitdir for submodule '%s' with "
2281 "more than one worktree not supported"), path);
2283 old_git_dir = xstrfmt("%s/.git", path);
2284 if (read_gitfile(old_git_dir))
2285 /* If it is an actual gitfile, it doesn't need migration. */
2286 return;
2288 real_old_git_dir = real_pathdup(old_git_dir, 1);
2290 sub = submodule_from_path(the_repository, null_oid(), path);
2291 if (!sub)
2292 die(_("could not lookup name for submodule '%s'"), path);
2294 submodule_name_to_gitdir(&new_gitdir, the_repository, sub->name);
2295 if (validate_submodule_git_dir(new_gitdir.buf, sub->name) < 0)
2296 die(_("refusing to move '%s' into an existing git dir"),
2297 real_old_git_dir);
2298 if (safe_create_leading_directories_const(new_gitdir.buf) < 0)
2299 die(_("could not create directory '%s'"), new_gitdir.buf);
2300 real_new_git_dir = real_pathdup(new_gitdir.buf, 1);
2302 fprintf(stderr, _("Migrating git directory of '%s%s' from\n'%s' to\n'%s'\n"),
2303 super_prefix ? super_prefix : "", path,
2304 real_old_git_dir, real_new_git_dir);
2306 relocate_gitdir(path, real_old_git_dir, real_new_git_dir);
2308 free(old_git_dir);
2309 free(real_old_git_dir);
2310 free(real_new_git_dir);
2311 strbuf_release(&new_gitdir);
2314 static void absorb_git_dir_into_superproject_recurse(const char *path,
2315 const char *super_prefix)
2318 struct child_process cp = CHILD_PROCESS_INIT;
2320 cp.dir = path;
2321 cp.git_cmd = 1;
2322 cp.no_stdin = 1;
2323 strvec_pushl(&cp.args, "submodule--helper",
2324 "absorbgitdirs", NULL);
2325 strvec_pushf(&cp.args, "--super-prefix=%s%s/", super_prefix ?
2326 super_prefix : "", path);
2328 prepare_submodule_repo_env(&cp.env);
2329 if (run_command(&cp))
2330 die(_("could not recurse into submodule '%s'"), path);
2334 * Migrate the git directory of the submodule given by path from
2335 * having its git directory within the working tree to the git dir nested
2336 * in its superprojects git dir under modules/.
2338 void absorb_git_dir_into_superproject(const char *path,
2339 const char *super_prefix)
2341 int err_code;
2342 const char *sub_git_dir;
2343 struct strbuf gitdir = STRBUF_INIT;
2344 strbuf_addf(&gitdir, "%s/.git", path);
2345 sub_git_dir = resolve_gitdir_gently(gitdir.buf, &err_code);
2347 /* Not populated? */
2348 if (!sub_git_dir) {
2349 const struct submodule *sub;
2350 struct strbuf sub_gitdir = STRBUF_INIT;
2352 if (err_code == READ_GITFILE_ERR_STAT_FAILED) {
2353 /* unpopulated as expected */
2354 strbuf_release(&gitdir);
2355 return;
2358 if (err_code != READ_GITFILE_ERR_NOT_A_REPO)
2359 /* We don't know what broke here. */
2360 read_gitfile_error_die(err_code, path, NULL);
2363 * Maybe populated, but no git directory was found?
2364 * This can happen if the superproject is a submodule
2365 * itself and was just absorbed. The absorption of the
2366 * superproject did not rewrite the git file links yet,
2367 * fix it now.
2369 sub = submodule_from_path(the_repository, null_oid(), path);
2370 if (!sub)
2371 die(_("could not lookup name for submodule '%s'"), path);
2372 submodule_name_to_gitdir(&sub_gitdir, the_repository, sub->name);
2373 connect_work_tree_and_git_dir(path, sub_gitdir.buf, 0);
2374 strbuf_release(&sub_gitdir);
2375 } else {
2376 /* Is it already absorbed into the superprojects git dir? */
2377 char *real_sub_git_dir = real_pathdup(sub_git_dir, 1);
2378 char *real_common_git_dir = real_pathdup(get_git_common_dir(), 1);
2380 if (!starts_with(real_sub_git_dir, real_common_git_dir))
2381 relocate_single_git_dir_into_superproject(path, super_prefix);
2383 free(real_sub_git_dir);
2384 free(real_common_git_dir);
2386 strbuf_release(&gitdir);
2388 absorb_git_dir_into_superproject_recurse(path, super_prefix);
2391 int get_superproject_working_tree(struct strbuf *buf)
2393 struct child_process cp = CHILD_PROCESS_INIT;
2394 struct strbuf sb = STRBUF_INIT;
2395 struct strbuf one_up = STRBUF_INIT;
2396 char *cwd = xgetcwd();
2397 int ret = 0;
2398 const char *subpath;
2399 int code;
2400 ssize_t len;
2402 if (!is_inside_work_tree())
2404 * FIXME:
2405 * We might have a superproject, but it is harder
2406 * to determine.
2408 return 0;
2410 if (!strbuf_realpath(&one_up, "../", 0))
2411 return 0;
2413 subpath = relative_path(cwd, one_up.buf, &sb);
2414 strbuf_release(&one_up);
2416 prepare_submodule_repo_env(&cp.env);
2417 strvec_pop(&cp.env);
2419 strvec_pushl(&cp.args, "--literal-pathspecs", "-C", "..",
2420 "ls-files", "-z", "--stage", "--full-name", "--",
2421 subpath, NULL);
2422 strbuf_reset(&sb);
2424 cp.no_stdin = 1;
2425 cp.no_stderr = 1;
2426 cp.out = -1;
2427 cp.git_cmd = 1;
2429 if (start_command(&cp))
2430 die(_("could not start ls-files in .."));
2432 len = strbuf_read(&sb, cp.out, PATH_MAX);
2433 close(cp.out);
2435 if (starts_with(sb.buf, "160000")) {
2436 int super_sub_len;
2437 int cwd_len = strlen(cwd);
2438 char *super_sub, *super_wt;
2441 * There is a superproject having this repo as a submodule.
2442 * The format is <mode> SP <hash> SP <stage> TAB <full name> \0,
2443 * We're only interested in the name after the tab.
2445 super_sub = strchr(sb.buf, '\t') + 1;
2446 super_sub_len = strlen(super_sub);
2448 if (super_sub_len > cwd_len ||
2449 strcmp(&cwd[cwd_len - super_sub_len], super_sub))
2450 BUG("returned path string doesn't match cwd?");
2452 super_wt = xstrdup(cwd);
2453 super_wt[cwd_len - super_sub_len] = '\0';
2455 strbuf_realpath(buf, super_wt, 1);
2456 ret = 1;
2457 free(super_wt);
2459 free(cwd);
2460 strbuf_release(&sb);
2462 code = finish_command(&cp);
2464 if (code == 128)
2465 /* '../' is not a git repository */
2466 return 0;
2467 if (code == 0 && len == 0)
2468 /* There is an unrelated git repository at '../' */
2469 return 0;
2470 if (code)
2471 die(_("ls-tree returned unexpected return code %d"), code);
2473 return ret;
2477 * Put the gitdir for a submodule (given relative to the main
2478 * repository worktree) into `buf`, or return -1 on error.
2480 int submodule_to_gitdir(struct strbuf *buf, const char *submodule)
2482 const struct submodule *sub;
2483 const char *git_dir;
2484 int ret = 0;
2486 strbuf_reset(buf);
2487 strbuf_addstr(buf, submodule);
2488 strbuf_complete(buf, '/');
2489 strbuf_addstr(buf, ".git");
2491 git_dir = read_gitfile(buf->buf);
2492 if (git_dir) {
2493 strbuf_reset(buf);
2494 strbuf_addstr(buf, git_dir);
2496 if (!is_git_directory(buf->buf)) {
2497 sub = submodule_from_path(the_repository, null_oid(),
2498 submodule);
2499 if (!sub) {
2500 ret = -1;
2501 goto cleanup;
2503 strbuf_reset(buf);
2504 submodule_name_to_gitdir(buf, the_repository, sub->name);
2507 cleanup:
2508 return ret;
2511 void submodule_name_to_gitdir(struct strbuf *buf, struct repository *r,
2512 const char *submodule_name)
2515 * NEEDSWORK: The current way of mapping a submodule's name to
2516 * its location in .git/modules/ has problems with some naming
2517 * schemes. For example, if a submodule is named "foo" and
2518 * another is named "foo/bar" (whether present in the same
2519 * superproject commit or not - the problem will arise if both
2520 * superproject commits have been checked out at any point in
2521 * time), or if two submodule names only have different cases in
2522 * a case-insensitive filesystem.
2524 * There are several solutions, including encoding the path in
2525 * some way, introducing a submodule.<name>.gitdir config in
2526 * .git/config (not .gitmodules) that allows overriding what the
2527 * gitdir of a submodule would be (and teach Git, upon noticing
2528 * a clash, to automatically determine a non-clashing name and
2529 * to write such a config), or introducing a
2530 * submodule.<name>.gitdir config in .gitmodules that repo
2531 * administrators can explicitly set. Nothing has been decided,
2532 * so for now, just append the name at the end of the path.
2534 strbuf_repo_git_path(buf, r, "modules/");
2535 strbuf_addstr(buf, submodule_name);