is_path_owned_by_current_uid(): mark "report" parameter as unused
[git.git] / submodule.c
blob597a347f859be7632d2f3f5d176635014d75160a
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"
25 #include "shallow.h"
27 static int config_update_recurse_submodules = RECURSE_SUBMODULES_OFF;
28 static int initialized_fetch_ref_tips;
29 static struct oid_array ref_tips_before_fetch;
30 static struct oid_array ref_tips_after_fetch;
33 * Check if the .gitmodules file is unmerged. Parsing of the .gitmodules file
34 * will be disabled because we can't guess what might be configured in
35 * .gitmodules unless the user resolves the conflict.
37 int is_gitmodules_unmerged(struct index_state *istate)
39 int pos = index_name_pos(istate, GITMODULES_FILE, strlen(GITMODULES_FILE));
40 if (pos < 0) { /* .gitmodules not found or isn't merged */
41 pos = -1 - pos;
42 if (istate->cache_nr > pos) { /* there is a .gitmodules */
43 const struct cache_entry *ce = istate->cache[pos];
44 if (ce_namelen(ce) == strlen(GITMODULES_FILE) &&
45 !strcmp(ce->name, GITMODULES_FILE))
46 return 1;
50 return 0;
54 * Check if the .gitmodules file is safe to write.
56 * Writing to the .gitmodules file requires that the file exists in the
57 * working tree or, if it doesn't, that a brand new .gitmodules file is going
58 * to be created (i.e. it's neither in the index nor in the current branch).
60 * It is not safe to write to .gitmodules if it's not in the working tree but
61 * it is in the index or in the current branch, because writing new values
62 * (and staging them) would blindly overwrite ALL the old content.
64 int is_writing_gitmodules_ok(void)
66 struct object_id oid;
67 return file_exists(GITMODULES_FILE) ||
68 (get_oid(GITMODULES_INDEX, &oid) < 0 && get_oid(GITMODULES_HEAD, &oid) < 0);
72 * Check if the .gitmodules file has unstaged modifications. This must be
73 * checked before allowing modifications to the .gitmodules file with the
74 * intention to stage them later, because when continuing we would stage the
75 * modifications the user didn't stage herself too. That might change in a
76 * future version when we learn to stage the changes we do ourselves without
77 * staging any previous modifications.
79 int is_staging_gitmodules_ok(struct index_state *istate)
81 int pos = index_name_pos(istate, GITMODULES_FILE, strlen(GITMODULES_FILE));
83 if ((pos >= 0) && (pos < istate->cache_nr)) {
84 struct stat st;
85 if (lstat(GITMODULES_FILE, &st) == 0 &&
86 ie_modified(istate, istate->cache[pos], &st, 0) & DATA_CHANGED)
87 return 0;
90 return 1;
93 static int for_each_remote_ref_submodule(const char *submodule,
94 each_ref_fn fn, void *cb_data)
96 return refs_for_each_remote_ref(get_submodule_ref_store(submodule),
97 fn, cb_data);
101 * Try to update the "path" entry in the "submodule.<name>" section of the
102 * .gitmodules file. Return 0 only if a .gitmodules file was found, a section
103 * with the correct path=<oldpath> setting was found and we could update it.
105 int update_path_in_gitmodules(const char *oldpath, const char *newpath)
107 struct strbuf entry = STRBUF_INIT;
108 const struct submodule *submodule;
109 int ret;
111 if (!file_exists(GITMODULES_FILE)) /* Do nothing without .gitmodules */
112 return -1;
114 if (is_gitmodules_unmerged(the_repository->index))
115 die(_("Cannot change unmerged .gitmodules, resolve merge conflicts first"));
117 submodule = submodule_from_path(the_repository, null_oid(), oldpath);
118 if (!submodule || !submodule->name) {
119 warning(_("Could not find section in .gitmodules where path=%s"), oldpath);
120 return -1;
122 strbuf_addstr(&entry, "submodule.");
123 strbuf_addstr(&entry, submodule->name);
124 strbuf_addstr(&entry, ".path");
125 ret = config_set_in_gitmodules_file_gently(entry.buf, newpath);
126 strbuf_release(&entry);
127 return ret;
131 * Try to remove the "submodule.<name>" section from .gitmodules where the given
132 * path is configured. Return 0 only if a .gitmodules file was found, a section
133 * with the correct path=<path> setting was found and we could remove it.
135 int remove_path_from_gitmodules(const char *path)
137 struct strbuf sect = STRBUF_INIT;
138 const struct submodule *submodule;
140 if (!file_exists(GITMODULES_FILE)) /* Do nothing without .gitmodules */
141 return -1;
143 if (is_gitmodules_unmerged(the_repository->index))
144 die(_("Cannot change unmerged .gitmodules, resolve merge conflicts first"));
146 submodule = submodule_from_path(the_repository, null_oid(), path);
147 if (!submodule || !submodule->name) {
148 warning(_("Could not find section in .gitmodules where path=%s"), path);
149 return -1;
151 strbuf_addstr(&sect, "submodule.");
152 strbuf_addstr(&sect, submodule->name);
153 if (git_config_rename_section_in_file(GITMODULES_FILE, sect.buf, NULL) < 0) {
154 /* Maybe the user already did that, don't error out here */
155 warning(_("Could not remove .gitmodules entry for %s"), path);
156 strbuf_release(&sect);
157 return -1;
159 strbuf_release(&sect);
160 return 0;
163 void stage_updated_gitmodules(struct index_state *istate)
165 if (add_file_to_index(istate, GITMODULES_FILE, 0))
166 die(_("staging updated .gitmodules failed"));
169 static struct string_list added_submodule_odb_paths = STRING_LIST_INIT_NODUP;
171 void add_submodule_odb_by_path(const char *path)
173 string_list_insert(&added_submodule_odb_paths, xstrdup(path));
176 int register_all_submodule_odb_as_alternates(void)
178 int i;
179 int ret = added_submodule_odb_paths.nr;
181 for (i = 0; i < added_submodule_odb_paths.nr; i++)
182 add_to_alternates_memory(added_submodule_odb_paths.items[i].string);
183 if (ret) {
184 string_list_clear(&added_submodule_odb_paths, 0);
185 trace2_data_intmax("submodule", the_repository,
186 "register_all_submodule_odb_as_alternates/registered", ret);
187 if (git_env_bool("GIT_TEST_FATAL_REGISTER_SUBMODULE_ODB", 0))
188 BUG("register_all_submodule_odb_as_alternates() called");
190 return ret;
193 void set_diffopt_flags_from_submodule_config(struct diff_options *diffopt,
194 const char *path)
196 const struct submodule *submodule = submodule_from_path(the_repository,
197 null_oid(),
198 path);
199 if (submodule) {
200 const char *ignore;
201 char *key;
203 key = xstrfmt("submodule.%s.ignore", submodule->name);
204 if (repo_config_get_string_tmp(the_repository, key, &ignore))
205 ignore = submodule->ignore;
206 free(key);
208 if (ignore)
209 handle_ignore_submodules_arg(diffopt, ignore);
210 else if (is_gitmodules_unmerged(the_repository->index))
211 diffopt->flags.ignore_submodules = 1;
215 /* Cheap function that only determines if we're interested in submodules at all */
216 int git_default_submodule_config(const char *var, const char *value,
217 void *UNUSED(cb))
219 if (!strcmp(var, "submodule.recurse")) {
220 int v = git_config_bool(var, value) ?
221 RECURSE_SUBMODULES_ON : RECURSE_SUBMODULES_OFF;
222 config_update_recurse_submodules = v;
224 return 0;
227 int option_parse_recurse_submodules_worktree_updater(const struct option *opt,
228 const char *arg, int unset)
230 if (unset) {
231 config_update_recurse_submodules = RECURSE_SUBMODULES_OFF;
232 return 0;
234 if (arg)
235 config_update_recurse_submodules =
236 parse_update_recurse_submodules_arg(opt->long_name,
237 arg);
238 else
239 config_update_recurse_submodules = RECURSE_SUBMODULES_ON;
241 return 0;
245 * Determine if a submodule has been initialized at a given 'path'
248 * NEEDSWORK: Emit a warning if submodule.active exists, but is valueless,
249 * ie, the config looks like: "[submodule] active\n".
250 * Since that is an invalid pathspec, we should inform the user.
252 int is_tree_submodule_active(struct repository *repo,
253 const struct object_id *treeish_name,
254 const char *path)
256 int ret = 0;
257 char *key = NULL;
258 char *value = NULL;
259 const struct string_list *sl;
260 const struct submodule *module;
262 module = submodule_from_path(repo, treeish_name, path);
264 /* early return if there isn't a path->module mapping */
265 if (!module)
266 return 0;
268 /* submodule.<name>.active is set */
269 key = xstrfmt("submodule.%s.active", module->name);
270 if (!repo_config_get_bool(repo, key, &ret)) {
271 free(key);
272 return ret;
274 free(key);
276 /* submodule.active is set */
277 sl = repo_config_get_value_multi(repo, "submodule.active");
278 if (sl) {
279 struct pathspec ps;
280 struct strvec args = STRVEC_INIT;
281 const struct string_list_item *item;
283 for_each_string_list_item(item, sl) {
284 strvec_push(&args, item->string);
287 parse_pathspec(&ps, 0, 0, NULL, args.v);
288 ret = match_pathspec(repo->index, &ps, path, strlen(path), 0, NULL, 1);
290 strvec_clear(&args);
291 clear_pathspec(&ps);
292 return ret;
295 /* fallback to checking if the URL is set */
296 key = xstrfmt("submodule.%s.url", module->name);
297 ret = !repo_config_get_string(repo, key, &value);
299 free(value);
300 free(key);
301 return ret;
304 int is_submodule_active(struct repository *repo, const char *path)
306 return is_tree_submodule_active(repo, null_oid(), path);
309 int is_submodule_populated_gently(const char *path, int *return_error_code)
311 int ret = 0;
312 char *gitdir = xstrfmt("%s/.git", path);
314 if (resolve_gitdir_gently(gitdir, return_error_code))
315 ret = 1;
317 free(gitdir);
318 return ret;
322 * Dies if the provided 'prefix' corresponds to an unpopulated submodule
324 void die_in_unpopulated_submodule(struct index_state *istate,
325 const char *prefix)
327 int i, prefixlen;
329 if (!prefix)
330 return;
332 prefixlen = strlen(prefix);
334 for (i = 0; i < istate->cache_nr; i++) {
335 struct cache_entry *ce = istate->cache[i];
336 int ce_len = ce_namelen(ce);
338 if (!S_ISGITLINK(ce->ce_mode))
339 continue;
340 if (prefixlen <= ce_len)
341 continue;
342 if (strncmp(ce->name, prefix, ce_len))
343 continue;
344 if (prefix[ce_len] != '/')
345 continue;
347 die(_("in unpopulated submodule '%s'"), ce->name);
352 * Dies if any paths in the provided pathspec descends into a submodule
354 void die_path_inside_submodule(struct index_state *istate,
355 const struct pathspec *ps)
357 int i, j;
359 for (i = 0; i < istate->cache_nr; i++) {
360 struct cache_entry *ce = istate->cache[i];
361 int ce_len = ce_namelen(ce);
363 if (!S_ISGITLINK(ce->ce_mode))
364 continue;
366 for (j = 0; j < ps->nr ; j++) {
367 const struct pathspec_item *item = &ps->items[j];
369 if (item->len <= ce_len)
370 continue;
371 if (item->match[ce_len] != '/')
372 continue;
373 if (strncmp(ce->name, item->match, ce_len))
374 continue;
375 if (item->len == ce_len + 1)
376 continue;
378 die(_("Pathspec '%s' is in submodule '%.*s'"),
379 item->original, ce_len, ce->name);
384 enum submodule_update_type parse_submodule_update_type(const char *value)
386 if (!strcmp(value, "none"))
387 return SM_UPDATE_NONE;
388 else if (!strcmp(value, "checkout"))
389 return SM_UPDATE_CHECKOUT;
390 else if (!strcmp(value, "rebase"))
391 return SM_UPDATE_REBASE;
392 else if (!strcmp(value, "merge"))
393 return SM_UPDATE_MERGE;
394 else if (*value == '!')
395 return SM_UPDATE_COMMAND;
396 else
397 return SM_UPDATE_UNSPECIFIED;
400 int parse_submodule_update_strategy(const char *value,
401 struct submodule_update_strategy *dst)
403 enum submodule_update_type type;
405 free((void*)dst->command);
406 dst->command = NULL;
408 type = parse_submodule_update_type(value);
409 if (type == SM_UPDATE_UNSPECIFIED)
410 return -1;
412 dst->type = type;
413 if (type == SM_UPDATE_COMMAND)
414 dst->command = xstrdup(value + 1);
416 return 0;
419 const char *submodule_strategy_to_string(const struct submodule_update_strategy *s)
421 struct strbuf sb = STRBUF_INIT;
422 switch (s->type) {
423 case SM_UPDATE_CHECKOUT:
424 return "checkout";
425 case SM_UPDATE_MERGE:
426 return "merge";
427 case SM_UPDATE_REBASE:
428 return "rebase";
429 case SM_UPDATE_NONE:
430 return "none";
431 case SM_UPDATE_UNSPECIFIED:
432 return NULL;
433 case SM_UPDATE_COMMAND:
434 strbuf_addf(&sb, "!%s", s->command);
435 return strbuf_detach(&sb, NULL);
437 return NULL;
440 void handle_ignore_submodules_arg(struct diff_options *diffopt,
441 const char *arg)
443 diffopt->flags.ignore_submodule_set = 1;
444 diffopt->flags.ignore_submodules = 0;
445 diffopt->flags.ignore_untracked_in_submodules = 0;
446 diffopt->flags.ignore_dirty_submodules = 0;
448 if (!strcmp(arg, "all"))
449 diffopt->flags.ignore_submodules = 1;
450 else if (!strcmp(arg, "untracked"))
451 diffopt->flags.ignore_untracked_in_submodules = 1;
452 else if (!strcmp(arg, "dirty"))
453 diffopt->flags.ignore_dirty_submodules = 1;
454 else if (strcmp(arg, "none"))
455 die(_("bad --ignore-submodules argument: %s"), arg);
457 * Please update _git_status() in git-completion.bash when you
458 * add new options
462 static int prepare_submodule_diff_summary(struct repository *r, struct rev_info *rev,
463 const char *path,
464 struct commit *left, struct commit *right,
465 struct commit_list *merge_bases)
467 struct commit_list *list;
469 repo_init_revisions(r, rev, NULL);
470 setup_revisions(0, NULL, rev, NULL);
471 rev->left_right = 1;
472 rev->first_parent_only = 1;
473 left->object.flags |= SYMMETRIC_LEFT;
474 add_pending_object(rev, &left->object, path);
475 add_pending_object(rev, &right->object, path);
476 for (list = merge_bases; list; list = list->next) {
477 list->item->object.flags |= UNINTERESTING;
478 add_pending_object(rev, &list->item->object,
479 oid_to_hex(&list->item->object.oid));
481 return prepare_revision_walk(rev);
484 static void print_submodule_diff_summary(struct repository *r, struct rev_info *rev, struct diff_options *o)
486 static const char format[] = " %m %s";
487 struct strbuf sb = STRBUF_INIT;
488 struct commit *commit;
490 while ((commit = get_revision(rev))) {
491 struct pretty_print_context ctx = {0};
492 ctx.date_mode = rev->date_mode;
493 ctx.output_encoding = get_log_output_encoding();
494 strbuf_setlen(&sb, 0);
495 repo_format_commit_message(r, commit, format, &sb,
496 &ctx);
497 strbuf_addch(&sb, '\n');
498 if (commit->object.flags & SYMMETRIC_LEFT)
499 diff_emit_submodule_del(o, sb.buf);
500 else
501 diff_emit_submodule_add(o, sb.buf);
503 strbuf_release(&sb);
506 void prepare_submodule_repo_env(struct strvec *out)
508 prepare_other_repo_env(out, DEFAULT_GIT_DIR_ENVIRONMENT);
511 static void prepare_submodule_repo_env_in_gitdir(struct strvec *out)
513 prepare_other_repo_env(out, ".");
517 * Initialize a repository struct for a submodule based on the provided 'path'.
519 * Returns the repository struct on success,
520 * NULL when the submodule is not present.
522 static struct repository *open_submodule(const char *path)
524 struct strbuf sb = STRBUF_INIT;
525 struct repository *out = xmalloc(sizeof(*out));
527 if (submodule_to_gitdir(&sb, path) || repo_init(out, sb.buf, NULL)) {
528 strbuf_release(&sb);
529 free(out);
530 return NULL;
533 /* Mark it as a submodule */
534 out->submodule_prefix = xstrdup(path);
536 strbuf_release(&sb);
537 return out;
541 * Helper function to display the submodule header line prior to the full
542 * summary output.
544 * If it can locate the submodule git directory it will create a repository
545 * handle for the submodule and lookup both the left and right commits and
546 * put them into the left and right pointers.
548 static void show_submodule_header(struct diff_options *o,
549 const char *path,
550 struct object_id *one, struct object_id *two,
551 unsigned dirty_submodule,
552 struct repository *sub,
553 struct commit **left, struct commit **right,
554 struct commit_list **merge_bases)
556 const char *message = NULL;
557 struct strbuf sb = STRBUF_INIT;
558 int fast_forward = 0, fast_backward = 0;
560 if (dirty_submodule & DIRTY_SUBMODULE_UNTRACKED)
561 diff_emit_submodule_untracked(o, path);
563 if (dirty_submodule & DIRTY_SUBMODULE_MODIFIED)
564 diff_emit_submodule_modified(o, path);
566 if (is_null_oid(one))
567 message = "(new submodule)";
568 else if (is_null_oid(two))
569 message = "(submodule deleted)";
571 if (!sub) {
572 if (!message)
573 message = "(commits not present)";
574 goto output_header;
578 * Attempt to lookup the commit references, and determine if this is
579 * a fast forward or fast backwards update.
581 *left = lookup_commit_reference(sub, one);
582 *right = lookup_commit_reference(sub, two);
585 * Warn about missing commits in the submodule project, but only if
586 * they aren't null.
588 if ((!is_null_oid(one) && !*left) ||
589 (!is_null_oid(two) && !*right))
590 message = "(commits not present)";
592 *merge_bases = repo_get_merge_bases(sub, *left, *right);
593 if (*merge_bases) {
594 if ((*merge_bases)->item == *left)
595 fast_forward = 1;
596 else if ((*merge_bases)->item == *right)
597 fast_backward = 1;
600 if (oideq(one, two)) {
601 strbuf_release(&sb);
602 return;
605 output_header:
606 strbuf_addf(&sb, "Submodule %s ", path);
607 strbuf_add_unique_abbrev(&sb, one, DEFAULT_ABBREV);
608 strbuf_addstr(&sb, (fast_backward || fast_forward) ? ".." : "...");
609 strbuf_add_unique_abbrev(&sb, two, DEFAULT_ABBREV);
610 if (message)
611 strbuf_addf(&sb, " %s\n", message);
612 else
613 strbuf_addf(&sb, "%s:\n", fast_backward ? " (rewind)" : "");
614 diff_emit_submodule_header(o, sb.buf);
616 strbuf_release(&sb);
619 void show_submodule_diff_summary(struct diff_options *o, const char *path,
620 struct object_id *one, struct object_id *two,
621 unsigned dirty_submodule)
623 struct rev_info rev = REV_INFO_INIT;
624 struct commit *left = NULL, *right = NULL;
625 struct commit_list *merge_bases = NULL;
626 struct repository *sub;
628 sub = open_submodule(path);
629 show_submodule_header(o, path, one, two, dirty_submodule,
630 sub, &left, &right, &merge_bases);
633 * If we don't have both a left and a right pointer, there is no
634 * reason to try and display a summary. The header line should contain
635 * all the information the user needs.
637 if (!left || !right || !sub)
638 goto out;
640 /* Treat revision walker failure the same as missing commits */
641 if (prepare_submodule_diff_summary(sub, &rev, path, left, right, merge_bases)) {
642 diff_emit_submodule_error(o, "(revision walker failed)\n");
643 goto out;
646 print_submodule_diff_summary(sub, &rev, o);
648 out:
649 free_commit_list(merge_bases);
650 release_revisions(&rev);
651 clear_commit_marks(left, ~0);
652 clear_commit_marks(right, ~0);
653 if (sub) {
654 repo_clear(sub);
655 free(sub);
659 void show_submodule_inline_diff(struct diff_options *o, const char *path,
660 struct object_id *one, struct object_id *two,
661 unsigned dirty_submodule)
663 const struct object_id *old_oid = the_hash_algo->empty_tree, *new_oid = the_hash_algo->empty_tree;
664 struct commit *left = NULL, *right = NULL;
665 struct commit_list *merge_bases = NULL;
666 struct child_process cp = CHILD_PROCESS_INIT;
667 struct strbuf sb = STRBUF_INIT;
668 struct repository *sub;
670 sub = open_submodule(path);
671 show_submodule_header(o, path, one, two, dirty_submodule,
672 sub, &left, &right, &merge_bases);
674 /* We need a valid left and right commit to display a difference */
675 if (!(left || is_null_oid(one)) ||
676 !(right || is_null_oid(two)))
677 goto done;
679 if (left)
680 old_oid = one;
681 if (right)
682 new_oid = two;
684 cp.git_cmd = 1;
685 cp.dir = path;
686 cp.out = -1;
687 cp.no_stdin = 1;
689 /* TODO: other options may need to be passed here. */
690 strvec_pushl(&cp.args, "diff", "--submodule=diff", NULL);
691 strvec_pushf(&cp.args, "--color=%s", want_color(o->use_color) ?
692 "always" : "never");
694 if (o->flags.reverse_diff) {
695 strvec_pushf(&cp.args, "--src-prefix=%s%s/",
696 o->b_prefix, path);
697 strvec_pushf(&cp.args, "--dst-prefix=%s%s/",
698 o->a_prefix, path);
699 } else {
700 strvec_pushf(&cp.args, "--src-prefix=%s%s/",
701 o->a_prefix, path);
702 strvec_pushf(&cp.args, "--dst-prefix=%s%s/",
703 o->b_prefix, path);
705 strvec_push(&cp.args, oid_to_hex(old_oid));
707 * If the submodule has modified content, we will diff against the
708 * work tree, under the assumption that the user has asked for the
709 * diff format and wishes to actually see all differences even if they
710 * haven't yet been committed to the submodule yet.
712 if (!(dirty_submodule & DIRTY_SUBMODULE_MODIFIED))
713 strvec_push(&cp.args, oid_to_hex(new_oid));
715 prepare_submodule_repo_env(&cp.env);
717 if (!is_directory(path)) {
718 /* fall back to absorbed git dir, if any */
719 if (!sub)
720 goto done;
721 cp.dir = sub->gitdir;
722 strvec_push(&cp.env, GIT_DIR_ENVIRONMENT "=.");
723 strvec_push(&cp.env, GIT_WORK_TREE_ENVIRONMENT "=.");
726 if (start_command(&cp)) {
727 diff_emit_submodule_error(o, "(diff failed)\n");
728 goto done;
731 while (strbuf_getwholeline_fd(&sb, cp.out, '\n') != EOF)
732 diff_emit_submodule_pipethrough(o, sb.buf, sb.len);
734 if (finish_command(&cp))
735 diff_emit_submodule_error(o, "(diff failed)\n");
737 done:
738 strbuf_release(&sb);
739 free_commit_list(merge_bases);
740 if (left)
741 clear_commit_marks(left, ~0);
742 if (right)
743 clear_commit_marks(right, ~0);
744 if (sub) {
745 repo_clear(sub);
746 free(sub);
750 int should_update_submodules(void)
752 return config_update_recurse_submodules == RECURSE_SUBMODULES_ON;
755 const struct submodule *submodule_from_ce(const struct cache_entry *ce)
757 if (!S_ISGITLINK(ce->ce_mode))
758 return NULL;
760 if (!should_update_submodules())
761 return NULL;
763 return submodule_from_path(the_repository, null_oid(), ce->name);
767 struct collect_changed_submodules_cb_data {
768 struct repository *repo;
769 struct string_list *changed;
770 const struct object_id *commit_oid;
774 * this would normally be two functions: default_name_from_path() and
775 * path_from_default_name(). Since the default name is the same as
776 * the submodule path we can get away with just one function which only
777 * checks whether there is a submodule in the working directory at that
778 * location.
780 static const char *default_name_or_path(const char *path_or_name)
782 int error_code;
784 if (!is_submodule_populated_gently(path_or_name, &error_code))
785 return NULL;
787 return path_or_name;
791 * Holds relevant information for a changed submodule. Used as the .util
792 * member of the changed submodule name string_list_item.
794 * (super_oid, path) allows the submodule config to be read from _some_
795 * .gitmodules file. We store this information the first time we find a
796 * superproject commit that points to the submodule, but this is
797 * arbitrary - we can choose any (super_oid, path) that matches the
798 * submodule's name.
800 * NEEDSWORK: Storing an arbitrary commit is undesirable because we can't
801 * guarantee that we're reading the commit that the user would expect. A better
802 * scheme would be to just fetch a submodule by its name. This requires two
803 * steps:
804 * - Create a function that behaves like repo_submodule_init(), but accepts a
805 * submodule name instead of treeish_name and path. This should be easy
806 * because repo_submodule_init() internally uses the submodule's name.
808 * - Replace most instances of 'struct submodule' (which is the .gitmodules
809 * config) with just the submodule name. This is OK because we expect
810 * submodule settings to be stored in .git/config (via "git submodule init"),
811 * not .gitmodules. This also lets us delete get_non_gitmodules_submodule(),
812 * which constructs a bogus 'struct submodule' for the sake of giving a
813 * placeholder name to a gitlink.
815 struct changed_submodule_data {
817 * The first superproject commit in the rev walk that points to
818 * the submodule.
820 const struct object_id *super_oid;
822 * Path to the submodule in the superproject commit referenced
823 * by 'super_oid'.
825 char *path;
826 /* The submodule commits that have changed in the rev walk. */
827 struct oid_array new_commits;
830 static void changed_submodule_data_clear(struct changed_submodule_data *cs_data)
832 oid_array_clear(&cs_data->new_commits);
833 free(cs_data->path);
836 static void collect_changed_submodules_cb(struct diff_queue_struct *q,
837 struct diff_options *options,
838 void *data)
840 struct collect_changed_submodules_cb_data *me = data;
841 struct string_list *changed = me->changed;
842 const struct object_id *commit_oid = me->commit_oid;
843 int i;
845 for (i = 0; i < q->nr; i++) {
846 struct diff_filepair *p = q->queue[i];
847 const struct submodule *submodule;
848 const char *name;
849 struct string_list_item *item;
850 struct changed_submodule_data *cs_data;
852 if (!S_ISGITLINK(p->two->mode))
853 continue;
855 submodule = submodule_from_path(me->repo,
856 commit_oid, p->two->path);
857 if (submodule)
858 name = submodule->name;
859 else {
860 name = default_name_or_path(p->two->path);
861 /* make sure name does not collide with existing one */
862 if (name)
863 submodule = submodule_from_name(me->repo,
864 commit_oid, name);
865 if (submodule) {
866 warning(_("Submodule in commit %s at path: "
867 "'%s' collides with a submodule named "
868 "the same. Skipping it."),
869 oid_to_hex(commit_oid), p->two->path);
870 name = NULL;
874 if (!name)
875 continue;
877 item = string_list_insert(changed, name);
878 if (item->util)
879 cs_data = item->util;
880 else {
881 item->util = xcalloc(1, sizeof(struct changed_submodule_data));
882 cs_data = item->util;
883 cs_data->super_oid = commit_oid;
884 cs_data->path = xstrdup(p->two->path);
886 oid_array_append(&cs_data->new_commits, &p->two->oid);
891 * Collect the paths of submodules in 'changed' which have changed based on
892 * the revisions as specified in 'argv'. Each entry in 'changed' will also
893 * have a corresponding 'struct oid_array' (in the 'util' field) which lists
894 * what the submodule pointers were updated to during the change.
896 static void collect_changed_submodules(struct repository *r,
897 struct string_list *changed,
898 struct strvec *argv)
900 struct rev_info rev;
901 const struct commit *commit;
902 int save_warning;
903 struct setup_revision_opt s_r_opt = {
904 .assume_dashdash = 1,
907 save_warning = warn_on_object_refname_ambiguity;
908 warn_on_object_refname_ambiguity = 0;
909 repo_init_revisions(r, &rev, NULL);
910 setup_revisions(argv->nr, argv->v, &rev, &s_r_opt);
911 warn_on_object_refname_ambiguity = save_warning;
912 if (prepare_revision_walk(&rev))
913 die(_("revision walk setup failed"));
915 while ((commit = get_revision(&rev))) {
916 struct rev_info diff_rev;
917 struct collect_changed_submodules_cb_data data;
918 data.repo = r;
919 data.changed = changed;
920 data.commit_oid = &commit->object.oid;
922 repo_init_revisions(r, &diff_rev, NULL);
923 diff_rev.diffopt.output_format |= DIFF_FORMAT_CALLBACK;
924 diff_rev.diffopt.format_callback = collect_changed_submodules_cb;
925 diff_rev.diffopt.format_callback_data = &data;
926 diff_rev.dense_combined_merges = 1;
927 diff_tree_combined_merge(commit, &diff_rev);
928 release_revisions(&diff_rev);
931 reset_revision_walk();
932 release_revisions(&rev);
935 static void free_submodules_data(struct string_list *submodules)
937 struct string_list_item *item;
938 for_each_string_list_item(item, submodules)
939 changed_submodule_data_clear(item->util);
941 string_list_clear(submodules, 1);
944 static int has_remote(const char *UNUSED(refname),
945 const struct object_id *UNUSED(oid),
946 int UNUSED(flags), void *UNUSED(cb_data))
948 return 1;
951 static int append_oid_to_argv(const struct object_id *oid, void *data)
953 struct strvec *argv = data;
954 strvec_push(argv, oid_to_hex(oid));
955 return 0;
958 struct has_commit_data {
959 struct repository *repo;
960 int result;
961 const char *path;
962 const struct object_id *super_oid;
965 static int check_has_commit(const struct object_id *oid, void *data)
967 struct has_commit_data *cb = data;
968 struct repository subrepo;
969 enum object_type type;
971 if (repo_submodule_init(&subrepo, cb->repo, cb->path, cb->super_oid)) {
972 cb->result = 0;
973 /* subrepo failed to init, so don't clean it up. */
974 return 0;
977 type = oid_object_info(&subrepo, oid, NULL);
979 switch (type) {
980 case OBJ_COMMIT:
981 goto cleanup;
982 case OBJ_BAD:
984 * Object is missing or invalid. If invalid, an error message
985 * has already been printed.
987 cb->result = 0;
988 goto cleanup;
989 default:
990 die(_("submodule entry '%s' (%s) is a %s, not a commit"),
991 cb->path, oid_to_hex(oid), type_name(type));
993 cleanup:
994 repo_clear(&subrepo);
995 return 0;
998 static int submodule_has_commits(struct repository *r,
999 const char *path,
1000 const struct object_id *super_oid,
1001 struct oid_array *commits)
1003 struct has_commit_data has_commit = {
1004 .repo = r,
1005 .result = 1,
1006 .path = path,
1007 .super_oid = super_oid
1010 oid_array_for_each_unique(commits, check_has_commit, &has_commit);
1012 if (has_commit.result) {
1014 * Even if the submodule is checked out and the commit is
1015 * present, make sure it exists in the submodule's object store
1016 * and that it is reachable from a ref.
1018 struct child_process cp = CHILD_PROCESS_INIT;
1019 struct strbuf out = STRBUF_INIT;
1021 strvec_pushl(&cp.args, "rev-list", "-n", "1", NULL);
1022 oid_array_for_each_unique(commits, append_oid_to_argv, &cp.args);
1023 strvec_pushl(&cp.args, "--not", "--all", NULL);
1025 prepare_submodule_repo_env(&cp.env);
1026 cp.git_cmd = 1;
1027 cp.no_stdin = 1;
1028 cp.dir = path;
1030 if (capture_command(&cp, &out, GIT_MAX_HEXSZ + 1) || out.len)
1031 has_commit.result = 0;
1033 strbuf_release(&out);
1036 return has_commit.result;
1039 static int submodule_needs_pushing(struct repository *r,
1040 const char *path,
1041 struct oid_array *commits)
1043 if (!submodule_has_commits(r, path, null_oid(), commits))
1045 * NOTE: We do consider it safe to return "no" here. The
1046 * correct answer would be "We do not know" instead of
1047 * "No push needed", but it is quite hard to change
1048 * the submodule pointer without having the submodule
1049 * around. If a user did however change the submodules
1050 * without having the submodule around, this indicates
1051 * an expert who knows what they are doing or a
1052 * maintainer integrating work from other people. In
1053 * both cases it should be safe to skip this check.
1055 return 0;
1057 if (for_each_remote_ref_submodule(path, has_remote, NULL) > 0) {
1058 struct child_process cp = CHILD_PROCESS_INIT;
1059 struct strbuf buf = STRBUF_INIT;
1060 int needs_pushing = 0;
1062 strvec_push(&cp.args, "rev-list");
1063 oid_array_for_each_unique(commits, append_oid_to_argv, &cp.args);
1064 strvec_pushl(&cp.args, "--not", "--remotes", "-n", "1" , NULL);
1066 prepare_submodule_repo_env(&cp.env);
1067 cp.git_cmd = 1;
1068 cp.no_stdin = 1;
1069 cp.out = -1;
1070 cp.dir = path;
1071 if (start_command(&cp))
1072 die(_("Could not run 'git rev-list <commits> --not --remotes -n 1' command in submodule %s"),
1073 path);
1074 if (strbuf_read(&buf, cp.out, the_hash_algo->hexsz + 1))
1075 needs_pushing = 1;
1076 finish_command(&cp);
1077 close(cp.out);
1078 strbuf_release(&buf);
1079 return needs_pushing;
1082 return 0;
1085 int find_unpushed_submodules(struct repository *r,
1086 struct oid_array *commits,
1087 const char *remotes_name,
1088 struct string_list *needs_pushing)
1090 struct string_list submodules = STRING_LIST_INIT_DUP;
1091 struct string_list_item *name;
1092 struct strvec argv = STRVEC_INIT;
1094 /* argv.v[0] will be ignored by setup_revisions */
1095 strvec_push(&argv, "find_unpushed_submodules");
1096 oid_array_for_each_unique(commits, append_oid_to_argv, &argv);
1097 strvec_push(&argv, "--not");
1098 strvec_pushf(&argv, "--remotes=%s", remotes_name);
1100 collect_changed_submodules(r, &submodules, &argv);
1102 for_each_string_list_item(name, &submodules) {
1103 struct changed_submodule_data *cs_data = name->util;
1104 const struct submodule *submodule;
1105 const char *path = NULL;
1107 submodule = submodule_from_name(r, null_oid(), name->string);
1108 if (submodule)
1109 path = submodule->path;
1110 else
1111 path = default_name_or_path(name->string);
1113 if (!path)
1114 continue;
1116 if (submodule_needs_pushing(r, path, &cs_data->new_commits))
1117 string_list_insert(needs_pushing, path);
1120 free_submodules_data(&submodules);
1121 strvec_clear(&argv);
1123 return needs_pushing->nr;
1126 static int push_submodule(const char *path,
1127 const struct remote *remote,
1128 const struct refspec *rs,
1129 const struct string_list *push_options,
1130 int dry_run)
1132 if (for_each_remote_ref_submodule(path, has_remote, NULL) > 0) {
1133 struct child_process cp = CHILD_PROCESS_INIT;
1134 strvec_push(&cp.args, "push");
1135 if (dry_run)
1136 strvec_push(&cp.args, "--dry-run");
1138 if (push_options && push_options->nr) {
1139 const struct string_list_item *item;
1140 for_each_string_list_item(item, push_options)
1141 strvec_pushf(&cp.args, "--push-option=%s",
1142 item->string);
1145 if (remote->origin != REMOTE_UNCONFIGURED) {
1146 int i;
1147 strvec_push(&cp.args, remote->name);
1148 for (i = 0; i < rs->raw_nr; i++)
1149 strvec_push(&cp.args, rs->raw[i]);
1152 prepare_submodule_repo_env(&cp.env);
1153 cp.git_cmd = 1;
1154 cp.no_stdin = 1;
1155 cp.dir = path;
1156 if (run_command(&cp))
1157 return 0;
1158 close(cp.out);
1161 return 1;
1165 * Perform a check in the submodule to see if the remote and refspec work.
1166 * Die if the submodule can't be pushed.
1168 static void submodule_push_check(const char *path, const char *head,
1169 const struct remote *remote,
1170 const struct refspec *rs)
1172 struct child_process cp = CHILD_PROCESS_INIT;
1173 int i;
1175 strvec_push(&cp.args, "submodule--helper");
1176 strvec_push(&cp.args, "push-check");
1177 strvec_push(&cp.args, head);
1178 strvec_push(&cp.args, remote->name);
1180 for (i = 0; i < rs->raw_nr; i++)
1181 strvec_push(&cp.args, rs->raw[i]);
1183 prepare_submodule_repo_env(&cp.env);
1184 cp.git_cmd = 1;
1185 cp.no_stdin = 1;
1186 cp.no_stdout = 1;
1187 cp.dir = path;
1190 * Simply indicate if 'submodule--helper push-check' failed.
1191 * More detailed error information will be provided by the
1192 * child process.
1194 if (run_command(&cp))
1195 die(_("process for submodule '%s' failed"), path);
1198 int push_unpushed_submodules(struct repository *r,
1199 struct oid_array *commits,
1200 const struct remote *remote,
1201 const struct refspec *rs,
1202 const struct string_list *push_options,
1203 int dry_run)
1205 int i, ret = 1;
1206 struct string_list needs_pushing = STRING_LIST_INIT_DUP;
1208 if (!find_unpushed_submodules(r, commits,
1209 remote->name, &needs_pushing))
1210 return 1;
1213 * Verify that the remote and refspec can be propagated to all
1214 * submodules. This check can be skipped if the remote and refspec
1215 * won't be propagated due to the remote being unconfigured (e.g. a URL
1216 * instead of a remote name).
1218 if (remote->origin != REMOTE_UNCONFIGURED) {
1219 char *head;
1220 struct object_id head_oid;
1222 head = resolve_refdup("HEAD", 0, &head_oid, NULL);
1223 if (!head)
1224 die(_("Failed to resolve HEAD as a valid ref."));
1226 for (i = 0; i < needs_pushing.nr; i++)
1227 submodule_push_check(needs_pushing.items[i].string,
1228 head, remote, rs);
1229 free(head);
1232 /* Actually push the submodules */
1233 for (i = 0; i < needs_pushing.nr; i++) {
1234 const char *path = needs_pushing.items[i].string;
1235 fprintf(stderr, _("Pushing submodule '%s'\n"), path);
1236 if (!push_submodule(path, remote, rs,
1237 push_options, dry_run)) {
1238 fprintf(stderr, _("Unable to push submodule '%s'\n"), path);
1239 ret = 0;
1243 string_list_clear(&needs_pushing, 0);
1245 return ret;
1248 static int append_oid_to_array(const char *UNUSED(ref),
1249 const struct object_id *oid,
1250 int UNUSED(flags), void *data)
1252 struct oid_array *array = data;
1253 oid_array_append(array, oid);
1254 return 0;
1257 void check_for_new_submodule_commits(struct object_id *oid)
1259 if (!initialized_fetch_ref_tips) {
1260 for_each_ref(append_oid_to_array, &ref_tips_before_fetch);
1261 initialized_fetch_ref_tips = 1;
1264 oid_array_append(&ref_tips_after_fetch, oid);
1268 * Returns 1 if there is at least one submodule gitdir in
1269 * $GIT_DIR/modules and 0 otherwise. This follows
1270 * submodule_name_to_gitdir(), which looks for submodules in
1271 * $GIT_DIR/modules, not $GIT_COMMON_DIR.
1273 * A submodule can be moved to $GIT_DIR/modules manually by running "git
1274 * submodule absorbgitdirs", or it may be initialized there by "git
1275 * submodule update".
1277 static int repo_has_absorbed_submodules(struct repository *r)
1279 int ret;
1280 struct strbuf buf = STRBUF_INIT;
1282 strbuf_repo_git_path(&buf, r, "modules/");
1283 ret = file_exists(buf.buf) && !is_empty_dir(buf.buf);
1284 strbuf_release(&buf);
1285 return ret;
1288 static void calculate_changed_submodule_paths(struct repository *r,
1289 struct string_list *changed_submodule_names)
1291 struct strvec argv = STRVEC_INIT;
1292 struct string_list_item *name;
1294 /* No need to check if no submodules would be fetched */
1295 if (!submodule_from_path(r, NULL, NULL) &&
1296 !repo_has_absorbed_submodules(r))
1297 return;
1299 strvec_push(&argv, "--"); /* argv[0] program name */
1300 oid_array_for_each_unique(&ref_tips_after_fetch,
1301 append_oid_to_argv, &argv);
1302 strvec_push(&argv, "--not");
1303 oid_array_for_each_unique(&ref_tips_before_fetch,
1304 append_oid_to_argv, &argv);
1307 * Collect all submodules (whether checked out or not) for which new
1308 * commits have been recorded upstream in "changed_submodule_names".
1310 collect_changed_submodules(r, changed_submodule_names, &argv);
1312 for_each_string_list_item(name, changed_submodule_names) {
1313 struct changed_submodule_data *cs_data = name->util;
1314 const struct submodule *submodule;
1315 const char *path = NULL;
1317 submodule = submodule_from_name(r, null_oid(), name->string);
1318 if (submodule)
1319 path = submodule->path;
1320 else
1321 path = default_name_or_path(name->string);
1323 if (!path)
1324 continue;
1326 if (submodule_has_commits(r, path, null_oid(), &cs_data->new_commits)) {
1327 changed_submodule_data_clear(cs_data);
1328 *name->string = '\0';
1332 string_list_remove_empty_items(changed_submodule_names, 1);
1334 strvec_clear(&argv);
1335 oid_array_clear(&ref_tips_before_fetch);
1336 oid_array_clear(&ref_tips_after_fetch);
1337 initialized_fetch_ref_tips = 0;
1340 int submodule_touches_in_range(struct repository *r,
1341 struct object_id *excl_oid,
1342 struct object_id *incl_oid)
1344 struct string_list subs = STRING_LIST_INIT_DUP;
1345 struct strvec args = STRVEC_INIT;
1346 int ret;
1348 /* No need to check if there are no submodules configured */
1349 if (!submodule_from_path(r, NULL, NULL))
1350 return 0;
1352 strvec_push(&args, "--"); /* args[0] program name */
1353 strvec_push(&args, oid_to_hex(incl_oid));
1354 if (!is_null_oid(excl_oid)) {
1355 strvec_push(&args, "--not");
1356 strvec_push(&args, oid_to_hex(excl_oid));
1359 collect_changed_submodules(r, &subs, &args);
1360 ret = subs.nr;
1362 strvec_clear(&args);
1364 free_submodules_data(&subs);
1365 return ret;
1368 struct submodule_parallel_fetch {
1370 * The index of the last index entry processed by
1371 * get_fetch_task_from_index().
1373 int index_count;
1375 * The index of the last string_list entry processed by
1376 * get_fetch_task_from_changed().
1378 int changed_count;
1379 struct strvec args;
1380 struct repository *r;
1381 const char *prefix;
1382 int command_line_option;
1383 int default_option;
1384 int quiet;
1385 int result;
1388 * Names of submodules that have new commits. Generated by
1389 * walking the newly fetched superproject commits.
1391 struct string_list changed_submodule_names;
1393 * Names of submodules that have already been processed. Lets us
1394 * avoid fetching the same submodule more than once.
1396 struct string_list seen_submodule_names;
1398 /* Pending fetches by OIDs */
1399 struct fetch_task **oid_fetch_tasks;
1400 int oid_fetch_tasks_nr, oid_fetch_tasks_alloc;
1402 struct strbuf submodules_with_errors;
1404 #define SPF_INIT { \
1405 .args = STRVEC_INIT, \
1406 .changed_submodule_names = STRING_LIST_INIT_DUP, \
1407 .seen_submodule_names = STRING_LIST_INIT_DUP, \
1408 .submodules_with_errors = STRBUF_INIT, \
1411 static int get_fetch_recurse_config(const struct submodule *submodule,
1412 struct submodule_parallel_fetch *spf)
1414 if (spf->command_line_option != RECURSE_SUBMODULES_DEFAULT)
1415 return spf->command_line_option;
1417 if (submodule) {
1418 char *key;
1419 const char *value;
1421 int fetch_recurse = submodule->fetch_recurse;
1422 key = xstrfmt("submodule.%s.fetchRecurseSubmodules", submodule->name);
1423 if (!repo_config_get_string_tmp(spf->r, key, &value)) {
1424 fetch_recurse = parse_fetch_recurse_submodules_arg(key, value);
1426 free(key);
1428 if (fetch_recurse != RECURSE_SUBMODULES_NONE)
1429 /* local config overrules everything except commandline */
1430 return fetch_recurse;
1433 return spf->default_option;
1437 * Fetch in progress (if callback data) or
1438 * pending (if in oid_fetch_tasks in struct submodule_parallel_fetch)
1440 struct fetch_task {
1441 struct repository *repo;
1442 const struct submodule *sub;
1443 unsigned free_sub : 1; /* Do we need to free the submodule? */
1444 const char *default_argv; /* The default fetch mode. */
1445 struct strvec git_args; /* Args for the child git process. */
1447 struct oid_array *commits; /* Ensure these commits are fetched */
1451 * When a submodule is not defined in .gitmodules, we cannot access it
1452 * via the regular submodule-config. Create a fake submodule, which we can
1453 * work on.
1455 static const struct submodule *get_non_gitmodules_submodule(const char *path)
1457 struct submodule *ret = NULL;
1458 const char *name = default_name_or_path(path);
1460 if (!name)
1461 return NULL;
1463 ret = xmalloc(sizeof(*ret));
1464 memset(ret, 0, sizeof(*ret));
1465 ret->path = name;
1466 ret->name = name;
1468 return (const struct submodule *) ret;
1471 static void fetch_task_release(struct fetch_task *p)
1473 if (p->free_sub)
1474 free((void*)p->sub);
1475 p->free_sub = 0;
1476 p->sub = NULL;
1478 if (p->repo)
1479 repo_clear(p->repo);
1480 FREE_AND_NULL(p->repo);
1482 strvec_clear(&p->git_args);
1485 static struct repository *get_submodule_repo_for(struct repository *r,
1486 const char *path,
1487 const struct object_id *treeish_name)
1489 struct repository *ret = xmalloc(sizeof(*ret));
1491 if (repo_submodule_init(ret, r, path, treeish_name)) {
1492 free(ret);
1493 return NULL;
1496 return ret;
1499 static struct fetch_task *fetch_task_create(struct submodule_parallel_fetch *spf,
1500 const char *path,
1501 const struct object_id *treeish_name)
1503 struct fetch_task *task = xmalloc(sizeof(*task));
1504 memset(task, 0, sizeof(*task));
1506 task->sub = submodule_from_path(spf->r, treeish_name, path);
1508 if (!task->sub) {
1510 * No entry in .gitmodules? Technically not a submodule,
1511 * but historically we supported repositories that happen to be
1512 * in-place where a gitlink is. Keep supporting them.
1514 task->sub = get_non_gitmodules_submodule(path);
1515 if (!task->sub)
1516 goto cleanup;
1518 task->free_sub = 1;
1521 if (string_list_lookup(&spf->seen_submodule_names, task->sub->name))
1522 goto cleanup;
1524 switch (get_fetch_recurse_config(task->sub, spf))
1526 default:
1527 case RECURSE_SUBMODULES_DEFAULT:
1528 case RECURSE_SUBMODULES_ON_DEMAND:
1529 if (!task->sub ||
1530 !string_list_lookup(
1531 &spf->changed_submodule_names,
1532 task->sub->name))
1533 goto cleanup;
1534 task->default_argv = "on-demand";
1535 break;
1536 case RECURSE_SUBMODULES_ON:
1537 task->default_argv = "yes";
1538 break;
1539 case RECURSE_SUBMODULES_OFF:
1540 goto cleanup;
1543 task->repo = get_submodule_repo_for(spf->r, path, treeish_name);
1545 return task;
1547 cleanup:
1548 fetch_task_release(task);
1549 free(task);
1550 return NULL;
1553 static struct fetch_task *
1554 get_fetch_task_from_index(struct submodule_parallel_fetch *spf,
1555 struct strbuf *err)
1557 for (; spf->index_count < spf->r->index->cache_nr; spf->index_count++) {
1558 const struct cache_entry *ce =
1559 spf->r->index->cache[spf->index_count];
1560 struct fetch_task *task;
1562 if (!S_ISGITLINK(ce->ce_mode))
1563 continue;
1565 task = fetch_task_create(spf, ce->name, null_oid());
1566 if (!task)
1567 continue;
1569 if (task->repo) {
1570 if (!spf->quiet)
1571 strbuf_addf(err, _("Fetching submodule %s%s\n"),
1572 spf->prefix, ce->name);
1574 spf->index_count++;
1575 return task;
1576 } else {
1577 struct strbuf empty_submodule_path = STRBUF_INIT;
1579 fetch_task_release(task);
1580 free(task);
1583 * An empty directory is normal,
1584 * the submodule is not initialized
1586 strbuf_addf(&empty_submodule_path, "%s/%s/",
1587 spf->r->worktree,
1588 ce->name);
1589 if (S_ISGITLINK(ce->ce_mode) &&
1590 !is_empty_dir(empty_submodule_path.buf)) {
1591 spf->result = 1;
1592 strbuf_addf(err,
1593 _("Could not access submodule '%s'\n"),
1594 ce->name);
1596 strbuf_release(&empty_submodule_path);
1599 return NULL;
1602 static struct fetch_task *
1603 get_fetch_task_from_changed(struct submodule_parallel_fetch *spf,
1604 struct strbuf *err)
1606 for (; spf->changed_count < spf->changed_submodule_names.nr;
1607 spf->changed_count++) {
1608 struct string_list_item item =
1609 spf->changed_submodule_names.items[spf->changed_count];
1610 struct changed_submodule_data *cs_data = item.util;
1611 struct fetch_task *task;
1613 if (!is_tree_submodule_active(spf->r, cs_data->super_oid,cs_data->path))
1614 continue;
1616 task = fetch_task_create(spf, cs_data->path,
1617 cs_data->super_oid);
1618 if (!task)
1619 continue;
1621 if (!task->repo) {
1622 strbuf_addf(err, _("Could not access submodule '%s' at commit %s\n"),
1623 cs_data->path,
1624 find_unique_abbrev(cs_data->super_oid, DEFAULT_ABBREV));
1626 fetch_task_release(task);
1627 free(task);
1628 continue;
1631 if (!spf->quiet)
1632 strbuf_addf(err,
1633 _("Fetching submodule %s%s at commit %s\n"),
1634 spf->prefix, task->sub->path,
1635 find_unique_abbrev(cs_data->super_oid,
1636 DEFAULT_ABBREV));
1638 spf->changed_count++;
1640 * NEEDSWORK: Submodules set/unset a value for
1641 * core.worktree when they are populated/unpopulated by
1642 * "git checkout" (and similar commands, see
1643 * submodule_move_head() and
1644 * connect_work_tree_and_git_dir()), but if the
1645 * submodule is unpopulated in another way (e.g. "git
1646 * rm", "rm -r"), core.worktree will still be set even
1647 * though the directory doesn't exist, and the child
1648 * process will crash while trying to chdir into the
1649 * nonexistent directory.
1651 * In this case, we know that the submodule has no
1652 * working tree, so we can work around this by
1653 * setting "--work-tree=." (--bare does not work because
1654 * worktree settings take precedence over bare-ness).
1655 * However, this is not necessarily true in other cases,
1656 * so a generalized solution is still necessary.
1658 * Possible solutions:
1659 * - teach "git [add|rm]" to unset core.worktree and
1660 * discourage users from removing submodules without
1661 * using a Git command.
1662 * - teach submodule child processes to ignore stale
1663 * core.worktree values.
1665 strvec_push(&task->git_args, "--work-tree=.");
1666 return task;
1668 return NULL;
1671 static int get_next_submodule(struct child_process *cp, struct strbuf *err,
1672 void *data, void **task_cb)
1674 struct submodule_parallel_fetch *spf = data;
1675 struct fetch_task *task =
1676 get_fetch_task_from_index(spf, err);
1677 if (!task)
1678 task = get_fetch_task_from_changed(spf, err);
1680 if (task) {
1681 struct strbuf submodule_prefix = STRBUF_INIT;
1683 child_process_init(cp);
1684 cp->dir = task->repo->gitdir;
1685 prepare_submodule_repo_env_in_gitdir(&cp->env);
1686 cp->git_cmd = 1;
1687 strvec_init(&cp->args);
1688 if (task->git_args.nr)
1689 strvec_pushv(&cp->args, task->git_args.v);
1690 strvec_pushv(&cp->args, spf->args.v);
1691 strvec_push(&cp->args, task->default_argv);
1692 strvec_push(&cp->args, "--submodule-prefix");
1694 strbuf_addf(&submodule_prefix, "%s%s/",
1695 spf->prefix,
1696 task->sub->path);
1697 strvec_push(&cp->args, submodule_prefix.buf);
1698 *task_cb = task;
1700 strbuf_release(&submodule_prefix);
1701 string_list_insert(&spf->seen_submodule_names, task->sub->name);
1702 return 1;
1705 if (spf->oid_fetch_tasks_nr) {
1706 struct fetch_task *task =
1707 spf->oid_fetch_tasks[spf->oid_fetch_tasks_nr - 1];
1708 struct strbuf submodule_prefix = STRBUF_INIT;
1709 spf->oid_fetch_tasks_nr--;
1711 strbuf_addf(&submodule_prefix, "%s%s/",
1712 spf->prefix, task->sub->path);
1714 child_process_init(cp);
1715 prepare_submodule_repo_env_in_gitdir(&cp->env);
1716 cp->git_cmd = 1;
1717 cp->dir = task->repo->gitdir;
1719 strvec_init(&cp->args);
1720 strvec_pushv(&cp->args, spf->args.v);
1721 strvec_push(&cp->args, "on-demand");
1722 strvec_push(&cp->args, "--submodule-prefix");
1723 strvec_push(&cp->args, submodule_prefix.buf);
1725 /* NEEDSWORK: have get_default_remote from submodule--helper */
1726 strvec_push(&cp->args, "origin");
1727 oid_array_for_each_unique(task->commits,
1728 append_oid_to_argv, &cp->args);
1730 *task_cb = task;
1731 strbuf_release(&submodule_prefix);
1732 return 1;
1735 return 0;
1738 static int fetch_start_failure(struct strbuf *err,
1739 void *cb, void *task_cb)
1741 struct submodule_parallel_fetch *spf = cb;
1742 struct fetch_task *task = task_cb;
1744 spf->result = 1;
1746 fetch_task_release(task);
1747 return 0;
1750 static int commit_missing_in_sub(const struct object_id *oid, void *data)
1752 struct repository *subrepo = data;
1754 enum object_type type = oid_object_info(subrepo, oid, NULL);
1756 return type != OBJ_COMMIT;
1759 static int fetch_finish(int retvalue, struct strbuf *err,
1760 void *cb, void *task_cb)
1762 struct submodule_parallel_fetch *spf = cb;
1763 struct fetch_task *task = task_cb;
1765 struct string_list_item *it;
1766 struct changed_submodule_data *cs_data;
1768 if (!task || !task->sub)
1769 BUG("callback cookie bogus");
1771 if (retvalue) {
1773 * NEEDSWORK: This indicates that the overall fetch
1774 * failed, even though there may be a subsequent fetch
1775 * by commit hash that might work. It may be a good
1776 * idea to not indicate failure in this case, and only
1777 * indicate failure if the subsequent fetch fails.
1779 spf->result = 1;
1781 strbuf_addf(&spf->submodules_with_errors, "\t%s\n",
1782 task->sub->name);
1785 /* Is this the second time we process this submodule? */
1786 if (task->commits)
1787 goto out;
1789 it = string_list_lookup(&spf->changed_submodule_names, task->sub->name);
1790 if (!it)
1791 /* Could be an unchanged submodule, not contained in the list */
1792 goto out;
1794 cs_data = it->util;
1795 oid_array_filter(&cs_data->new_commits,
1796 commit_missing_in_sub,
1797 task->repo);
1799 /* Are there commits we want, but do not exist? */
1800 if (cs_data->new_commits.nr) {
1801 task->commits = &cs_data->new_commits;
1802 ALLOC_GROW(spf->oid_fetch_tasks,
1803 spf->oid_fetch_tasks_nr + 1,
1804 spf->oid_fetch_tasks_alloc);
1805 spf->oid_fetch_tasks[spf->oid_fetch_tasks_nr] = task;
1806 spf->oid_fetch_tasks_nr++;
1807 return 0;
1810 out:
1811 fetch_task_release(task);
1813 return 0;
1816 int fetch_submodules(struct repository *r,
1817 const struct strvec *options,
1818 const char *prefix, int command_line_option,
1819 int default_option,
1820 int quiet, int max_parallel_jobs)
1822 int i;
1823 struct submodule_parallel_fetch spf = SPF_INIT;
1825 spf.r = r;
1826 spf.command_line_option = command_line_option;
1827 spf.default_option = default_option;
1828 spf.quiet = quiet;
1829 spf.prefix = prefix;
1831 if (!r->worktree)
1832 goto out;
1834 if (repo_read_index(r) < 0)
1835 die(_("index file corrupt"));
1837 strvec_push(&spf.args, "fetch");
1838 for (i = 0; i < options->nr; i++)
1839 strvec_push(&spf.args, options->v[i]);
1840 strvec_push(&spf.args, "--recurse-submodules-default");
1841 /* default value, "--submodule-prefix" and its value are added later */
1843 calculate_changed_submodule_paths(r, &spf.changed_submodule_names);
1844 string_list_sort(&spf.changed_submodule_names);
1845 run_processes_parallel_tr2(max_parallel_jobs,
1846 get_next_submodule,
1847 fetch_start_failure,
1848 fetch_finish,
1849 &spf,
1850 "submodule", "parallel/fetch");
1852 if (spf.submodules_with_errors.len > 0)
1853 fprintf(stderr, _("Errors during submodule fetch:\n%s"),
1854 spf.submodules_with_errors.buf);
1857 strvec_clear(&spf.args);
1858 out:
1859 free_submodules_data(&spf.changed_submodule_names);
1860 return spf.result;
1863 unsigned is_submodule_modified(const char *path, int ignore_untracked)
1865 struct child_process cp = CHILD_PROCESS_INIT;
1866 struct strbuf buf = STRBUF_INIT;
1867 FILE *fp;
1868 unsigned dirty_submodule = 0;
1869 const char *git_dir;
1870 int ignore_cp_exit_code = 0;
1872 strbuf_addf(&buf, "%s/.git", path);
1873 git_dir = read_gitfile(buf.buf);
1874 if (!git_dir)
1875 git_dir = buf.buf;
1876 if (!is_git_directory(git_dir)) {
1877 if (is_directory(git_dir))
1878 die(_("'%s' not recognized as a git repository"), git_dir);
1879 strbuf_release(&buf);
1880 /* The submodule is not checked out, so it is not modified */
1881 return 0;
1883 strbuf_reset(&buf);
1885 strvec_pushl(&cp.args, "status", "--porcelain=2", NULL);
1886 if (ignore_untracked)
1887 strvec_push(&cp.args, "-uno");
1889 prepare_submodule_repo_env(&cp.env);
1890 cp.git_cmd = 1;
1891 cp.no_stdin = 1;
1892 cp.out = -1;
1893 cp.dir = path;
1894 if (start_command(&cp))
1895 die(_("Could not run 'git status --porcelain=2' in submodule %s"), path);
1897 fp = xfdopen(cp.out, "r");
1898 while (strbuf_getwholeline(&buf, fp, '\n') != EOF) {
1899 /* regular untracked files */
1900 if (buf.buf[0] == '?')
1901 dirty_submodule |= DIRTY_SUBMODULE_UNTRACKED;
1903 if (buf.buf[0] == 'u' ||
1904 buf.buf[0] == '1' ||
1905 buf.buf[0] == '2') {
1906 /* T = line type, XY = status, SSSS = submodule state */
1907 if (buf.len < strlen("T XY SSSS"))
1908 BUG("invalid status --porcelain=2 line %s",
1909 buf.buf);
1911 if (buf.buf[5] == 'S' && buf.buf[8] == 'U')
1912 /* nested untracked file */
1913 dirty_submodule |= DIRTY_SUBMODULE_UNTRACKED;
1915 if (buf.buf[0] == 'u' ||
1916 buf.buf[0] == '2' ||
1917 memcmp(buf.buf + 5, "S..U", 4))
1918 /* other change */
1919 dirty_submodule |= DIRTY_SUBMODULE_MODIFIED;
1922 if ((dirty_submodule & DIRTY_SUBMODULE_MODIFIED) &&
1923 ((dirty_submodule & DIRTY_SUBMODULE_UNTRACKED) ||
1924 ignore_untracked)) {
1926 * We're not interested in any further information from
1927 * the child any more, neither output nor its exit code.
1929 ignore_cp_exit_code = 1;
1930 break;
1933 fclose(fp);
1935 if (finish_command(&cp) && !ignore_cp_exit_code)
1936 die(_("'git status --porcelain=2' failed in submodule %s"), path);
1938 strbuf_release(&buf);
1939 return dirty_submodule;
1942 int submodule_uses_gitfile(const char *path)
1944 struct child_process cp = CHILD_PROCESS_INIT;
1945 struct strbuf buf = STRBUF_INIT;
1946 const char *git_dir;
1948 strbuf_addf(&buf, "%s/.git", path);
1949 git_dir = read_gitfile(buf.buf);
1950 if (!git_dir) {
1951 strbuf_release(&buf);
1952 return 0;
1954 strbuf_release(&buf);
1956 /* Now test that all nested submodules use a gitfile too */
1957 strvec_pushl(&cp.args,
1958 "submodule", "foreach", "--quiet", "--recursive",
1959 "test -f .git", NULL);
1961 prepare_submodule_repo_env(&cp.env);
1962 cp.git_cmd = 1;
1963 cp.no_stdin = 1;
1964 cp.no_stderr = 1;
1965 cp.no_stdout = 1;
1966 cp.dir = path;
1967 if (run_command(&cp))
1968 return 0;
1970 return 1;
1974 * Check if it is a bad idea to remove a submodule, i.e. if we'd lose data
1975 * when doing so.
1977 * Return 1 if we'd lose data, return 0 if the removal is fine,
1978 * and negative values for errors.
1980 int bad_to_remove_submodule(const char *path, unsigned flags)
1982 ssize_t len;
1983 struct child_process cp = CHILD_PROCESS_INIT;
1984 struct strbuf buf = STRBUF_INIT;
1985 int ret = 0;
1987 if (!file_exists(path) || is_empty_dir(path))
1988 return 0;
1990 if (!submodule_uses_gitfile(path))
1991 return 1;
1993 strvec_pushl(&cp.args, "status", "--porcelain",
1994 "--ignore-submodules=none", NULL);
1996 if (flags & SUBMODULE_REMOVAL_IGNORE_UNTRACKED)
1997 strvec_push(&cp.args, "-uno");
1998 else
1999 strvec_push(&cp.args, "-uall");
2001 if (!(flags & SUBMODULE_REMOVAL_IGNORE_IGNORED_UNTRACKED))
2002 strvec_push(&cp.args, "--ignored");
2004 prepare_submodule_repo_env(&cp.env);
2005 cp.git_cmd = 1;
2006 cp.no_stdin = 1;
2007 cp.out = -1;
2008 cp.dir = path;
2009 if (start_command(&cp)) {
2010 if (flags & SUBMODULE_REMOVAL_DIE_ON_ERROR)
2011 die(_("could not start 'git status' in submodule '%s'"),
2012 path);
2013 ret = -1;
2014 goto out;
2017 len = strbuf_read(&buf, cp.out, 1024);
2018 if (len > 2)
2019 ret = 1;
2020 close(cp.out);
2022 if (finish_command(&cp)) {
2023 if (flags & SUBMODULE_REMOVAL_DIE_ON_ERROR)
2024 die(_("could not run 'git status' in submodule '%s'"),
2025 path);
2026 ret = -1;
2028 out:
2029 strbuf_release(&buf);
2030 return ret;
2033 void submodule_unset_core_worktree(const struct submodule *sub)
2035 struct strbuf config_path = STRBUF_INIT;
2037 submodule_name_to_gitdir(&config_path, the_repository, sub->name);
2038 strbuf_addstr(&config_path, "/config");
2040 if (git_config_set_in_file_gently(config_path.buf, "core.worktree", NULL))
2041 warning(_("Could not unset core.worktree setting in submodule '%s'"),
2042 sub->path);
2044 strbuf_release(&config_path);
2047 static const char *get_super_prefix_or_empty(void)
2049 const char *s = get_super_prefix();
2050 if (!s)
2051 s = "";
2052 return s;
2055 static int submodule_has_dirty_index(const struct submodule *sub)
2057 struct child_process cp = CHILD_PROCESS_INIT;
2059 prepare_submodule_repo_env(&cp.env);
2061 cp.git_cmd = 1;
2062 strvec_pushl(&cp.args, "diff-index", "--quiet",
2063 "--cached", "HEAD", NULL);
2064 cp.no_stdin = 1;
2065 cp.no_stdout = 1;
2066 cp.dir = sub->path;
2067 if (start_command(&cp))
2068 die(_("could not recurse into submodule '%s'"), sub->path);
2070 return finish_command(&cp);
2073 static void submodule_reset_index(const char *path)
2075 struct child_process cp = CHILD_PROCESS_INIT;
2076 prepare_submodule_repo_env(&cp.env);
2078 cp.git_cmd = 1;
2079 cp.no_stdin = 1;
2080 cp.dir = path;
2082 strvec_pushf(&cp.args, "--super-prefix=%s%s/",
2083 get_super_prefix_or_empty(), path);
2084 /* TODO: determine if this might overwright untracked files */
2085 strvec_pushl(&cp.args, "read-tree", "-u", "--reset", NULL);
2087 strvec_push(&cp.args, empty_tree_oid_hex());
2089 if (run_command(&cp))
2090 die(_("could not reset submodule index"));
2094 * Moves a submodule at a given path from a given head to another new head.
2095 * For edge cases (a submodule coming into existence or removing a submodule)
2096 * pass NULL for old or new respectively.
2098 int submodule_move_head(const char *path,
2099 const char *old_head,
2100 const char *new_head,
2101 unsigned flags)
2103 int ret = 0;
2104 struct child_process cp = CHILD_PROCESS_INIT;
2105 const struct submodule *sub;
2106 int *error_code_ptr, error_code;
2108 if (!is_submodule_active(the_repository, path))
2109 return 0;
2111 if (flags & SUBMODULE_MOVE_HEAD_FORCE)
2113 * Pass non NULL pointer to is_submodule_populated_gently
2114 * to prevent die()-ing. We'll use connect_work_tree_and_git_dir
2115 * to fixup the submodule in the force case later.
2117 error_code_ptr = &error_code;
2118 else
2119 error_code_ptr = NULL;
2121 if (old_head && !is_submodule_populated_gently(path, error_code_ptr))
2122 return 0;
2124 sub = submodule_from_path(the_repository, null_oid(), path);
2126 if (!sub)
2127 BUG("could not get submodule information for '%s'", path);
2129 if (old_head && !(flags & SUBMODULE_MOVE_HEAD_FORCE)) {
2130 /* Check if the submodule has a dirty index. */
2131 if (submodule_has_dirty_index(sub))
2132 return error(_("submodule '%s' has dirty index"), path);
2135 if (!(flags & SUBMODULE_MOVE_HEAD_DRY_RUN)) {
2136 if (old_head) {
2137 if (!submodule_uses_gitfile(path))
2138 absorb_git_dir_into_superproject(path,
2139 ABSORB_GITDIR_RECURSE_SUBMODULES);
2140 } else {
2141 struct strbuf gitdir = STRBUF_INIT;
2142 submodule_name_to_gitdir(&gitdir, the_repository,
2143 sub->name);
2144 connect_work_tree_and_git_dir(path, gitdir.buf, 0);
2145 strbuf_release(&gitdir);
2147 /* make sure the index is clean as well */
2148 submodule_reset_index(path);
2151 if (old_head && (flags & SUBMODULE_MOVE_HEAD_FORCE)) {
2152 struct strbuf gitdir = STRBUF_INIT;
2153 submodule_name_to_gitdir(&gitdir, the_repository,
2154 sub->name);
2155 connect_work_tree_and_git_dir(path, gitdir.buf, 1);
2156 strbuf_release(&gitdir);
2160 prepare_submodule_repo_env(&cp.env);
2162 cp.git_cmd = 1;
2163 cp.no_stdin = 1;
2164 cp.dir = path;
2166 strvec_pushf(&cp.args, "--super-prefix=%s%s/",
2167 get_super_prefix_or_empty(), path);
2168 strvec_pushl(&cp.args, "read-tree", "--recurse-submodules", NULL);
2170 if (flags & SUBMODULE_MOVE_HEAD_DRY_RUN)
2171 strvec_push(&cp.args, "-n");
2172 else
2173 strvec_push(&cp.args, "-u");
2175 if (flags & SUBMODULE_MOVE_HEAD_FORCE)
2176 strvec_push(&cp.args, "--reset");
2177 else
2178 strvec_push(&cp.args, "-m");
2180 if (!(flags & SUBMODULE_MOVE_HEAD_FORCE))
2181 strvec_push(&cp.args, old_head ? old_head : empty_tree_oid_hex());
2183 strvec_push(&cp.args, new_head ? new_head : empty_tree_oid_hex());
2185 if (run_command(&cp)) {
2186 ret = error(_("Submodule '%s' could not be updated."), path);
2187 goto out;
2190 if (!(flags & SUBMODULE_MOVE_HEAD_DRY_RUN)) {
2191 if (new_head) {
2192 child_process_init(&cp);
2193 /* also set the HEAD accordingly */
2194 cp.git_cmd = 1;
2195 cp.no_stdin = 1;
2196 cp.dir = path;
2198 prepare_submodule_repo_env(&cp.env);
2199 strvec_pushl(&cp.args, "update-ref", "HEAD",
2200 "--no-deref", new_head, NULL);
2202 if (run_command(&cp)) {
2203 ret = -1;
2204 goto out;
2206 } else {
2207 struct strbuf sb = STRBUF_INIT;
2209 strbuf_addf(&sb, "%s/.git", path);
2210 unlink_or_warn(sb.buf);
2211 strbuf_release(&sb);
2213 if (is_empty_dir(path))
2214 rmdir_or_warn(path);
2216 submodule_unset_core_worktree(sub);
2219 out:
2220 return ret;
2223 int validate_submodule_git_dir(char *git_dir, const char *submodule_name)
2225 size_t len = strlen(git_dir), suffix_len = strlen(submodule_name);
2226 char *p;
2227 int ret = 0;
2229 if (len <= suffix_len || (p = git_dir + len - suffix_len)[-1] != '/' ||
2230 strcmp(p, submodule_name))
2231 BUG("submodule name '%s' not a suffix of git dir '%s'",
2232 submodule_name, git_dir);
2235 * We prevent the contents of sibling submodules' git directories to
2236 * clash.
2238 * Example: having a submodule named `hippo` and another one named
2239 * `hippo/hooks` would result in the git directories
2240 * `.git/modules/hippo/` and `.git/modules/hippo/hooks/`, respectively,
2241 * but the latter directory is already designated to contain the hooks
2242 * of the former.
2244 for (; *p; p++) {
2245 if (is_dir_sep(*p)) {
2246 char c = *p;
2248 *p = '\0';
2249 if (is_git_directory(git_dir))
2250 ret = -1;
2251 *p = c;
2253 if (ret < 0)
2254 return error(_("submodule git dir '%s' is "
2255 "inside git dir '%.*s'"),
2256 git_dir,
2257 (int)(p - git_dir), git_dir);
2261 return 0;
2265 * Embeds a single submodules git directory into the superprojects git dir,
2266 * non recursively.
2268 static void relocate_single_git_dir_into_superproject(const char *path)
2270 char *old_git_dir = NULL, *real_old_git_dir = NULL, *real_new_git_dir = NULL;
2271 struct strbuf new_gitdir = STRBUF_INIT;
2272 const struct submodule *sub;
2274 if (submodule_uses_worktrees(path))
2275 die(_("relocate_gitdir for submodule '%s' with "
2276 "more than one worktree not supported"), path);
2278 old_git_dir = xstrfmt("%s/.git", path);
2279 if (read_gitfile(old_git_dir))
2280 /* If it is an actual gitfile, it doesn't need migration. */
2281 return;
2283 real_old_git_dir = real_pathdup(old_git_dir, 1);
2285 sub = submodule_from_path(the_repository, null_oid(), path);
2286 if (!sub)
2287 die(_("could not lookup name for submodule '%s'"), path);
2289 submodule_name_to_gitdir(&new_gitdir, the_repository, sub->name);
2290 if (validate_submodule_git_dir(new_gitdir.buf, sub->name) < 0)
2291 die(_("refusing to move '%s' into an existing git dir"),
2292 real_old_git_dir);
2293 if (safe_create_leading_directories_const(new_gitdir.buf) < 0)
2294 die(_("could not create directory '%s'"), new_gitdir.buf);
2295 real_new_git_dir = real_pathdup(new_gitdir.buf, 1);
2297 fprintf(stderr, _("Migrating git directory of '%s%s' from\n'%s' to\n'%s'\n"),
2298 get_super_prefix_or_empty(), path,
2299 real_old_git_dir, real_new_git_dir);
2301 relocate_gitdir(path, real_old_git_dir, real_new_git_dir);
2303 free(old_git_dir);
2304 free(real_old_git_dir);
2305 free(real_new_git_dir);
2306 strbuf_release(&new_gitdir);
2310 * Migrate the git directory of the submodule given by path from
2311 * having its git directory within the working tree to the git dir nested
2312 * in its superprojects git dir under modules/.
2314 void absorb_git_dir_into_superproject(const char *path,
2315 unsigned flags)
2317 int err_code;
2318 const char *sub_git_dir;
2319 struct strbuf gitdir = STRBUF_INIT;
2320 strbuf_addf(&gitdir, "%s/.git", path);
2321 sub_git_dir = resolve_gitdir_gently(gitdir.buf, &err_code);
2323 /* Not populated? */
2324 if (!sub_git_dir) {
2325 const struct submodule *sub;
2326 struct strbuf sub_gitdir = STRBUF_INIT;
2328 if (err_code == READ_GITFILE_ERR_STAT_FAILED) {
2329 /* unpopulated as expected */
2330 strbuf_release(&gitdir);
2331 return;
2334 if (err_code != READ_GITFILE_ERR_NOT_A_REPO)
2335 /* We don't know what broke here. */
2336 read_gitfile_error_die(err_code, path, NULL);
2339 * Maybe populated, but no git directory was found?
2340 * This can happen if the superproject is a submodule
2341 * itself and was just absorbed. The absorption of the
2342 * superproject did not rewrite the git file links yet,
2343 * fix it now.
2345 sub = submodule_from_path(the_repository, null_oid(), path);
2346 if (!sub)
2347 die(_("could not lookup name for submodule '%s'"), path);
2348 submodule_name_to_gitdir(&sub_gitdir, the_repository, sub->name);
2349 connect_work_tree_and_git_dir(path, sub_gitdir.buf, 0);
2350 strbuf_release(&sub_gitdir);
2351 } else {
2352 /* Is it already absorbed into the superprojects git dir? */
2353 char *real_sub_git_dir = real_pathdup(sub_git_dir, 1);
2354 char *real_common_git_dir = real_pathdup(get_git_common_dir(), 1);
2356 if (!starts_with(real_sub_git_dir, real_common_git_dir))
2357 relocate_single_git_dir_into_superproject(path);
2359 free(real_sub_git_dir);
2360 free(real_common_git_dir);
2362 strbuf_release(&gitdir);
2364 if (flags & ABSORB_GITDIR_RECURSE_SUBMODULES) {
2365 struct child_process cp = CHILD_PROCESS_INIT;
2366 struct strbuf sb = STRBUF_INIT;
2368 if (flags & ~ABSORB_GITDIR_RECURSE_SUBMODULES)
2369 BUG("we don't know how to pass the flags down?");
2371 strbuf_addstr(&sb, get_super_prefix_or_empty());
2372 strbuf_addstr(&sb, path);
2373 strbuf_addch(&sb, '/');
2375 cp.dir = path;
2376 cp.git_cmd = 1;
2377 cp.no_stdin = 1;
2378 strvec_pushl(&cp.args, "--super-prefix", sb.buf,
2379 "submodule--helper",
2380 "absorbgitdirs", NULL);
2381 prepare_submodule_repo_env(&cp.env);
2382 if (run_command(&cp))
2383 die(_("could not recurse into submodule '%s'"), path);
2385 strbuf_release(&sb);
2389 int get_superproject_working_tree(struct strbuf *buf)
2391 struct child_process cp = CHILD_PROCESS_INIT;
2392 struct strbuf sb = STRBUF_INIT;
2393 struct strbuf one_up = STRBUF_INIT;
2394 char *cwd = xgetcwd();
2395 int ret = 0;
2396 const char *subpath;
2397 int code;
2398 ssize_t len;
2400 if (!is_inside_work_tree())
2402 * FIXME:
2403 * We might have a superproject, but it is harder
2404 * to determine.
2406 return 0;
2408 if (!strbuf_realpath(&one_up, "../", 0))
2409 return 0;
2411 subpath = relative_path(cwd, one_up.buf, &sb);
2412 strbuf_release(&one_up);
2414 prepare_submodule_repo_env(&cp.env);
2415 strvec_pop(&cp.env);
2417 strvec_pushl(&cp.args, "--literal-pathspecs", "-C", "..",
2418 "ls-files", "-z", "--stage", "--full-name", "--",
2419 subpath, NULL);
2420 strbuf_reset(&sb);
2422 cp.no_stdin = 1;
2423 cp.no_stderr = 1;
2424 cp.out = -1;
2425 cp.git_cmd = 1;
2427 if (start_command(&cp))
2428 die(_("could not start ls-files in .."));
2430 len = strbuf_read(&sb, cp.out, PATH_MAX);
2431 close(cp.out);
2433 if (starts_with(sb.buf, "160000")) {
2434 int super_sub_len;
2435 int cwd_len = strlen(cwd);
2436 char *super_sub, *super_wt;
2439 * There is a superproject having this repo as a submodule.
2440 * The format is <mode> SP <hash> SP <stage> TAB <full name> \0,
2441 * We're only interested in the name after the tab.
2443 super_sub = strchr(sb.buf, '\t') + 1;
2444 super_sub_len = strlen(super_sub);
2446 if (super_sub_len > cwd_len ||
2447 strcmp(&cwd[cwd_len - super_sub_len], super_sub))
2448 BUG("returned path string doesn't match cwd?");
2450 super_wt = xstrdup(cwd);
2451 super_wt[cwd_len - super_sub_len] = '\0';
2453 strbuf_realpath(buf, super_wt, 1);
2454 ret = 1;
2455 free(super_wt);
2457 free(cwd);
2458 strbuf_release(&sb);
2460 code = finish_command(&cp);
2462 if (code == 128)
2463 /* '../' is not a git repository */
2464 return 0;
2465 if (code == 0 && len == 0)
2466 /* There is an unrelated git repository at '../' */
2467 return 0;
2468 if (code)
2469 die(_("ls-tree returned unexpected return code %d"), code);
2471 return ret;
2475 * Put the gitdir for a submodule (given relative to the main
2476 * repository worktree) into `buf`, or return -1 on error.
2478 int submodule_to_gitdir(struct strbuf *buf, const char *submodule)
2480 const struct submodule *sub;
2481 const char *git_dir;
2482 int ret = 0;
2484 strbuf_reset(buf);
2485 strbuf_addstr(buf, submodule);
2486 strbuf_complete(buf, '/');
2487 strbuf_addstr(buf, ".git");
2489 git_dir = read_gitfile(buf->buf);
2490 if (git_dir) {
2491 strbuf_reset(buf);
2492 strbuf_addstr(buf, git_dir);
2494 if (!is_git_directory(buf->buf)) {
2495 sub = submodule_from_path(the_repository, null_oid(),
2496 submodule);
2497 if (!sub) {
2498 ret = -1;
2499 goto cleanup;
2501 strbuf_reset(buf);
2502 submodule_name_to_gitdir(buf, the_repository, sub->name);
2505 cleanup:
2506 return ret;
2509 void submodule_name_to_gitdir(struct strbuf *buf, struct repository *r,
2510 const char *submodule_name)
2513 * NEEDSWORK: The current way of mapping a submodule's name to
2514 * its location in .git/modules/ has problems with some naming
2515 * schemes. For example, if a submodule is named "foo" and
2516 * another is named "foo/bar" (whether present in the same
2517 * superproject commit or not - the problem will arise if both
2518 * superproject commits have been checked out at any point in
2519 * time), or if two submodule names only have different cases in
2520 * a case-insensitive filesystem.
2522 * There are several solutions, including encoding the path in
2523 * some way, introducing a submodule.<name>.gitdir config in
2524 * .git/config (not .gitmodules) that allows overriding what the
2525 * gitdir of a submodule would be (and teach Git, upon noticing
2526 * a clash, to automatically determine a non-clashing name and
2527 * to write such a config), or introducing a
2528 * submodule.<name>.gitdir config in .gitmodules that repo
2529 * administrators can explicitly set. Nothing has been decided,
2530 * so for now, just append the name at the end of the path.
2532 strbuf_repo_git_path(buf, r, "modules/");
2533 strbuf_addstr(buf, submodule_name);