submodule: fix latent check_has_commit() bug
[git/debian.git] / submodule.c
blob93c78a4dc359665e6c2bda2705f05075a6408dfe
2 #include "cache.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 "revision.h"
11 #include "run-command.h"
12 #include "diffcore.h"
13 #include "refs.h"
14 #include "string-list.h"
15 #include "oid-array.h"
16 #include "strvec.h"
17 #include "blob.h"
18 #include "thread-utils.h"
19 #include "quote.h"
20 #include "remote.h"
21 #include "worktree.h"
22 #include "parse-options.h"
23 #include "object-store.h"
24 #include "commit-reach.h"
26 static int config_update_recurse_submodules = RECURSE_SUBMODULES_OFF;
27 static int initialized_fetch_ref_tips;
28 static struct oid_array ref_tips_before_fetch;
29 static struct oid_array ref_tips_after_fetch;
32 * Check if the .gitmodules file is unmerged. Parsing of the .gitmodules file
33 * will be disabled because we can't guess what might be configured in
34 * .gitmodules unless the user resolves the conflict.
36 int is_gitmodules_unmerged(struct index_state *istate)
38 int pos = index_name_pos(istate, GITMODULES_FILE, strlen(GITMODULES_FILE));
39 if (pos < 0) { /* .gitmodules not found or isn't merged */
40 pos = -1 - pos;
41 if (istate->cache_nr > pos) { /* there is a .gitmodules */
42 const struct cache_entry *ce = istate->cache[pos];
43 if (ce_namelen(ce) == strlen(GITMODULES_FILE) &&
44 !strcmp(ce->name, GITMODULES_FILE))
45 return 1;
49 return 0;
53 * Check if the .gitmodules file is safe to write.
55 * Writing to the .gitmodules file requires that the file exists in the
56 * working tree or, if it doesn't, that a brand new .gitmodules file is going
57 * to be created (i.e. it's neither in the index nor in the current branch).
59 * It is not safe to write to .gitmodules if it's not in the working tree but
60 * it is in the index or in the current branch, because writing new values
61 * (and staging them) would blindly overwrite ALL the old content.
63 int is_writing_gitmodules_ok(void)
65 struct object_id oid;
66 return file_exists(GITMODULES_FILE) ||
67 (get_oid(GITMODULES_INDEX, &oid) < 0 && get_oid(GITMODULES_HEAD, &oid) < 0);
71 * Check if the .gitmodules file has unstaged modifications. This must be
72 * checked before allowing modifications to the .gitmodules file with the
73 * intention to stage them later, because when continuing we would stage the
74 * modifications the user didn't stage herself too. That might change in a
75 * future version when we learn to stage the changes we do ourselves without
76 * staging any previous modifications.
78 int is_staging_gitmodules_ok(struct index_state *istate)
80 int pos = index_name_pos(istate, GITMODULES_FILE, strlen(GITMODULES_FILE));
82 if ((pos >= 0) && (pos < istate->cache_nr)) {
83 struct stat st;
84 if (lstat(GITMODULES_FILE, &st) == 0 &&
85 ie_modified(istate, istate->cache[pos], &st, 0) & DATA_CHANGED)
86 return 0;
89 return 1;
92 static int for_each_remote_ref_submodule(const char *submodule,
93 each_ref_fn fn, void *cb_data)
95 return refs_for_each_remote_ref(get_submodule_ref_store(submodule),
96 fn, cb_data);
100 * Try to update the "path" entry in the "submodule.<name>" section of the
101 * .gitmodules file. Return 0 only if a .gitmodules file was found, a section
102 * with the correct path=<oldpath> setting was found and we could update it.
104 int update_path_in_gitmodules(const char *oldpath, const char *newpath)
106 struct strbuf entry = STRBUF_INIT;
107 const struct submodule *submodule;
108 int ret;
110 if (!file_exists(GITMODULES_FILE)) /* Do nothing without .gitmodules */
111 return -1;
113 if (is_gitmodules_unmerged(the_repository->index))
114 die(_("Cannot change unmerged .gitmodules, resolve merge conflicts first"));
116 submodule = submodule_from_path(the_repository, null_oid(), oldpath);
117 if (!submodule || !submodule->name) {
118 warning(_("Could not find section in .gitmodules where path=%s"), oldpath);
119 return -1;
121 strbuf_addstr(&entry, "submodule.");
122 strbuf_addstr(&entry, submodule->name);
123 strbuf_addstr(&entry, ".path");
124 ret = config_set_in_gitmodules_file_gently(entry.buf, newpath);
125 strbuf_release(&entry);
126 return ret;
130 * Try to remove the "submodule.<name>" section from .gitmodules where the given
131 * path is configured. Return 0 only if a .gitmodules file was found, a section
132 * with the correct path=<path> setting was found and we could remove it.
134 int remove_path_from_gitmodules(const char *path)
136 struct strbuf sect = STRBUF_INIT;
137 const struct submodule *submodule;
139 if (!file_exists(GITMODULES_FILE)) /* Do nothing without .gitmodules */
140 return -1;
142 if (is_gitmodules_unmerged(the_repository->index))
143 die(_("Cannot change unmerged .gitmodules, resolve merge conflicts first"));
145 submodule = submodule_from_path(the_repository, null_oid(), path);
146 if (!submodule || !submodule->name) {
147 warning(_("Could not find section in .gitmodules where path=%s"), path);
148 return -1;
150 strbuf_addstr(&sect, "submodule.");
151 strbuf_addstr(&sect, submodule->name);
152 if (git_config_rename_section_in_file(GITMODULES_FILE, sect.buf, NULL) < 0) {
153 /* Maybe the user already did that, don't error out here */
154 warning(_("Could not remove .gitmodules entry for %s"), path);
155 strbuf_release(&sect);
156 return -1;
158 strbuf_release(&sect);
159 return 0;
162 void stage_updated_gitmodules(struct index_state *istate)
164 if (add_file_to_index(istate, GITMODULES_FILE, 0))
165 die(_("staging updated .gitmodules failed"));
168 static struct string_list added_submodule_odb_paths = STRING_LIST_INIT_NODUP;
170 void add_submodule_odb_by_path(const char *path)
172 string_list_insert(&added_submodule_odb_paths, xstrdup(path));
175 int register_all_submodule_odb_as_alternates(void)
177 int i;
178 int ret = added_submodule_odb_paths.nr;
180 for (i = 0; i < added_submodule_odb_paths.nr; i++)
181 add_to_alternates_memory(added_submodule_odb_paths.items[i].string);
182 if (ret) {
183 string_list_clear(&added_submodule_odb_paths, 0);
184 trace2_data_intmax("submodule", the_repository,
185 "register_all_submodule_odb_as_alternates/registered", ret);
186 if (git_env_bool("GIT_TEST_FATAL_REGISTER_SUBMODULE_ODB", 0))
187 BUG("register_all_submodule_odb_as_alternates() called");
189 return ret;
192 void set_diffopt_flags_from_submodule_config(struct diff_options *diffopt,
193 const char *path)
195 const struct submodule *submodule = submodule_from_path(the_repository,
196 null_oid(),
197 path);
198 if (submodule) {
199 const char *ignore;
200 char *key;
202 key = xstrfmt("submodule.%s.ignore", submodule->name);
203 if (repo_config_get_string_tmp(the_repository, key, &ignore))
204 ignore = submodule->ignore;
205 free(key);
207 if (ignore)
208 handle_ignore_submodules_arg(diffopt, ignore);
209 else if (is_gitmodules_unmerged(the_repository->index))
210 diffopt->flags.ignore_submodules = 1;
214 /* Cheap function that only determines if we're interested in submodules at all */
215 int git_default_submodule_config(const char *var, const char *value, void *cb)
217 if (!strcmp(var, "submodule.recurse")) {
218 int v = git_config_bool(var, value) ?
219 RECURSE_SUBMODULES_ON : RECURSE_SUBMODULES_OFF;
220 config_update_recurse_submodules = v;
222 return 0;
225 int option_parse_recurse_submodules_worktree_updater(const struct option *opt,
226 const char *arg, int unset)
228 if (unset) {
229 config_update_recurse_submodules = RECURSE_SUBMODULES_OFF;
230 return 0;
232 if (arg)
233 config_update_recurse_submodules =
234 parse_update_recurse_submodules_arg(opt->long_name,
235 arg);
236 else
237 config_update_recurse_submodules = RECURSE_SUBMODULES_ON;
239 return 0;
243 * Determine if a submodule has been initialized at a given 'path'
246 * NEEDSWORK: Emit a warning if submodule.active exists, but is valueless,
247 * ie, the config looks like: "[submodule] active\n".
248 * Since that is an invalid pathspec, we should inform the user.
250 int is_tree_submodule_active(struct repository *repo,
251 const struct object_id *treeish_name,
252 const char *path)
254 int ret = 0;
255 char *key = NULL;
256 char *value = NULL;
257 const struct string_list *sl;
258 const struct submodule *module;
260 module = submodule_from_path(repo, treeish_name, path);
262 /* early return if there isn't a path->module mapping */
263 if (!module)
264 return 0;
266 /* submodule.<name>.active is set */
267 key = xstrfmt("submodule.%s.active", module->name);
268 if (!repo_config_get_bool(repo, key, &ret)) {
269 free(key);
270 return ret;
272 free(key);
274 /* submodule.active is set */
275 sl = repo_config_get_value_multi(repo, "submodule.active");
276 if (sl) {
277 struct pathspec ps;
278 struct strvec args = STRVEC_INIT;
279 const struct string_list_item *item;
281 for_each_string_list_item(item, sl) {
282 strvec_push(&args, item->string);
285 parse_pathspec(&ps, 0, 0, NULL, args.v);
286 ret = match_pathspec(repo->index, &ps, path, strlen(path), 0, NULL, 1);
288 strvec_clear(&args);
289 clear_pathspec(&ps);
290 return ret;
293 /* fallback to checking if the URL is set */
294 key = xstrfmt("submodule.%s.url", module->name);
295 ret = !repo_config_get_string(repo, key, &value);
297 free(value);
298 free(key);
299 return ret;
302 int is_submodule_active(struct repository *repo, const char *path)
304 return is_tree_submodule_active(repo, null_oid(), path);
307 int is_submodule_populated_gently(const char *path, int *return_error_code)
309 int ret = 0;
310 char *gitdir = xstrfmt("%s/.git", path);
312 if (resolve_gitdir_gently(gitdir, return_error_code))
313 ret = 1;
315 free(gitdir);
316 return ret;
320 * Dies if the provided 'prefix' corresponds to an unpopulated submodule
322 void die_in_unpopulated_submodule(struct index_state *istate,
323 const char *prefix)
325 int i, prefixlen;
327 if (!prefix)
328 return;
330 prefixlen = strlen(prefix);
332 for (i = 0; i < istate->cache_nr; i++) {
333 struct cache_entry *ce = istate->cache[i];
334 int ce_len = ce_namelen(ce);
336 if (!S_ISGITLINK(ce->ce_mode))
337 continue;
338 if (prefixlen <= ce_len)
339 continue;
340 if (strncmp(ce->name, prefix, ce_len))
341 continue;
342 if (prefix[ce_len] != '/')
343 continue;
345 die(_("in unpopulated submodule '%s'"), ce->name);
350 * Dies if any paths in the provided pathspec descends into a submodule
352 void die_path_inside_submodule(struct index_state *istate,
353 const struct pathspec *ps)
355 int i, j;
357 for (i = 0; i < istate->cache_nr; i++) {
358 struct cache_entry *ce = istate->cache[i];
359 int ce_len = ce_namelen(ce);
361 if (!S_ISGITLINK(ce->ce_mode))
362 continue;
364 for (j = 0; j < ps->nr ; j++) {
365 const struct pathspec_item *item = &ps->items[j];
367 if (item->len <= ce_len)
368 continue;
369 if (item->match[ce_len] != '/')
370 continue;
371 if (strncmp(ce->name, item->match, ce_len))
372 continue;
373 if (item->len == ce_len + 1)
374 continue;
376 die(_("Pathspec '%s' is in submodule '%.*s'"),
377 item->original, ce_len, ce->name);
382 enum submodule_update_type parse_submodule_update_type(const char *value)
384 if (!strcmp(value, "none"))
385 return SM_UPDATE_NONE;
386 else if (!strcmp(value, "checkout"))
387 return SM_UPDATE_CHECKOUT;
388 else if (!strcmp(value, "rebase"))
389 return SM_UPDATE_REBASE;
390 else if (!strcmp(value, "merge"))
391 return SM_UPDATE_MERGE;
392 else if (*value == '!')
393 return SM_UPDATE_COMMAND;
394 else
395 return SM_UPDATE_UNSPECIFIED;
398 int parse_submodule_update_strategy(const char *value,
399 struct submodule_update_strategy *dst)
401 enum submodule_update_type type;
403 free((void*)dst->command);
404 dst->command = NULL;
406 type = parse_submodule_update_type(value);
407 if (type == SM_UPDATE_UNSPECIFIED)
408 return -1;
410 dst->type = type;
411 if (type == SM_UPDATE_COMMAND)
412 dst->command = xstrdup(value + 1);
414 return 0;
417 const char *submodule_strategy_to_string(const struct submodule_update_strategy *s)
419 struct strbuf sb = STRBUF_INIT;
420 switch (s->type) {
421 case SM_UPDATE_CHECKOUT:
422 return "checkout";
423 case SM_UPDATE_MERGE:
424 return "merge";
425 case SM_UPDATE_REBASE:
426 return "rebase";
427 case SM_UPDATE_NONE:
428 return "none";
429 case SM_UPDATE_UNSPECIFIED:
430 return NULL;
431 case SM_UPDATE_COMMAND:
432 strbuf_addf(&sb, "!%s", s->command);
433 return strbuf_detach(&sb, NULL);
435 return NULL;
438 void handle_ignore_submodules_arg(struct diff_options *diffopt,
439 const char *arg)
441 diffopt->flags.ignore_submodule_set = 1;
442 diffopt->flags.ignore_submodules = 0;
443 diffopt->flags.ignore_untracked_in_submodules = 0;
444 diffopt->flags.ignore_dirty_submodules = 0;
446 if (!strcmp(arg, "all"))
447 diffopt->flags.ignore_submodules = 1;
448 else if (!strcmp(arg, "untracked"))
449 diffopt->flags.ignore_untracked_in_submodules = 1;
450 else if (!strcmp(arg, "dirty"))
451 diffopt->flags.ignore_dirty_submodules = 1;
452 else if (strcmp(arg, "none"))
453 die(_("bad --ignore-submodules argument: %s"), arg);
455 * Please update _git_status() in git-completion.bash when you
456 * add new options
460 static int prepare_submodule_diff_summary(struct repository *r, struct rev_info *rev,
461 const char *path,
462 struct commit *left, struct commit *right,
463 struct commit_list *merge_bases)
465 struct commit_list *list;
467 repo_init_revisions(r, rev, NULL);
468 setup_revisions(0, NULL, rev, NULL);
469 rev->left_right = 1;
470 rev->first_parent_only = 1;
471 left->object.flags |= SYMMETRIC_LEFT;
472 add_pending_object(rev, &left->object, path);
473 add_pending_object(rev, &right->object, path);
474 for (list = merge_bases; list; list = list->next) {
475 list->item->object.flags |= UNINTERESTING;
476 add_pending_object(rev, &list->item->object,
477 oid_to_hex(&list->item->object.oid));
479 return prepare_revision_walk(rev);
482 static void print_submodule_diff_summary(struct repository *r, struct rev_info *rev, struct diff_options *o)
484 static const char format[] = " %m %s";
485 struct strbuf sb = STRBUF_INIT;
486 struct commit *commit;
488 while ((commit = get_revision(rev))) {
489 struct pretty_print_context ctx = {0};
490 ctx.date_mode = rev->date_mode;
491 ctx.output_encoding = get_log_output_encoding();
492 strbuf_setlen(&sb, 0);
493 repo_format_commit_message(r, commit, format, &sb,
494 &ctx);
495 strbuf_addch(&sb, '\n');
496 if (commit->object.flags & SYMMETRIC_LEFT)
497 diff_emit_submodule_del(o, sb.buf);
498 else
499 diff_emit_submodule_add(o, sb.buf);
501 strbuf_release(&sb);
504 void prepare_submodule_repo_env(struct strvec *out)
506 prepare_other_repo_env(out, DEFAULT_GIT_DIR_ENVIRONMENT);
509 static void prepare_submodule_repo_env_in_gitdir(struct strvec *out)
511 prepare_other_repo_env(out, ".");
515 * Initialize a repository struct for a submodule based on the provided 'path'.
517 * Returns the repository struct on success,
518 * NULL when the submodule is not present.
520 static struct repository *open_submodule(const char *path)
522 struct strbuf sb = STRBUF_INIT;
523 struct repository *out = xmalloc(sizeof(*out));
525 if (submodule_to_gitdir(&sb, path) || repo_init(out, sb.buf, NULL)) {
526 strbuf_release(&sb);
527 free(out);
528 return NULL;
531 /* Mark it as a submodule */
532 out->submodule_prefix = xstrdup(path);
534 strbuf_release(&sb);
535 return out;
539 * Helper function to display the submodule header line prior to the full
540 * summary output.
542 * If it can locate the submodule git directory it will create a repository
543 * handle for the submodule and lookup both the left and right commits and
544 * put them into the left and right pointers.
546 static void show_submodule_header(struct diff_options *o,
547 const char *path,
548 struct object_id *one, struct object_id *two,
549 unsigned dirty_submodule,
550 struct repository *sub,
551 struct commit **left, struct commit **right,
552 struct commit_list **merge_bases)
554 const char *message = NULL;
555 struct strbuf sb = STRBUF_INIT;
556 int fast_forward = 0, fast_backward = 0;
558 if (dirty_submodule & DIRTY_SUBMODULE_UNTRACKED)
559 diff_emit_submodule_untracked(o, path);
561 if (dirty_submodule & DIRTY_SUBMODULE_MODIFIED)
562 diff_emit_submodule_modified(o, path);
564 if (is_null_oid(one))
565 message = "(new submodule)";
566 else if (is_null_oid(two))
567 message = "(submodule deleted)";
569 if (!sub) {
570 if (!message)
571 message = "(commits not present)";
572 goto output_header;
576 * Attempt to lookup the commit references, and determine if this is
577 * a fast forward or fast backwards update.
579 *left = lookup_commit_reference(sub, one);
580 *right = lookup_commit_reference(sub, two);
583 * Warn about missing commits in the submodule project, but only if
584 * they aren't null.
586 if ((!is_null_oid(one) && !*left) ||
587 (!is_null_oid(two) && !*right))
588 message = "(commits not present)";
590 *merge_bases = repo_get_merge_bases(sub, *left, *right);
591 if (*merge_bases) {
592 if ((*merge_bases)->item == *left)
593 fast_forward = 1;
594 else if ((*merge_bases)->item == *right)
595 fast_backward = 1;
598 if (oideq(one, two)) {
599 strbuf_release(&sb);
600 return;
603 output_header:
604 strbuf_addf(&sb, "Submodule %s ", path);
605 strbuf_add_unique_abbrev(&sb, one, DEFAULT_ABBREV);
606 strbuf_addstr(&sb, (fast_backward || fast_forward) ? ".." : "...");
607 strbuf_add_unique_abbrev(&sb, two, DEFAULT_ABBREV);
608 if (message)
609 strbuf_addf(&sb, " %s\n", message);
610 else
611 strbuf_addf(&sb, "%s:\n", fast_backward ? " (rewind)" : "");
612 diff_emit_submodule_header(o, sb.buf);
614 strbuf_release(&sb);
617 void show_submodule_diff_summary(struct diff_options *o, const char *path,
618 struct object_id *one, struct object_id *two,
619 unsigned dirty_submodule)
621 struct rev_info rev;
622 struct commit *left = NULL, *right = NULL;
623 struct commit_list *merge_bases = NULL;
624 struct repository *sub;
626 sub = open_submodule(path);
627 show_submodule_header(o, path, one, two, dirty_submodule,
628 sub, &left, &right, &merge_bases);
631 * If we don't have both a left and a right pointer, there is no
632 * reason to try and display a summary. The header line should contain
633 * all the information the user needs.
635 if (!left || !right || !sub)
636 goto out;
638 /* Treat revision walker failure the same as missing commits */
639 if (prepare_submodule_diff_summary(sub, &rev, path, left, right, merge_bases)) {
640 diff_emit_submodule_error(o, "(revision walker failed)\n");
641 goto out;
644 print_submodule_diff_summary(sub, &rev, o);
646 out:
647 if (merge_bases)
648 free_commit_list(merge_bases);
649 clear_commit_marks(left, ~0);
650 clear_commit_marks(right, ~0);
651 if (sub) {
652 repo_clear(sub);
653 free(sub);
657 void show_submodule_inline_diff(struct diff_options *o, const char *path,
658 struct object_id *one, struct object_id *two,
659 unsigned dirty_submodule)
661 const struct object_id *old_oid = the_hash_algo->empty_tree, *new_oid = the_hash_algo->empty_tree;
662 struct commit *left = NULL, *right = NULL;
663 struct commit_list *merge_bases = NULL;
664 struct child_process cp = CHILD_PROCESS_INIT;
665 struct strbuf sb = STRBUF_INIT;
666 struct repository *sub;
668 sub = open_submodule(path);
669 show_submodule_header(o, path, one, two, dirty_submodule,
670 sub, &left, &right, &merge_bases);
672 /* We need a valid left and right commit to display a difference */
673 if (!(left || is_null_oid(one)) ||
674 !(right || is_null_oid(two)))
675 goto done;
677 if (left)
678 old_oid = one;
679 if (right)
680 new_oid = two;
682 cp.git_cmd = 1;
683 cp.dir = path;
684 cp.out = -1;
685 cp.no_stdin = 1;
687 /* TODO: other options may need to be passed here. */
688 strvec_pushl(&cp.args, "diff", "--submodule=diff", NULL);
689 strvec_pushf(&cp.args, "--color=%s", want_color(o->use_color) ?
690 "always" : "never");
692 if (o->flags.reverse_diff) {
693 strvec_pushf(&cp.args, "--src-prefix=%s%s/",
694 o->b_prefix, path);
695 strvec_pushf(&cp.args, "--dst-prefix=%s%s/",
696 o->a_prefix, path);
697 } else {
698 strvec_pushf(&cp.args, "--src-prefix=%s%s/",
699 o->a_prefix, path);
700 strvec_pushf(&cp.args, "--dst-prefix=%s%s/",
701 o->b_prefix, path);
703 strvec_push(&cp.args, oid_to_hex(old_oid));
705 * If the submodule has modified content, we will diff against the
706 * work tree, under the assumption that the user has asked for the
707 * diff format and wishes to actually see all differences even if they
708 * haven't yet been committed to the submodule yet.
710 if (!(dirty_submodule & DIRTY_SUBMODULE_MODIFIED))
711 strvec_push(&cp.args, oid_to_hex(new_oid));
713 prepare_submodule_repo_env(&cp.env_array);
715 if (!is_directory(path)) {
716 /* fall back to absorbed git dir, if any */
717 if (!sub)
718 goto done;
719 cp.dir = sub->gitdir;
720 strvec_push(&cp.env_array, GIT_DIR_ENVIRONMENT "=.");
721 strvec_push(&cp.env_array, GIT_WORK_TREE_ENVIRONMENT "=.");
724 if (start_command(&cp)) {
725 diff_emit_submodule_error(o, "(diff failed)\n");
726 goto done;
729 while (strbuf_getwholeline_fd(&sb, cp.out, '\n') != EOF)
730 diff_emit_submodule_pipethrough(o, sb.buf, sb.len);
732 if (finish_command(&cp))
733 diff_emit_submodule_error(o, "(diff failed)\n");
735 done:
736 strbuf_release(&sb);
737 if (merge_bases)
738 free_commit_list(merge_bases);
739 if (left)
740 clear_commit_marks(left, ~0);
741 if (right)
742 clear_commit_marks(right, ~0);
743 if (sub) {
744 repo_clear(sub);
745 free(sub);
749 int should_update_submodules(void)
751 return config_update_recurse_submodules == RECURSE_SUBMODULES_ON;
754 const struct submodule *submodule_from_ce(const struct cache_entry *ce)
756 if (!S_ISGITLINK(ce->ce_mode))
757 return NULL;
759 if (!should_update_submodules())
760 return NULL;
762 return submodule_from_path(the_repository, null_oid(), ce->name);
766 struct collect_changed_submodules_cb_data {
767 struct repository *repo;
768 struct string_list *changed;
769 const struct object_id *commit_oid;
773 * this would normally be two functions: default_name_from_path() and
774 * path_from_default_name(). Since the default name is the same as
775 * the submodule path we can get away with just one function which only
776 * checks whether there is a submodule in the working directory at that
777 * location.
779 static const char *default_name_or_path(const char *path_or_name)
781 int error_code;
783 if (!is_submodule_populated_gently(path_or_name, &error_code))
784 return NULL;
786 return path_or_name;
790 * Holds relevant information for a changed submodule. Used as the .util
791 * member of the changed submodule name string_list_item.
793 * (super_oid, path) allows the submodule config to be read from _some_
794 * .gitmodules file. We store this information the first time we find a
795 * superproject commit that points to the submodule, but this is
796 * arbitrary - we can choose any (super_oid, path) that matches the
797 * submodule's name.
799 * NEEDSWORK: Storing an arbitrary commit is undesirable because we can't
800 * guarantee that we're reading the commit that the user would expect. A better
801 * scheme would be to just fetch a submodule by its name. This requires two
802 * steps:
803 * - Create a function that behaves like repo_submodule_init(), but accepts a
804 * submodule name instead of treeish_name and path. This should be easy
805 * because repo_submodule_init() internally uses the submodule's name.
807 * - Replace most instances of 'struct submodule' (which is the .gitmodules
808 * config) with just the submodule name. This is OK because we expect
809 * submodule settings to be stored in .git/config (via "git submodule init"),
810 * not .gitmodules. This also lets us delete get_non_gitmodules_submodule(),
811 * which constructs a bogus 'struct submodule' for the sake of giving a
812 * placeholder name to a gitlink.
814 struct changed_submodule_data {
816 * The first superproject commit in the rev walk that points to
817 * the submodule.
819 const struct object_id *super_oid;
821 * Path to the submodule in the superproject commit referenced
822 * by 'super_oid'.
824 char *path;
825 /* The submodule commits that have changed in the rev walk. */
826 struct oid_array new_commits;
829 static void changed_submodule_data_clear(struct changed_submodule_data *cs_data)
831 oid_array_clear(&cs_data->new_commits);
832 free(cs_data->path);
835 static void collect_changed_submodules_cb(struct diff_queue_struct *q,
836 struct diff_options *options,
837 void *data)
839 struct collect_changed_submodules_cb_data *me = data;
840 struct string_list *changed = me->changed;
841 const struct object_id *commit_oid = me->commit_oid;
842 int i;
844 for (i = 0; i < q->nr; i++) {
845 struct diff_filepair *p = q->queue[i];
846 const struct submodule *submodule;
847 const char *name;
848 struct string_list_item *item;
849 struct changed_submodule_data *cs_data;
851 if (!S_ISGITLINK(p->two->mode))
852 continue;
854 submodule = submodule_from_path(me->repo,
855 commit_oid, p->two->path);
856 if (submodule)
857 name = submodule->name;
858 else {
859 name = default_name_or_path(p->two->path);
860 /* make sure name does not collide with existing one */
861 if (name)
862 submodule = submodule_from_name(me->repo,
863 commit_oid, name);
864 if (submodule) {
865 warning(_("Submodule in commit %s at path: "
866 "'%s' collides with a submodule named "
867 "the same. Skipping it."),
868 oid_to_hex(commit_oid), p->two->path);
869 name = NULL;
873 if (!name)
874 continue;
876 item = string_list_insert(changed, name);
877 if (item->util)
878 cs_data = item->util;
879 else {
880 item->util = xcalloc(1, sizeof(struct changed_submodule_data));
881 cs_data = item->util;
882 cs_data->super_oid = commit_oid;
883 cs_data->path = xstrdup(p->two->path);
885 oid_array_append(&cs_data->new_commits, &p->two->oid);
890 * Collect the paths of submodules in 'changed' which have changed based on
891 * the revisions as specified in 'argv'. Each entry in 'changed' will also
892 * have a corresponding 'struct oid_array' (in the 'util' field) which lists
893 * what the submodule pointers were updated to during the change.
895 static void collect_changed_submodules(struct repository *r,
896 struct string_list *changed,
897 struct strvec *argv)
899 struct rev_info rev;
900 const struct commit *commit;
901 int save_warning;
902 struct setup_revision_opt s_r_opt = {
903 .assume_dashdash = 1,
906 save_warning = warn_on_object_refname_ambiguity;
907 warn_on_object_refname_ambiguity = 0;
908 repo_init_revisions(r, &rev, NULL);
909 setup_revisions(argv->nr, argv->v, &rev, &s_r_opt);
910 warn_on_object_refname_ambiguity = save_warning;
911 if (prepare_revision_walk(&rev))
912 die(_("revision walk setup failed"));
914 while ((commit = get_revision(&rev))) {
915 struct rev_info diff_rev;
916 struct collect_changed_submodules_cb_data data;
917 data.repo = r;
918 data.changed = changed;
919 data.commit_oid = &commit->object.oid;
921 repo_init_revisions(r, &diff_rev, NULL);
922 diff_rev.diffopt.output_format |= DIFF_FORMAT_CALLBACK;
923 diff_rev.diffopt.format_callback = collect_changed_submodules_cb;
924 diff_rev.diffopt.format_callback_data = &data;
925 diff_rev.dense_combined_merges = 1;
926 diff_tree_combined_merge(commit, &diff_rev);
929 reset_revision_walk();
932 static void free_submodules_data(struct string_list *submodules)
934 struct string_list_item *item;
935 for_each_string_list_item(item, submodules)
936 changed_submodule_data_clear(item->util);
938 string_list_clear(submodules, 1);
941 static int has_remote(const char *refname, const struct object_id *oid,
942 int flags, void *cb_data)
944 return 1;
947 static int append_oid_to_argv(const struct object_id *oid, void *data)
949 struct strvec *argv = data;
950 strvec_push(argv, oid_to_hex(oid));
951 return 0;
954 struct has_commit_data {
955 struct repository *repo;
956 int result;
957 const char *path;
958 const struct object_id *super_oid;
961 static int check_has_commit(const struct object_id *oid, void *data)
963 struct has_commit_data *cb = data;
964 struct repository subrepo;
965 enum object_type type;
967 if (repo_submodule_init(&subrepo, cb->repo, cb->path, cb->super_oid)) {
968 cb->result = 0;
969 /* subrepo failed to init, so don't clean it up. */
970 return 0;
973 type = oid_object_info(&subrepo, oid, NULL);
975 switch (type) {
976 case OBJ_COMMIT:
977 goto cleanup;
978 case OBJ_BAD:
980 * Object is missing or invalid. If invalid, an error message
981 * has already been printed.
983 cb->result = 0;
984 goto cleanup;
985 default:
986 die(_("submodule entry '%s' (%s) is a %s, not a commit"),
987 cb->path, oid_to_hex(oid), type_name(type));
989 cleanup:
990 repo_clear(&subrepo);
991 return 0;
994 static int submodule_has_commits(struct repository *r,
995 const char *path,
996 const struct object_id *super_oid,
997 struct oid_array *commits)
999 struct has_commit_data has_commit = {
1000 .repo = r,
1001 .result = 1,
1002 .path = path,
1003 .super_oid = super_oid
1006 oid_array_for_each_unique(commits, check_has_commit, &has_commit);
1008 if (has_commit.result) {
1010 * Even if the submodule is checked out and the commit is
1011 * present, make sure it exists in the submodule's object store
1012 * and that it is reachable from a ref.
1014 struct child_process cp = CHILD_PROCESS_INIT;
1015 struct strbuf out = STRBUF_INIT;
1017 strvec_pushl(&cp.args, "rev-list", "-n", "1", NULL);
1018 oid_array_for_each_unique(commits, append_oid_to_argv, &cp.args);
1019 strvec_pushl(&cp.args, "--not", "--all", NULL);
1021 prepare_submodule_repo_env(&cp.env_array);
1022 cp.git_cmd = 1;
1023 cp.no_stdin = 1;
1024 cp.dir = path;
1026 if (capture_command(&cp, &out, GIT_MAX_HEXSZ + 1) || out.len)
1027 has_commit.result = 0;
1029 strbuf_release(&out);
1032 return has_commit.result;
1035 static int submodule_needs_pushing(struct repository *r,
1036 const char *path,
1037 struct oid_array *commits)
1039 if (!submodule_has_commits(r, path, null_oid(), commits))
1041 * NOTE: We do consider it safe to return "no" here. The
1042 * correct answer would be "We do not know" instead of
1043 * "No push needed", but it is quite hard to change
1044 * the submodule pointer without having the submodule
1045 * around. If a user did however change the submodules
1046 * without having the submodule around, this indicates
1047 * an expert who knows what they are doing or a
1048 * maintainer integrating work from other people. In
1049 * both cases it should be safe to skip this check.
1051 return 0;
1053 if (for_each_remote_ref_submodule(path, has_remote, NULL) > 0) {
1054 struct child_process cp = CHILD_PROCESS_INIT;
1055 struct strbuf buf = STRBUF_INIT;
1056 int needs_pushing = 0;
1058 strvec_push(&cp.args, "rev-list");
1059 oid_array_for_each_unique(commits, append_oid_to_argv, &cp.args);
1060 strvec_pushl(&cp.args, "--not", "--remotes", "-n", "1" , NULL);
1062 prepare_submodule_repo_env(&cp.env_array);
1063 cp.git_cmd = 1;
1064 cp.no_stdin = 1;
1065 cp.out = -1;
1066 cp.dir = path;
1067 if (start_command(&cp))
1068 die(_("Could not run 'git rev-list <commits> --not --remotes -n 1' command in submodule %s"),
1069 path);
1070 if (strbuf_read(&buf, cp.out, the_hash_algo->hexsz + 1))
1071 needs_pushing = 1;
1072 finish_command(&cp);
1073 close(cp.out);
1074 strbuf_release(&buf);
1075 return needs_pushing;
1078 return 0;
1081 int find_unpushed_submodules(struct repository *r,
1082 struct oid_array *commits,
1083 const char *remotes_name,
1084 struct string_list *needs_pushing)
1086 struct string_list submodules = STRING_LIST_INIT_DUP;
1087 struct string_list_item *name;
1088 struct strvec argv = STRVEC_INIT;
1090 /* argv.v[0] will be ignored by setup_revisions */
1091 strvec_push(&argv, "find_unpushed_submodules");
1092 oid_array_for_each_unique(commits, append_oid_to_argv, &argv);
1093 strvec_push(&argv, "--not");
1094 strvec_pushf(&argv, "--remotes=%s", remotes_name);
1096 collect_changed_submodules(r, &submodules, &argv);
1098 for_each_string_list_item(name, &submodules) {
1099 struct changed_submodule_data *cs_data = name->util;
1100 const struct submodule *submodule;
1101 const char *path = NULL;
1103 submodule = submodule_from_name(r, null_oid(), name->string);
1104 if (submodule)
1105 path = submodule->path;
1106 else
1107 path = default_name_or_path(name->string);
1109 if (!path)
1110 continue;
1112 if (submodule_needs_pushing(r, path, &cs_data->new_commits))
1113 string_list_insert(needs_pushing, path);
1116 free_submodules_data(&submodules);
1117 strvec_clear(&argv);
1119 return needs_pushing->nr;
1122 static int push_submodule(const char *path,
1123 const struct remote *remote,
1124 const struct refspec *rs,
1125 const struct string_list *push_options,
1126 int dry_run)
1128 if (for_each_remote_ref_submodule(path, has_remote, NULL) > 0) {
1129 struct child_process cp = CHILD_PROCESS_INIT;
1130 strvec_push(&cp.args, "push");
1131 if (dry_run)
1132 strvec_push(&cp.args, "--dry-run");
1134 if (push_options && push_options->nr) {
1135 const struct string_list_item *item;
1136 for_each_string_list_item(item, push_options)
1137 strvec_pushf(&cp.args, "--push-option=%s",
1138 item->string);
1141 if (remote->origin != REMOTE_UNCONFIGURED) {
1142 int i;
1143 strvec_push(&cp.args, remote->name);
1144 for (i = 0; i < rs->raw_nr; i++)
1145 strvec_push(&cp.args, rs->raw[i]);
1148 prepare_submodule_repo_env(&cp.env_array);
1149 cp.git_cmd = 1;
1150 cp.no_stdin = 1;
1151 cp.dir = path;
1152 if (run_command(&cp))
1153 return 0;
1154 close(cp.out);
1157 return 1;
1161 * Perform a check in the submodule to see if the remote and refspec work.
1162 * Die if the submodule can't be pushed.
1164 static void submodule_push_check(const char *path, const char *head,
1165 const struct remote *remote,
1166 const struct refspec *rs)
1168 struct child_process cp = CHILD_PROCESS_INIT;
1169 int i;
1171 strvec_push(&cp.args, "submodule--helper");
1172 strvec_push(&cp.args, "push-check");
1173 strvec_push(&cp.args, head);
1174 strvec_push(&cp.args, remote->name);
1176 for (i = 0; i < rs->raw_nr; i++)
1177 strvec_push(&cp.args, rs->raw[i]);
1179 prepare_submodule_repo_env(&cp.env_array);
1180 cp.git_cmd = 1;
1181 cp.no_stdin = 1;
1182 cp.no_stdout = 1;
1183 cp.dir = path;
1186 * Simply indicate if 'submodule--helper push-check' failed.
1187 * More detailed error information will be provided by the
1188 * child process.
1190 if (run_command(&cp))
1191 die(_("process for submodule '%s' failed"), path);
1194 int push_unpushed_submodules(struct repository *r,
1195 struct oid_array *commits,
1196 const struct remote *remote,
1197 const struct refspec *rs,
1198 const struct string_list *push_options,
1199 int dry_run)
1201 int i, ret = 1;
1202 struct string_list needs_pushing = STRING_LIST_INIT_DUP;
1204 if (!find_unpushed_submodules(r, commits,
1205 remote->name, &needs_pushing))
1206 return 1;
1209 * Verify that the remote and refspec can be propagated to all
1210 * submodules. This check can be skipped if the remote and refspec
1211 * won't be propagated due to the remote being unconfigured (e.g. a URL
1212 * instead of a remote name).
1214 if (remote->origin != REMOTE_UNCONFIGURED) {
1215 char *head;
1216 struct object_id head_oid;
1218 head = resolve_refdup("HEAD", 0, &head_oid, NULL);
1219 if (!head)
1220 die(_("Failed to resolve HEAD as a valid ref."));
1222 for (i = 0; i < needs_pushing.nr; i++)
1223 submodule_push_check(needs_pushing.items[i].string,
1224 head, remote, rs);
1225 free(head);
1228 /* Actually push the submodules */
1229 for (i = 0; i < needs_pushing.nr; i++) {
1230 const char *path = needs_pushing.items[i].string;
1231 fprintf(stderr, _("Pushing submodule '%s'\n"), path);
1232 if (!push_submodule(path, remote, rs,
1233 push_options, dry_run)) {
1234 fprintf(stderr, _("Unable to push submodule '%s'\n"), path);
1235 ret = 0;
1239 string_list_clear(&needs_pushing, 0);
1241 return ret;
1244 static int append_oid_to_array(const char *ref, const struct object_id *oid,
1245 int flags, void *data)
1247 struct oid_array *array = data;
1248 oid_array_append(array, oid);
1249 return 0;
1252 void check_for_new_submodule_commits(struct object_id *oid)
1254 if (!initialized_fetch_ref_tips) {
1255 for_each_ref(append_oid_to_array, &ref_tips_before_fetch);
1256 initialized_fetch_ref_tips = 1;
1259 oid_array_append(&ref_tips_after_fetch, oid);
1263 * Returns 1 if there is at least one submodule gitdir in
1264 * $GIT_DIR/modules and 0 otherwise. This follows
1265 * submodule_name_to_gitdir(), which looks for submodules in
1266 * $GIT_DIR/modules, not $GIT_COMMON_DIR.
1268 * A submodule can be moved to $GIT_DIR/modules manually by running "git
1269 * submodule absorbgitdirs", or it may be initialized there by "git
1270 * submodule update".
1272 static int repo_has_absorbed_submodules(struct repository *r)
1274 int ret;
1275 struct strbuf buf = STRBUF_INIT;
1277 strbuf_repo_git_path(&buf, r, "modules/");
1278 ret = file_exists(buf.buf) && !is_empty_dir(buf.buf);
1279 strbuf_release(&buf);
1280 return ret;
1283 static void calculate_changed_submodule_paths(struct repository *r,
1284 struct string_list *changed_submodule_names)
1286 struct strvec argv = STRVEC_INIT;
1287 struct string_list_item *name;
1289 /* No need to check if no submodules would be fetched */
1290 if (!submodule_from_path(r, NULL, NULL) &&
1291 !repo_has_absorbed_submodules(r))
1292 return;
1294 strvec_push(&argv, "--"); /* argv[0] program name */
1295 oid_array_for_each_unique(&ref_tips_after_fetch,
1296 append_oid_to_argv, &argv);
1297 strvec_push(&argv, "--not");
1298 oid_array_for_each_unique(&ref_tips_before_fetch,
1299 append_oid_to_argv, &argv);
1302 * Collect all submodules (whether checked out or not) for which new
1303 * commits have been recorded upstream in "changed_submodule_names".
1305 collect_changed_submodules(r, changed_submodule_names, &argv);
1307 for_each_string_list_item(name, changed_submodule_names) {
1308 struct changed_submodule_data *cs_data = name->util;
1309 const struct submodule *submodule;
1310 const char *path = NULL;
1312 submodule = submodule_from_name(r, null_oid(), name->string);
1313 if (submodule)
1314 path = submodule->path;
1315 else
1316 path = default_name_or_path(name->string);
1318 if (!path)
1319 continue;
1321 if (submodule_has_commits(r, path, null_oid(), &cs_data->new_commits)) {
1322 changed_submodule_data_clear(cs_data);
1323 *name->string = '\0';
1327 string_list_remove_empty_items(changed_submodule_names, 1);
1329 strvec_clear(&argv);
1330 oid_array_clear(&ref_tips_before_fetch);
1331 oid_array_clear(&ref_tips_after_fetch);
1332 initialized_fetch_ref_tips = 0;
1335 int submodule_touches_in_range(struct repository *r,
1336 struct object_id *excl_oid,
1337 struct object_id *incl_oid)
1339 struct string_list subs = STRING_LIST_INIT_DUP;
1340 struct strvec args = STRVEC_INIT;
1341 int ret;
1343 /* No need to check if there are no submodules configured */
1344 if (!submodule_from_path(r, NULL, NULL))
1345 return 0;
1347 strvec_push(&args, "--"); /* args[0] program name */
1348 strvec_push(&args, oid_to_hex(incl_oid));
1349 if (!is_null_oid(excl_oid)) {
1350 strvec_push(&args, "--not");
1351 strvec_push(&args, oid_to_hex(excl_oid));
1354 collect_changed_submodules(r, &subs, &args);
1355 ret = subs.nr;
1357 strvec_clear(&args);
1359 free_submodules_data(&subs);
1360 return ret;
1363 struct submodule_parallel_fetch {
1365 * The index of the last index entry processed by
1366 * get_fetch_task_from_index().
1368 int index_count;
1370 * The index of the last string_list entry processed by
1371 * get_fetch_task_from_changed().
1373 int changed_count;
1374 struct strvec args;
1375 struct repository *r;
1376 const char *prefix;
1377 int command_line_option;
1378 int default_option;
1379 int quiet;
1380 int result;
1383 * Names of submodules that have new commits. Generated by
1384 * walking the newly fetched superproject commits.
1386 struct string_list changed_submodule_names;
1388 * Names of submodules that have already been processed. Lets us
1389 * avoid fetching the same submodule more than once.
1391 struct string_list seen_submodule_names;
1393 /* Pending fetches by OIDs */
1394 struct fetch_task **oid_fetch_tasks;
1395 int oid_fetch_tasks_nr, oid_fetch_tasks_alloc;
1397 struct strbuf submodules_with_errors;
1399 #define SPF_INIT { \
1400 .args = STRVEC_INIT, \
1401 .changed_submodule_names = STRING_LIST_INIT_DUP, \
1402 .seen_submodule_names = STRING_LIST_INIT_DUP, \
1403 .submodules_with_errors = STRBUF_INIT, \
1406 static int get_fetch_recurse_config(const struct submodule *submodule,
1407 struct submodule_parallel_fetch *spf)
1409 if (spf->command_line_option != RECURSE_SUBMODULES_DEFAULT)
1410 return spf->command_line_option;
1412 if (submodule) {
1413 char *key;
1414 const char *value;
1416 int fetch_recurse = submodule->fetch_recurse;
1417 key = xstrfmt("submodule.%s.fetchRecurseSubmodules", submodule->name);
1418 if (!repo_config_get_string_tmp(spf->r, key, &value)) {
1419 fetch_recurse = parse_fetch_recurse_submodules_arg(key, value);
1421 free(key);
1423 if (fetch_recurse != RECURSE_SUBMODULES_NONE)
1424 /* local config overrules everything except commandline */
1425 return fetch_recurse;
1428 return spf->default_option;
1432 * Fetch in progress (if callback data) or
1433 * pending (if in oid_fetch_tasks in struct submodule_parallel_fetch)
1435 struct fetch_task {
1436 struct repository *repo;
1437 const struct submodule *sub;
1438 unsigned free_sub : 1; /* Do we need to free the submodule? */
1439 const char *default_argv; /* The default fetch mode. */
1440 struct strvec git_args; /* Args for the child git process. */
1442 struct oid_array *commits; /* Ensure these commits are fetched */
1446 * When a submodule is not defined in .gitmodules, we cannot access it
1447 * via the regular submodule-config. Create a fake submodule, which we can
1448 * work on.
1450 static const struct submodule *get_non_gitmodules_submodule(const char *path)
1452 struct submodule *ret = NULL;
1453 const char *name = default_name_or_path(path);
1455 if (!name)
1456 return NULL;
1458 ret = xmalloc(sizeof(*ret));
1459 memset(ret, 0, sizeof(*ret));
1460 ret->path = name;
1461 ret->name = name;
1463 return (const struct submodule *) ret;
1466 static void fetch_task_release(struct fetch_task *p)
1468 if (p->free_sub)
1469 free((void*)p->sub);
1470 p->free_sub = 0;
1471 p->sub = NULL;
1473 if (p->repo)
1474 repo_clear(p->repo);
1475 FREE_AND_NULL(p->repo);
1477 strvec_clear(&p->git_args);
1480 static struct repository *get_submodule_repo_for(struct repository *r,
1481 const char *path,
1482 const struct object_id *treeish_name)
1484 struct repository *ret = xmalloc(sizeof(*ret));
1486 if (repo_submodule_init(ret, r, path, treeish_name)) {
1487 free(ret);
1488 return NULL;
1491 return ret;
1494 static struct fetch_task *fetch_task_create(struct submodule_parallel_fetch *spf,
1495 const char *path,
1496 const struct object_id *treeish_name)
1498 struct fetch_task *task = xmalloc(sizeof(*task));
1499 memset(task, 0, sizeof(*task));
1501 task->sub = submodule_from_path(spf->r, treeish_name, path);
1503 if (!task->sub) {
1505 * No entry in .gitmodules? Technically not a submodule,
1506 * but historically we supported repositories that happen to be
1507 * in-place where a gitlink is. Keep supporting them.
1509 task->sub = get_non_gitmodules_submodule(path);
1510 if (!task->sub)
1511 goto cleanup;
1513 task->free_sub = 1;
1516 if (string_list_lookup(&spf->seen_submodule_names, task->sub->name))
1517 goto cleanup;
1519 switch (get_fetch_recurse_config(task->sub, spf))
1521 default:
1522 case RECURSE_SUBMODULES_DEFAULT:
1523 case RECURSE_SUBMODULES_ON_DEMAND:
1524 if (!task->sub ||
1525 !string_list_lookup(
1526 &spf->changed_submodule_names,
1527 task->sub->name))
1528 goto cleanup;
1529 task->default_argv = "on-demand";
1530 break;
1531 case RECURSE_SUBMODULES_ON:
1532 task->default_argv = "yes";
1533 break;
1534 case RECURSE_SUBMODULES_OFF:
1535 goto cleanup;
1538 task->repo = get_submodule_repo_for(spf->r, path, treeish_name);
1540 return task;
1542 cleanup:
1543 fetch_task_release(task);
1544 free(task);
1545 return NULL;
1548 static struct fetch_task *
1549 get_fetch_task_from_index(struct submodule_parallel_fetch *spf,
1550 struct strbuf *err)
1552 for (; spf->index_count < spf->r->index->cache_nr; spf->index_count++) {
1553 const struct cache_entry *ce =
1554 spf->r->index->cache[spf->index_count];
1555 struct fetch_task *task;
1557 if (!S_ISGITLINK(ce->ce_mode))
1558 continue;
1560 task = fetch_task_create(spf, ce->name, null_oid());
1561 if (!task)
1562 continue;
1564 if (task->repo) {
1565 if (!spf->quiet)
1566 strbuf_addf(err, _("Fetching submodule %s%s\n"),
1567 spf->prefix, ce->name);
1569 spf->index_count++;
1570 return task;
1571 } else {
1572 struct strbuf empty_submodule_path = STRBUF_INIT;
1574 fetch_task_release(task);
1575 free(task);
1578 * An empty directory is normal,
1579 * the submodule is not initialized
1581 strbuf_addf(&empty_submodule_path, "%s/%s/",
1582 spf->r->worktree,
1583 ce->name);
1584 if (S_ISGITLINK(ce->ce_mode) &&
1585 !is_empty_dir(empty_submodule_path.buf)) {
1586 spf->result = 1;
1587 strbuf_addf(err,
1588 _("Could not access submodule '%s'\n"),
1589 ce->name);
1591 strbuf_release(&empty_submodule_path);
1594 return NULL;
1597 static struct fetch_task *
1598 get_fetch_task_from_changed(struct submodule_parallel_fetch *spf,
1599 struct strbuf *err)
1601 for (; spf->changed_count < spf->changed_submodule_names.nr;
1602 spf->changed_count++) {
1603 struct string_list_item item =
1604 spf->changed_submodule_names.items[spf->changed_count];
1605 struct changed_submodule_data *cs_data = item.util;
1606 struct fetch_task *task;
1608 if (!is_tree_submodule_active(spf->r, cs_data->super_oid,cs_data->path))
1609 continue;
1611 task = fetch_task_create(spf, cs_data->path,
1612 cs_data->super_oid);
1613 if (!task)
1614 continue;
1616 if (!task->repo) {
1617 strbuf_addf(err, _("Could not access submodule '%s' at commit %s\n"),
1618 cs_data->path,
1619 find_unique_abbrev(cs_data->super_oid, DEFAULT_ABBREV));
1621 fetch_task_release(task);
1622 free(task);
1623 continue;
1626 if (!spf->quiet)
1627 strbuf_addf(err,
1628 _("Fetching submodule %s%s at commit %s\n"),
1629 spf->prefix, task->sub->path,
1630 find_unique_abbrev(cs_data->super_oid,
1631 DEFAULT_ABBREV));
1633 spf->changed_count++;
1635 * NEEDSWORK: Submodules set/unset a value for
1636 * core.worktree when they are populated/unpopulated by
1637 * "git checkout" (and similar commands, see
1638 * submodule_move_head() and
1639 * connect_work_tree_and_git_dir()), but if the
1640 * submodule is unpopulated in another way (e.g. "git
1641 * rm", "rm -r"), core.worktree will still be set even
1642 * though the directory doesn't exist, and the child
1643 * process will crash while trying to chdir into the
1644 * nonexistent directory.
1646 * In this case, we know that the submodule has no
1647 * working tree, so we can work around this by
1648 * setting "--work-tree=." (--bare does not work because
1649 * worktree settings take precedence over bare-ness).
1650 * However, this is not necessarily true in other cases,
1651 * so a generalized solution is still necessary.
1653 * Possible solutions:
1654 * - teach "git [add|rm]" to unset core.worktree and
1655 * discourage users from removing submodules without
1656 * using a Git command.
1657 * - teach submodule child processes to ignore stale
1658 * core.worktree values.
1660 strvec_push(&task->git_args, "--work-tree=.");
1661 return task;
1663 return NULL;
1666 static int get_next_submodule(struct child_process *cp, struct strbuf *err,
1667 void *data, void **task_cb)
1669 struct submodule_parallel_fetch *spf = data;
1670 struct fetch_task *task =
1671 get_fetch_task_from_index(spf, err);
1672 if (!task)
1673 task = get_fetch_task_from_changed(spf, err);
1675 if (task) {
1676 struct strbuf submodule_prefix = STRBUF_INIT;
1678 child_process_init(cp);
1679 cp->dir = task->repo->gitdir;
1680 prepare_submodule_repo_env_in_gitdir(&cp->env_array);
1681 cp->git_cmd = 1;
1682 strvec_init(&cp->args);
1683 if (task->git_args.nr)
1684 strvec_pushv(&cp->args, task->git_args.v);
1685 strvec_pushv(&cp->args, spf->args.v);
1686 strvec_push(&cp->args, task->default_argv);
1687 strvec_push(&cp->args, "--submodule-prefix");
1689 strbuf_addf(&submodule_prefix, "%s%s/",
1690 spf->prefix,
1691 task->sub->path);
1692 strvec_push(&cp->args, submodule_prefix.buf);
1693 *task_cb = task;
1695 strbuf_release(&submodule_prefix);
1696 string_list_insert(&spf->seen_submodule_names, task->sub->name);
1697 return 1;
1700 if (spf->oid_fetch_tasks_nr) {
1701 struct fetch_task *task =
1702 spf->oid_fetch_tasks[spf->oid_fetch_tasks_nr - 1];
1703 struct strbuf submodule_prefix = STRBUF_INIT;
1704 spf->oid_fetch_tasks_nr--;
1706 strbuf_addf(&submodule_prefix, "%s%s/",
1707 spf->prefix, task->sub->path);
1709 child_process_init(cp);
1710 prepare_submodule_repo_env_in_gitdir(&cp->env_array);
1711 cp->git_cmd = 1;
1712 cp->dir = task->repo->gitdir;
1714 strvec_init(&cp->args);
1715 strvec_pushv(&cp->args, spf->args.v);
1716 strvec_push(&cp->args, "on-demand");
1717 strvec_push(&cp->args, "--submodule-prefix");
1718 strvec_push(&cp->args, submodule_prefix.buf);
1720 /* NEEDSWORK: have get_default_remote from submodule--helper */
1721 strvec_push(&cp->args, "origin");
1722 oid_array_for_each_unique(task->commits,
1723 append_oid_to_argv, &cp->args);
1725 *task_cb = task;
1726 strbuf_release(&submodule_prefix);
1727 return 1;
1730 return 0;
1733 static int fetch_start_failure(struct strbuf *err,
1734 void *cb, void *task_cb)
1736 struct submodule_parallel_fetch *spf = cb;
1737 struct fetch_task *task = task_cb;
1739 spf->result = 1;
1741 fetch_task_release(task);
1742 return 0;
1745 static int commit_missing_in_sub(const struct object_id *oid, void *data)
1747 struct repository *subrepo = data;
1749 enum object_type type = oid_object_info(subrepo, oid, NULL);
1751 return type != OBJ_COMMIT;
1754 static int fetch_finish(int retvalue, struct strbuf *err,
1755 void *cb, void *task_cb)
1757 struct submodule_parallel_fetch *spf = cb;
1758 struct fetch_task *task = task_cb;
1760 struct string_list_item *it;
1761 struct changed_submodule_data *cs_data;
1763 if (!task || !task->sub)
1764 BUG("callback cookie bogus");
1766 if (retvalue) {
1768 * NEEDSWORK: This indicates that the overall fetch
1769 * failed, even though there may be a subsequent fetch
1770 * by commit hash that might work. It may be a good
1771 * idea to not indicate failure in this case, and only
1772 * indicate failure if the subsequent fetch fails.
1774 spf->result = 1;
1776 strbuf_addf(&spf->submodules_with_errors, "\t%s\n",
1777 task->sub->name);
1780 /* Is this the second time we process this submodule? */
1781 if (task->commits)
1782 goto out;
1784 it = string_list_lookup(&spf->changed_submodule_names, task->sub->name);
1785 if (!it)
1786 /* Could be an unchanged submodule, not contained in the list */
1787 goto out;
1789 cs_data = it->util;
1790 oid_array_filter(&cs_data->new_commits,
1791 commit_missing_in_sub,
1792 task->repo);
1794 /* Are there commits we want, but do not exist? */
1795 if (cs_data->new_commits.nr) {
1796 task->commits = &cs_data->new_commits;
1797 ALLOC_GROW(spf->oid_fetch_tasks,
1798 spf->oid_fetch_tasks_nr + 1,
1799 spf->oid_fetch_tasks_alloc);
1800 spf->oid_fetch_tasks[spf->oid_fetch_tasks_nr] = task;
1801 spf->oid_fetch_tasks_nr++;
1802 return 0;
1805 out:
1806 fetch_task_release(task);
1808 return 0;
1811 int fetch_submodules(struct repository *r,
1812 const struct strvec *options,
1813 const char *prefix, int command_line_option,
1814 int default_option,
1815 int quiet, int max_parallel_jobs)
1817 int i;
1818 struct submodule_parallel_fetch spf = SPF_INIT;
1820 spf.r = r;
1821 spf.command_line_option = command_line_option;
1822 spf.default_option = default_option;
1823 spf.quiet = quiet;
1824 spf.prefix = prefix;
1826 if (!r->worktree)
1827 goto out;
1829 if (repo_read_index(r) < 0)
1830 die(_("index file corrupt"));
1832 strvec_push(&spf.args, "fetch");
1833 for (i = 0; i < options->nr; i++)
1834 strvec_push(&spf.args, options->v[i]);
1835 strvec_push(&spf.args, "--recurse-submodules-default");
1836 /* default value, "--submodule-prefix" and its value are added later */
1838 calculate_changed_submodule_paths(r, &spf.changed_submodule_names);
1839 string_list_sort(&spf.changed_submodule_names);
1840 run_processes_parallel_tr2(max_parallel_jobs,
1841 get_next_submodule,
1842 fetch_start_failure,
1843 fetch_finish,
1844 &spf,
1845 "submodule", "parallel/fetch");
1847 if (spf.submodules_with_errors.len > 0)
1848 fprintf(stderr, _("Errors during submodule fetch:\n%s"),
1849 spf.submodules_with_errors.buf);
1852 strvec_clear(&spf.args);
1853 out:
1854 free_submodules_data(&spf.changed_submodule_names);
1855 return spf.result;
1858 unsigned is_submodule_modified(const char *path, int ignore_untracked)
1860 struct child_process cp = CHILD_PROCESS_INIT;
1861 struct strbuf buf = STRBUF_INIT;
1862 FILE *fp;
1863 unsigned dirty_submodule = 0;
1864 const char *git_dir;
1865 int ignore_cp_exit_code = 0;
1867 strbuf_addf(&buf, "%s/.git", path);
1868 git_dir = read_gitfile(buf.buf);
1869 if (!git_dir)
1870 git_dir = buf.buf;
1871 if (!is_git_directory(git_dir)) {
1872 if (is_directory(git_dir))
1873 die(_("'%s' not recognized as a git repository"), git_dir);
1874 strbuf_release(&buf);
1875 /* The submodule is not checked out, so it is not modified */
1876 return 0;
1878 strbuf_reset(&buf);
1880 strvec_pushl(&cp.args, "status", "--porcelain=2", NULL);
1881 if (ignore_untracked)
1882 strvec_push(&cp.args, "-uno");
1884 prepare_submodule_repo_env(&cp.env_array);
1885 cp.git_cmd = 1;
1886 cp.no_stdin = 1;
1887 cp.out = -1;
1888 cp.dir = path;
1889 if (start_command(&cp))
1890 die(_("Could not run 'git status --porcelain=2' in submodule %s"), path);
1892 fp = xfdopen(cp.out, "r");
1893 while (strbuf_getwholeline(&buf, fp, '\n') != EOF) {
1894 /* regular untracked files */
1895 if (buf.buf[0] == '?')
1896 dirty_submodule |= DIRTY_SUBMODULE_UNTRACKED;
1898 if (buf.buf[0] == 'u' ||
1899 buf.buf[0] == '1' ||
1900 buf.buf[0] == '2') {
1901 /* T = line type, XY = status, SSSS = submodule state */
1902 if (buf.len < strlen("T XY SSSS"))
1903 BUG("invalid status --porcelain=2 line %s",
1904 buf.buf);
1906 if (buf.buf[5] == 'S' && buf.buf[8] == 'U')
1907 /* nested untracked file */
1908 dirty_submodule |= DIRTY_SUBMODULE_UNTRACKED;
1910 if (buf.buf[0] == 'u' ||
1911 buf.buf[0] == '2' ||
1912 memcmp(buf.buf + 5, "S..U", 4))
1913 /* other change */
1914 dirty_submodule |= DIRTY_SUBMODULE_MODIFIED;
1917 if ((dirty_submodule & DIRTY_SUBMODULE_MODIFIED) &&
1918 ((dirty_submodule & DIRTY_SUBMODULE_UNTRACKED) ||
1919 ignore_untracked)) {
1921 * We're not interested in any further information from
1922 * the child any more, neither output nor its exit code.
1924 ignore_cp_exit_code = 1;
1925 break;
1928 fclose(fp);
1930 if (finish_command(&cp) && !ignore_cp_exit_code)
1931 die(_("'git status --porcelain=2' failed in submodule %s"), path);
1933 strbuf_release(&buf);
1934 return dirty_submodule;
1937 int submodule_uses_gitfile(const char *path)
1939 struct child_process cp = CHILD_PROCESS_INIT;
1940 struct strbuf buf = STRBUF_INIT;
1941 const char *git_dir;
1943 strbuf_addf(&buf, "%s/.git", path);
1944 git_dir = read_gitfile(buf.buf);
1945 if (!git_dir) {
1946 strbuf_release(&buf);
1947 return 0;
1949 strbuf_release(&buf);
1951 /* Now test that all nested submodules use a gitfile too */
1952 strvec_pushl(&cp.args,
1953 "submodule", "foreach", "--quiet", "--recursive",
1954 "test -f .git", NULL);
1956 prepare_submodule_repo_env(&cp.env_array);
1957 cp.git_cmd = 1;
1958 cp.no_stdin = 1;
1959 cp.no_stderr = 1;
1960 cp.no_stdout = 1;
1961 cp.dir = path;
1962 if (run_command(&cp))
1963 return 0;
1965 return 1;
1969 * Check if it is a bad idea to remove a submodule, i.e. if we'd lose data
1970 * when doing so.
1972 * Return 1 if we'd lose data, return 0 if the removal is fine,
1973 * and negative values for errors.
1975 int bad_to_remove_submodule(const char *path, unsigned flags)
1977 ssize_t len;
1978 struct child_process cp = CHILD_PROCESS_INIT;
1979 struct strbuf buf = STRBUF_INIT;
1980 int ret = 0;
1982 if (!file_exists(path) || is_empty_dir(path))
1983 return 0;
1985 if (!submodule_uses_gitfile(path))
1986 return 1;
1988 strvec_pushl(&cp.args, "status", "--porcelain",
1989 "--ignore-submodules=none", NULL);
1991 if (flags & SUBMODULE_REMOVAL_IGNORE_UNTRACKED)
1992 strvec_push(&cp.args, "-uno");
1993 else
1994 strvec_push(&cp.args, "-uall");
1996 if (!(flags & SUBMODULE_REMOVAL_IGNORE_IGNORED_UNTRACKED))
1997 strvec_push(&cp.args, "--ignored");
1999 prepare_submodule_repo_env(&cp.env_array);
2000 cp.git_cmd = 1;
2001 cp.no_stdin = 1;
2002 cp.out = -1;
2003 cp.dir = path;
2004 if (start_command(&cp)) {
2005 if (flags & SUBMODULE_REMOVAL_DIE_ON_ERROR)
2006 die(_("could not start 'git status' in submodule '%s'"),
2007 path);
2008 ret = -1;
2009 goto out;
2012 len = strbuf_read(&buf, cp.out, 1024);
2013 if (len > 2)
2014 ret = 1;
2015 close(cp.out);
2017 if (finish_command(&cp)) {
2018 if (flags & SUBMODULE_REMOVAL_DIE_ON_ERROR)
2019 die(_("could not run 'git status' in submodule '%s'"),
2020 path);
2021 ret = -1;
2023 out:
2024 strbuf_release(&buf);
2025 return ret;
2028 void submodule_unset_core_worktree(const struct submodule *sub)
2030 struct strbuf config_path = STRBUF_INIT;
2032 submodule_name_to_gitdir(&config_path, the_repository, sub->name);
2033 strbuf_addstr(&config_path, "/config");
2035 if (git_config_set_in_file_gently(config_path.buf, "core.worktree", NULL))
2036 warning(_("Could not unset core.worktree setting in submodule '%s'"),
2037 sub->path);
2039 strbuf_release(&config_path);
2042 static const char *get_super_prefix_or_empty(void)
2044 const char *s = get_super_prefix();
2045 if (!s)
2046 s = "";
2047 return s;
2050 static int submodule_has_dirty_index(const struct submodule *sub)
2052 struct child_process cp = CHILD_PROCESS_INIT;
2054 prepare_submodule_repo_env(&cp.env_array);
2056 cp.git_cmd = 1;
2057 strvec_pushl(&cp.args, "diff-index", "--quiet",
2058 "--cached", "HEAD", NULL);
2059 cp.no_stdin = 1;
2060 cp.no_stdout = 1;
2061 cp.dir = sub->path;
2062 if (start_command(&cp))
2063 die(_("could not recurse into submodule '%s'"), sub->path);
2065 return finish_command(&cp);
2068 static void submodule_reset_index(const char *path)
2070 struct child_process cp = CHILD_PROCESS_INIT;
2071 prepare_submodule_repo_env(&cp.env_array);
2073 cp.git_cmd = 1;
2074 cp.no_stdin = 1;
2075 cp.dir = path;
2077 strvec_pushf(&cp.args, "--super-prefix=%s%s/",
2078 get_super_prefix_or_empty(), path);
2079 /* TODO: determine if this might overwright untracked files */
2080 strvec_pushl(&cp.args, "read-tree", "-u", "--reset", NULL);
2082 strvec_push(&cp.args, empty_tree_oid_hex());
2084 if (run_command(&cp))
2085 die(_("could not reset submodule index"));
2089 * Moves a submodule at a given path from a given head to another new head.
2090 * For edge cases (a submodule coming into existence or removing a submodule)
2091 * pass NULL for old or new respectively.
2093 int submodule_move_head(const char *path,
2094 const char *old_head,
2095 const char *new_head,
2096 unsigned flags)
2098 int ret = 0;
2099 struct child_process cp = CHILD_PROCESS_INIT;
2100 const struct submodule *sub;
2101 int *error_code_ptr, error_code;
2103 if (!is_submodule_active(the_repository, path))
2104 return 0;
2106 if (flags & SUBMODULE_MOVE_HEAD_FORCE)
2108 * Pass non NULL pointer to is_submodule_populated_gently
2109 * to prevent die()-ing. We'll use connect_work_tree_and_git_dir
2110 * to fixup the submodule in the force case later.
2112 error_code_ptr = &error_code;
2113 else
2114 error_code_ptr = NULL;
2116 if (old_head && !is_submodule_populated_gently(path, error_code_ptr))
2117 return 0;
2119 sub = submodule_from_path(the_repository, null_oid(), path);
2121 if (!sub)
2122 BUG("could not get submodule information for '%s'", path);
2124 if (old_head && !(flags & SUBMODULE_MOVE_HEAD_FORCE)) {
2125 /* Check if the submodule has a dirty index. */
2126 if (submodule_has_dirty_index(sub))
2127 return error(_("submodule '%s' has dirty index"), path);
2130 if (!(flags & SUBMODULE_MOVE_HEAD_DRY_RUN)) {
2131 if (old_head) {
2132 if (!submodule_uses_gitfile(path))
2133 absorb_git_dir_into_superproject(path,
2134 ABSORB_GITDIR_RECURSE_SUBMODULES);
2135 } else {
2136 struct strbuf gitdir = STRBUF_INIT;
2137 submodule_name_to_gitdir(&gitdir, the_repository,
2138 sub->name);
2139 connect_work_tree_and_git_dir(path, gitdir.buf, 0);
2140 strbuf_release(&gitdir);
2142 /* make sure the index is clean as well */
2143 submodule_reset_index(path);
2146 if (old_head && (flags & SUBMODULE_MOVE_HEAD_FORCE)) {
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, 1);
2151 strbuf_release(&gitdir);
2155 prepare_submodule_repo_env(&cp.env_array);
2157 cp.git_cmd = 1;
2158 cp.no_stdin = 1;
2159 cp.dir = path;
2161 strvec_pushf(&cp.args, "--super-prefix=%s%s/",
2162 get_super_prefix_or_empty(), path);
2163 strvec_pushl(&cp.args, "read-tree", "--recurse-submodules", NULL);
2165 if (flags & SUBMODULE_MOVE_HEAD_DRY_RUN)
2166 strvec_push(&cp.args, "-n");
2167 else
2168 strvec_push(&cp.args, "-u");
2170 if (flags & SUBMODULE_MOVE_HEAD_FORCE)
2171 strvec_push(&cp.args, "--reset");
2172 else
2173 strvec_push(&cp.args, "-m");
2175 if (!(flags & SUBMODULE_MOVE_HEAD_FORCE))
2176 strvec_push(&cp.args, old_head ? old_head : empty_tree_oid_hex());
2178 strvec_push(&cp.args, new_head ? new_head : empty_tree_oid_hex());
2180 if (run_command(&cp)) {
2181 ret = error(_("Submodule '%s' could not be updated."), path);
2182 goto out;
2185 if (!(flags & SUBMODULE_MOVE_HEAD_DRY_RUN)) {
2186 if (new_head) {
2187 child_process_init(&cp);
2188 /* also set the HEAD accordingly */
2189 cp.git_cmd = 1;
2190 cp.no_stdin = 1;
2191 cp.dir = path;
2193 prepare_submodule_repo_env(&cp.env_array);
2194 strvec_pushl(&cp.args, "update-ref", "HEAD",
2195 "--no-deref", new_head, NULL);
2197 if (run_command(&cp)) {
2198 ret = -1;
2199 goto out;
2201 } else {
2202 struct strbuf sb = STRBUF_INIT;
2204 strbuf_addf(&sb, "%s/.git", path);
2205 unlink_or_warn(sb.buf);
2206 strbuf_release(&sb);
2208 if (is_empty_dir(path))
2209 rmdir_or_warn(path);
2211 submodule_unset_core_worktree(sub);
2214 out:
2215 return ret;
2218 int validate_submodule_git_dir(char *git_dir, const char *submodule_name)
2220 size_t len = strlen(git_dir), suffix_len = strlen(submodule_name);
2221 char *p;
2222 int ret = 0;
2224 if (len <= suffix_len || (p = git_dir + len - suffix_len)[-1] != '/' ||
2225 strcmp(p, submodule_name))
2226 BUG("submodule name '%s' not a suffix of git dir '%s'",
2227 submodule_name, git_dir);
2230 * We prevent the contents of sibling submodules' git directories to
2231 * clash.
2233 * Example: having a submodule named `hippo` and another one named
2234 * `hippo/hooks` would result in the git directories
2235 * `.git/modules/hippo/` and `.git/modules/hippo/hooks/`, respectively,
2236 * but the latter directory is already designated to contain the hooks
2237 * of the former.
2239 for (; *p; p++) {
2240 if (is_dir_sep(*p)) {
2241 char c = *p;
2243 *p = '\0';
2244 if (is_git_directory(git_dir))
2245 ret = -1;
2246 *p = c;
2248 if (ret < 0)
2249 return error(_("submodule git dir '%s' is "
2250 "inside git dir '%.*s'"),
2251 git_dir,
2252 (int)(p - git_dir), git_dir);
2256 return 0;
2260 * Embeds a single submodules git directory into the superprojects git dir,
2261 * non recursively.
2263 static void relocate_single_git_dir_into_superproject(const char *path)
2265 char *old_git_dir = NULL, *real_old_git_dir = NULL, *real_new_git_dir = NULL;
2266 struct strbuf new_gitdir = STRBUF_INIT;
2267 const struct submodule *sub;
2269 if (submodule_uses_worktrees(path))
2270 die(_("relocate_gitdir for submodule '%s' with "
2271 "more than one worktree not supported"), path);
2273 old_git_dir = xstrfmt("%s/.git", path);
2274 if (read_gitfile(old_git_dir))
2275 /* If it is an actual gitfile, it doesn't need migration. */
2276 return;
2278 real_old_git_dir = real_pathdup(old_git_dir, 1);
2280 sub = submodule_from_path(the_repository, null_oid(), path);
2281 if (!sub)
2282 die(_("could not lookup name for submodule '%s'"), path);
2284 submodule_name_to_gitdir(&new_gitdir, the_repository, sub->name);
2285 if (validate_submodule_git_dir(new_gitdir.buf, sub->name) < 0)
2286 die(_("refusing to move '%s' into an existing git dir"),
2287 real_old_git_dir);
2288 if (safe_create_leading_directories_const(new_gitdir.buf) < 0)
2289 die(_("could not create directory '%s'"), new_gitdir.buf);
2290 real_new_git_dir = real_pathdup(new_gitdir.buf, 1);
2292 fprintf(stderr, _("Migrating git directory of '%s%s' from\n'%s' to\n'%s'\n"),
2293 get_super_prefix_or_empty(), path,
2294 real_old_git_dir, real_new_git_dir);
2296 relocate_gitdir(path, real_old_git_dir, real_new_git_dir);
2298 free(old_git_dir);
2299 free(real_old_git_dir);
2300 free(real_new_git_dir);
2301 strbuf_release(&new_gitdir);
2305 * Migrate the git directory of the submodule given by path from
2306 * having its git directory within the working tree to the git dir nested
2307 * in its superprojects git dir under modules/.
2309 void absorb_git_dir_into_superproject(const char *path,
2310 unsigned flags)
2312 int err_code;
2313 const char *sub_git_dir;
2314 struct strbuf gitdir = STRBUF_INIT;
2315 strbuf_addf(&gitdir, "%s/.git", path);
2316 sub_git_dir = resolve_gitdir_gently(gitdir.buf, &err_code);
2318 /* Not populated? */
2319 if (!sub_git_dir) {
2320 const struct submodule *sub;
2321 struct strbuf sub_gitdir = STRBUF_INIT;
2323 if (err_code == READ_GITFILE_ERR_STAT_FAILED) {
2324 /* unpopulated as expected */
2325 strbuf_release(&gitdir);
2326 return;
2329 if (err_code != READ_GITFILE_ERR_NOT_A_REPO)
2330 /* We don't know what broke here. */
2331 read_gitfile_error_die(err_code, path, NULL);
2334 * Maybe populated, but no git directory was found?
2335 * This can happen if the superproject is a submodule
2336 * itself and was just absorbed. The absorption of the
2337 * superproject did not rewrite the git file links yet,
2338 * fix it now.
2340 sub = submodule_from_path(the_repository, null_oid(), path);
2341 if (!sub)
2342 die(_("could not lookup name for submodule '%s'"), path);
2343 submodule_name_to_gitdir(&sub_gitdir, the_repository, sub->name);
2344 connect_work_tree_and_git_dir(path, sub_gitdir.buf, 0);
2345 strbuf_release(&sub_gitdir);
2346 } else {
2347 /* Is it already absorbed into the superprojects git dir? */
2348 char *real_sub_git_dir = real_pathdup(sub_git_dir, 1);
2349 char *real_common_git_dir = real_pathdup(get_git_common_dir(), 1);
2351 if (!starts_with(real_sub_git_dir, real_common_git_dir))
2352 relocate_single_git_dir_into_superproject(path);
2354 free(real_sub_git_dir);
2355 free(real_common_git_dir);
2357 strbuf_release(&gitdir);
2359 if (flags & ABSORB_GITDIR_RECURSE_SUBMODULES) {
2360 struct child_process cp = CHILD_PROCESS_INIT;
2361 struct strbuf sb = STRBUF_INIT;
2363 if (flags & ~ABSORB_GITDIR_RECURSE_SUBMODULES)
2364 BUG("we don't know how to pass the flags down?");
2366 strbuf_addstr(&sb, get_super_prefix_or_empty());
2367 strbuf_addstr(&sb, path);
2368 strbuf_addch(&sb, '/');
2370 cp.dir = path;
2371 cp.git_cmd = 1;
2372 cp.no_stdin = 1;
2373 strvec_pushl(&cp.args, "--super-prefix", sb.buf,
2374 "submodule--helper",
2375 "absorb-git-dirs", NULL);
2376 prepare_submodule_repo_env(&cp.env_array);
2377 if (run_command(&cp))
2378 die(_("could not recurse into submodule '%s'"), path);
2380 strbuf_release(&sb);
2384 int get_superproject_working_tree(struct strbuf *buf)
2386 struct child_process cp = CHILD_PROCESS_INIT;
2387 struct strbuf sb = STRBUF_INIT;
2388 struct strbuf one_up = STRBUF_INIT;
2389 const char *cwd = xgetcwd();
2390 int ret = 0;
2391 const char *subpath;
2392 int code;
2393 ssize_t len;
2395 if (!is_inside_work_tree())
2397 * FIXME:
2398 * We might have a superproject, but it is harder
2399 * to determine.
2401 return 0;
2403 if (!strbuf_realpath(&one_up, "../", 0))
2404 return 0;
2406 subpath = relative_path(cwd, one_up.buf, &sb);
2407 strbuf_release(&one_up);
2409 prepare_submodule_repo_env(&cp.env_array);
2410 strvec_pop(&cp.env_array);
2412 strvec_pushl(&cp.args, "--literal-pathspecs", "-C", "..",
2413 "ls-files", "-z", "--stage", "--full-name", "--",
2414 subpath, NULL);
2415 strbuf_reset(&sb);
2417 cp.no_stdin = 1;
2418 cp.no_stderr = 1;
2419 cp.out = -1;
2420 cp.git_cmd = 1;
2422 if (start_command(&cp))
2423 die(_("could not start ls-files in .."));
2425 len = strbuf_read(&sb, cp.out, PATH_MAX);
2426 close(cp.out);
2428 if (starts_with(sb.buf, "160000")) {
2429 int super_sub_len;
2430 int cwd_len = strlen(cwd);
2431 char *super_sub, *super_wt;
2434 * There is a superproject having this repo as a submodule.
2435 * The format is <mode> SP <hash> SP <stage> TAB <full name> \0,
2436 * We're only interested in the name after the tab.
2438 super_sub = strchr(sb.buf, '\t') + 1;
2439 super_sub_len = strlen(super_sub);
2441 if (super_sub_len > cwd_len ||
2442 strcmp(&cwd[cwd_len - super_sub_len], super_sub))
2443 BUG("returned path string doesn't match cwd?");
2445 super_wt = xstrdup(cwd);
2446 super_wt[cwd_len - super_sub_len] = '\0';
2448 strbuf_realpath(buf, super_wt, 1);
2449 ret = 1;
2450 free(super_wt);
2452 strbuf_release(&sb);
2454 code = finish_command(&cp);
2456 if (code == 128)
2457 /* '../' is not a git repository */
2458 return 0;
2459 if (code == 0 && len == 0)
2460 /* There is an unrelated git repository at '../' */
2461 return 0;
2462 if (code)
2463 die(_("ls-tree returned unexpected return code %d"), code);
2465 return ret;
2469 * Put the gitdir for a submodule (given relative to the main
2470 * repository worktree) into `buf`, or return -1 on error.
2472 int submodule_to_gitdir(struct strbuf *buf, const char *submodule)
2474 const struct submodule *sub;
2475 const char *git_dir;
2476 int ret = 0;
2478 strbuf_reset(buf);
2479 strbuf_addstr(buf, submodule);
2480 strbuf_complete(buf, '/');
2481 strbuf_addstr(buf, ".git");
2483 git_dir = read_gitfile(buf->buf);
2484 if (git_dir) {
2485 strbuf_reset(buf);
2486 strbuf_addstr(buf, git_dir);
2488 if (!is_git_directory(buf->buf)) {
2489 sub = submodule_from_path(the_repository, null_oid(),
2490 submodule);
2491 if (!sub) {
2492 ret = -1;
2493 goto cleanup;
2495 strbuf_reset(buf);
2496 submodule_name_to_gitdir(buf, the_repository, sub->name);
2499 cleanup:
2500 return ret;
2503 void submodule_name_to_gitdir(struct strbuf *buf, struct repository *r,
2504 const char *submodule_name)
2507 * NEEDSWORK: The current way of mapping a submodule's name to
2508 * its location in .git/modules/ has problems with some naming
2509 * schemes. For example, if a submodule is named "foo" and
2510 * another is named "foo/bar" (whether present in the same
2511 * superproject commit or not - the problem will arise if both
2512 * superproject commits have been checked out at any point in
2513 * time), or if two submodule names only have different cases in
2514 * a case-insensitive filesystem.
2516 * There are several solutions, including encoding the path in
2517 * some way, introducing a submodule.<name>.gitdir config in
2518 * .git/config (not .gitmodules) that allows overriding what the
2519 * gitdir of a submodule would be (and teach Git, upon noticing
2520 * a clash, to automatically determine a non-clashing name and
2521 * to write such a config), or introducing a
2522 * submodule.<name>.gitdir config in .gitmodules that repo
2523 * administrators can explicitly set. Nothing has been decided,
2524 * so for now, just append the name at the end of the path.
2526 strbuf_repo_git_path(buf, r, "modules/");
2527 strbuf_addstr(buf, submodule_name);