Documentation/gitprotocol-v2.txt: fix a slight inconsistency in format
[git/gitster.git] / submodule.c
blob397e41304c086131511ff082c0dc7ed1fbdae48a
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 *cb UNUSED)
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_update_type_to_string(enum submodule_update_type type)
421 switch (type) {
422 case SM_UPDATE_CHECKOUT:
423 return "checkout";
424 case SM_UPDATE_MERGE:
425 return "merge";
426 case SM_UPDATE_REBASE:
427 return "rebase";
428 case SM_UPDATE_NONE:
429 return "none";
430 case SM_UPDATE_UNSPECIFIED:
431 case SM_UPDATE_COMMAND:
432 BUG("init_submodule() should handle type %d", type);
433 default:
434 BUG("unexpected update strategy type: %d", type);
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 = REV_INFO_INIT;
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 free_commit_list(merge_bases);
648 release_revisions(&rev);
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);
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, GIT_DIR_ENVIRONMENT "=.");
721 strvec_push(&cp.env, 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 free_commit_list(merge_bases);
738 if (left)
739 clear_commit_marks(left, ~0);
740 if (right)
741 clear_commit_marks(right, ~0);
742 if (sub) {
743 repo_clear(sub);
744 free(sub);
748 int should_update_submodules(void)
750 return config_update_recurse_submodules == RECURSE_SUBMODULES_ON;
753 const struct submodule *submodule_from_ce(const struct cache_entry *ce)
755 if (!S_ISGITLINK(ce->ce_mode))
756 return NULL;
758 if (!should_update_submodules())
759 return NULL;
761 return submodule_from_path(the_repository, null_oid(), ce->name);
765 struct collect_changed_submodules_cb_data {
766 struct repository *repo;
767 struct string_list *changed;
768 const struct object_id *commit_oid;
772 * this would normally be two functions: default_name_from_path() and
773 * path_from_default_name(). Since the default name is the same as
774 * the submodule path we can get away with just one function which only
775 * checks whether there is a submodule in the working directory at that
776 * location.
778 static const char *default_name_or_path(const char *path_or_name)
780 int error_code;
782 if (!is_submodule_populated_gently(path_or_name, &error_code))
783 return NULL;
785 return path_or_name;
789 * Holds relevant information for a changed submodule. Used as the .util
790 * member of the changed submodule name string_list_item.
792 * (super_oid, path) allows the submodule config to be read from _some_
793 * .gitmodules file. We store this information the first time we find a
794 * superproject commit that points to the submodule, but this is
795 * arbitrary - we can choose any (super_oid, path) that matches the
796 * submodule's name.
798 * NEEDSWORK: Storing an arbitrary commit is undesirable because we can't
799 * guarantee that we're reading the commit that the user would expect. A better
800 * scheme would be to just fetch a submodule by its name. This requires two
801 * steps:
802 * - Create a function that behaves like repo_submodule_init(), but accepts a
803 * submodule name instead of treeish_name and path. This should be easy
804 * because repo_submodule_init() internally uses the submodule's name.
806 * - Replace most instances of 'struct submodule' (which is the .gitmodules
807 * config) with just the submodule name. This is OK because we expect
808 * submodule settings to be stored in .git/config (via "git submodule init"),
809 * not .gitmodules. This also lets us delete get_non_gitmodules_submodule(),
810 * which constructs a bogus 'struct submodule' for the sake of giving a
811 * placeholder name to a gitlink.
813 struct changed_submodule_data {
815 * The first superproject commit in the rev walk that points to
816 * the submodule.
818 const struct object_id *super_oid;
820 * Path to the submodule in the superproject commit referenced
821 * by 'super_oid'.
823 char *path;
824 /* The submodule commits that have changed in the rev walk. */
825 struct oid_array new_commits;
828 static void changed_submodule_data_clear(struct changed_submodule_data *cs_data)
830 oid_array_clear(&cs_data->new_commits);
831 free(cs_data->path);
834 static void collect_changed_submodules_cb(struct diff_queue_struct *q,
835 struct diff_options *options UNUSED,
836 void *data)
838 struct collect_changed_submodules_cb_data *me = data;
839 struct string_list *changed = me->changed;
840 const struct object_id *commit_oid = me->commit_oid;
841 int i;
843 for (i = 0; i < q->nr; i++) {
844 struct diff_filepair *p = q->queue[i];
845 const struct submodule *submodule;
846 const char *name;
847 struct string_list_item *item;
848 struct changed_submodule_data *cs_data;
850 if (!S_ISGITLINK(p->two->mode))
851 continue;
853 submodule = submodule_from_path(me->repo,
854 commit_oid, p->two->path);
855 if (submodule)
856 name = submodule->name;
857 else {
858 name = default_name_or_path(p->two->path);
859 /* make sure name does not collide with existing one */
860 if (name)
861 submodule = submodule_from_name(me->repo,
862 commit_oid, name);
863 if (submodule) {
864 warning(_("Submodule in commit %s at path: "
865 "'%s' collides with a submodule named "
866 "the same. Skipping it."),
867 oid_to_hex(commit_oid), p->two->path);
868 name = NULL;
872 if (!name)
873 continue;
875 item = string_list_insert(changed, name);
876 if (item->util)
877 cs_data = item->util;
878 else {
879 item->util = xcalloc(1, sizeof(struct changed_submodule_data));
880 cs_data = item->util;
881 cs_data->super_oid = commit_oid;
882 cs_data->path = xstrdup(p->two->path);
884 oid_array_append(&cs_data->new_commits, &p->two->oid);
889 * Collect the paths of submodules in 'changed' which have changed based on
890 * the revisions as specified in 'argv'. Each entry in 'changed' will also
891 * have a corresponding 'struct oid_array' (in the 'util' field) which lists
892 * what the submodule pointers were updated to during the change.
894 static void collect_changed_submodules(struct repository *r,
895 struct string_list *changed,
896 struct strvec *argv)
898 struct rev_info rev;
899 const struct commit *commit;
900 int save_warning;
901 struct setup_revision_opt s_r_opt = {
902 .assume_dashdash = 1,
905 save_warning = warn_on_object_refname_ambiguity;
906 warn_on_object_refname_ambiguity = 0;
907 repo_init_revisions(r, &rev, NULL);
908 setup_revisions(argv->nr, argv->v, &rev, &s_r_opt);
909 warn_on_object_refname_ambiguity = save_warning;
910 if (prepare_revision_walk(&rev))
911 die(_("revision walk setup failed"));
913 while ((commit = get_revision(&rev))) {
914 struct rev_info diff_rev;
915 struct collect_changed_submodules_cb_data data;
916 data.repo = r;
917 data.changed = changed;
918 data.commit_oid = &commit->object.oid;
920 repo_init_revisions(r, &diff_rev, NULL);
921 diff_rev.diffopt.output_format |= DIFF_FORMAT_CALLBACK;
922 diff_rev.diffopt.format_callback = collect_changed_submodules_cb;
923 diff_rev.diffopt.format_callback_data = &data;
924 diff_rev.dense_combined_merges = 1;
925 diff_tree_combined_merge(commit, &diff_rev);
926 release_revisions(&diff_rev);
929 reset_revision_walk();
930 release_revisions(&rev);
933 static void free_submodules_data(struct string_list *submodules)
935 struct string_list_item *item;
936 for_each_string_list_item(item, submodules)
937 changed_submodule_data_clear(item->util);
939 string_list_clear(submodules, 1);
942 static int has_remote(const char *refname UNUSED,
943 const struct object_id *oid UNUSED,
944 int flags UNUSED, void *cb_data UNUSED)
946 return 1;
949 static int append_oid_to_argv(const struct object_id *oid, void *data)
951 struct strvec *argv = data;
952 strvec_push(argv, oid_to_hex(oid));
953 return 0;
956 struct has_commit_data {
957 struct repository *repo;
958 int result;
959 const char *path;
960 const struct object_id *super_oid;
963 static int check_has_commit(const struct object_id *oid, void *data)
965 struct has_commit_data *cb = data;
966 struct repository subrepo;
967 enum object_type type;
969 if (repo_submodule_init(&subrepo, cb->repo, cb->path, cb->super_oid)) {
970 cb->result = 0;
971 /* subrepo failed to init, so don't clean it up. */
972 return 0;
975 type = oid_object_info(&subrepo, oid, NULL);
977 switch (type) {
978 case OBJ_COMMIT:
979 goto cleanup;
980 case OBJ_BAD:
982 * Object is missing or invalid. If invalid, an error message
983 * has already been printed.
985 cb->result = 0;
986 goto cleanup;
987 default:
988 die(_("submodule entry '%s' (%s) is a %s, not a commit"),
989 cb->path, oid_to_hex(oid), type_name(type));
991 cleanup:
992 repo_clear(&subrepo);
993 return 0;
996 static int submodule_has_commits(struct repository *r,
997 const char *path,
998 const struct object_id *super_oid,
999 struct oid_array *commits)
1001 struct has_commit_data has_commit = {
1002 .repo = r,
1003 .result = 1,
1004 .path = path,
1005 .super_oid = super_oid
1008 if (validate_submodule_path(path) < 0)
1009 exit(128);
1011 oid_array_for_each_unique(commits, check_has_commit, &has_commit);
1013 if (has_commit.result) {
1015 * Even if the submodule is checked out and the commit is
1016 * present, make sure it exists in the submodule's object store
1017 * and that it is reachable from a ref.
1019 struct child_process cp = CHILD_PROCESS_INIT;
1020 struct strbuf out = STRBUF_INIT;
1022 strvec_pushl(&cp.args, "rev-list", "-n", "1", NULL);
1023 oid_array_for_each_unique(commits, append_oid_to_argv, &cp.args);
1024 strvec_pushl(&cp.args, "--not", "--all", NULL);
1026 prepare_submodule_repo_env(&cp.env);
1027 cp.git_cmd = 1;
1028 cp.no_stdin = 1;
1029 cp.dir = path;
1031 if (capture_command(&cp, &out, GIT_MAX_HEXSZ + 1) || out.len)
1032 has_commit.result = 0;
1034 strbuf_release(&out);
1037 return has_commit.result;
1040 static int submodule_needs_pushing(struct repository *r,
1041 const char *path,
1042 struct oid_array *commits)
1044 if (!submodule_has_commits(r, path, null_oid(), commits))
1046 * NOTE: We do consider it safe to return "no" here. The
1047 * correct answer would be "We do not know" instead of
1048 * "No push needed", but it is quite hard to change
1049 * the submodule pointer without having the submodule
1050 * around. If a user did however change the submodules
1051 * without having the submodule around, this indicates
1052 * an expert who knows what they are doing or a
1053 * maintainer integrating work from other people. In
1054 * both cases it should be safe to skip this check.
1056 return 0;
1058 if (for_each_remote_ref_submodule(path, has_remote, NULL) > 0) {
1059 struct child_process cp = CHILD_PROCESS_INIT;
1060 struct strbuf buf = STRBUF_INIT;
1061 int needs_pushing = 0;
1063 strvec_push(&cp.args, "rev-list");
1064 oid_array_for_each_unique(commits, append_oid_to_argv, &cp.args);
1065 strvec_pushl(&cp.args, "--not", "--remotes", "-n", "1" , NULL);
1067 prepare_submodule_repo_env(&cp.env);
1068 cp.git_cmd = 1;
1069 cp.no_stdin = 1;
1070 cp.out = -1;
1071 cp.dir = path;
1072 if (start_command(&cp))
1073 die(_("Could not run 'git rev-list <commits> --not --remotes -n 1' command in submodule %s"),
1074 path);
1075 if (strbuf_read(&buf, cp.out, the_hash_algo->hexsz + 1))
1076 needs_pushing = 1;
1077 finish_command(&cp);
1078 close(cp.out);
1079 strbuf_release(&buf);
1080 return needs_pushing;
1083 return 0;
1086 int find_unpushed_submodules(struct repository *r,
1087 struct oid_array *commits,
1088 const char *remotes_name,
1089 struct string_list *needs_pushing)
1091 struct string_list submodules = STRING_LIST_INIT_DUP;
1092 struct string_list_item *name;
1093 struct strvec argv = STRVEC_INIT;
1095 /* argv.v[0] will be ignored by setup_revisions */
1096 strvec_push(&argv, "find_unpushed_submodules");
1097 oid_array_for_each_unique(commits, append_oid_to_argv, &argv);
1098 strvec_push(&argv, "--not");
1099 strvec_pushf(&argv, "--remotes=%s", remotes_name);
1101 collect_changed_submodules(r, &submodules, &argv);
1103 for_each_string_list_item(name, &submodules) {
1104 struct changed_submodule_data *cs_data = name->util;
1105 const struct submodule *submodule;
1106 const char *path = NULL;
1108 submodule = submodule_from_name(r, null_oid(), name->string);
1109 if (submodule)
1110 path = submodule->path;
1111 else
1112 path = default_name_or_path(name->string);
1114 if (!path)
1115 continue;
1117 if (submodule_needs_pushing(r, path, &cs_data->new_commits))
1118 string_list_insert(needs_pushing, path);
1121 free_submodules_data(&submodules);
1122 strvec_clear(&argv);
1124 return needs_pushing->nr;
1127 static int push_submodule(const char *path,
1128 const struct remote *remote,
1129 const struct refspec *rs,
1130 const struct string_list *push_options,
1131 int dry_run)
1133 if (validate_submodule_path(path) < 0)
1134 exit(128);
1136 if (for_each_remote_ref_submodule(path, has_remote, NULL) > 0) {
1137 struct child_process cp = CHILD_PROCESS_INIT;
1138 strvec_push(&cp.args, "push");
1140 * When recursing into a submodule, treat any "only" configurations as "on-
1141 * demand", since "only" would not work (we need all submodules to be pushed
1142 * in order to be able to push the superproject).
1144 strvec_push(&cp.args, "--recurse-submodules=only-is-on-demand");
1145 if (dry_run)
1146 strvec_push(&cp.args, "--dry-run");
1148 if (push_options && push_options->nr) {
1149 const struct string_list_item *item;
1150 for_each_string_list_item(item, push_options)
1151 strvec_pushf(&cp.args, "--push-option=%s",
1152 item->string);
1155 if (remote->origin != REMOTE_UNCONFIGURED) {
1156 int i;
1157 strvec_push(&cp.args, remote->name);
1158 for (i = 0; i < rs->raw_nr; i++)
1159 strvec_push(&cp.args, rs->raw[i]);
1162 prepare_submodule_repo_env(&cp.env);
1163 cp.git_cmd = 1;
1164 cp.no_stdin = 1;
1165 cp.dir = path;
1166 if (run_command(&cp))
1167 return 0;
1168 close(cp.out);
1171 return 1;
1175 * Perform a check in the submodule to see if the remote and refspec work.
1176 * Die if the submodule can't be pushed.
1178 static void submodule_push_check(const char *path, const char *head,
1179 const struct remote *remote,
1180 const struct refspec *rs)
1182 struct child_process cp = CHILD_PROCESS_INIT;
1183 int i;
1185 if (validate_submodule_path(path) < 0)
1186 exit(128);
1188 strvec_push(&cp.args, "submodule--helper");
1189 strvec_push(&cp.args, "push-check");
1190 strvec_push(&cp.args, head);
1191 strvec_push(&cp.args, remote->name);
1193 for (i = 0; i < rs->raw_nr; i++)
1194 strvec_push(&cp.args, rs->raw[i]);
1196 prepare_submodule_repo_env(&cp.env);
1197 cp.git_cmd = 1;
1198 cp.no_stdin = 1;
1199 cp.no_stdout = 1;
1200 cp.dir = path;
1203 * Simply indicate if 'submodule--helper push-check' failed.
1204 * More detailed error information will be provided by the
1205 * child process.
1207 if (run_command(&cp))
1208 die(_("process for submodule '%s' failed"), path);
1211 int push_unpushed_submodules(struct repository *r,
1212 struct oid_array *commits,
1213 const struct remote *remote,
1214 const struct refspec *rs,
1215 const struct string_list *push_options,
1216 int dry_run)
1218 int i, ret = 1;
1219 struct string_list needs_pushing = STRING_LIST_INIT_DUP;
1221 if (!find_unpushed_submodules(r, commits,
1222 remote->name, &needs_pushing))
1223 return 1;
1226 * Verify that the remote and refspec can be propagated to all
1227 * submodules. This check can be skipped if the remote and refspec
1228 * won't be propagated due to the remote being unconfigured (e.g. a URL
1229 * instead of a remote name).
1231 if (remote->origin != REMOTE_UNCONFIGURED) {
1232 char *head;
1233 struct object_id head_oid;
1235 head = resolve_refdup("HEAD", 0, &head_oid, NULL);
1236 if (!head)
1237 die(_("Failed to resolve HEAD as a valid ref."));
1239 for (i = 0; i < needs_pushing.nr; i++)
1240 submodule_push_check(needs_pushing.items[i].string,
1241 head, remote, rs);
1242 free(head);
1245 /* Actually push the submodules */
1246 for (i = 0; i < needs_pushing.nr; i++) {
1247 const char *path = needs_pushing.items[i].string;
1248 fprintf(stderr, _("Pushing submodule '%s'\n"), path);
1249 if (!push_submodule(path, remote, rs,
1250 push_options, dry_run)) {
1251 fprintf(stderr, _("Unable to push submodule '%s'\n"), path);
1252 ret = 0;
1256 string_list_clear(&needs_pushing, 0);
1258 return ret;
1261 static int append_oid_to_array(const char *ref UNUSED,
1262 const struct object_id *oid,
1263 int flags UNUSED, void *data)
1265 struct oid_array *array = data;
1266 oid_array_append(array, oid);
1267 return 0;
1270 void check_for_new_submodule_commits(struct object_id *oid)
1272 if (!initialized_fetch_ref_tips) {
1273 for_each_ref(append_oid_to_array, &ref_tips_before_fetch);
1274 initialized_fetch_ref_tips = 1;
1277 oid_array_append(&ref_tips_after_fetch, oid);
1281 * Returns 1 if there is at least one submodule gitdir in
1282 * $GIT_DIR/modules and 0 otherwise. This follows
1283 * submodule_name_to_gitdir(), which looks for submodules in
1284 * $GIT_DIR/modules, not $GIT_COMMON_DIR.
1286 * A submodule can be moved to $GIT_DIR/modules manually by running "git
1287 * submodule absorbgitdirs", or it may be initialized there by "git
1288 * submodule update".
1290 static int repo_has_absorbed_submodules(struct repository *r)
1292 int ret;
1293 struct strbuf buf = STRBUF_INIT;
1295 strbuf_repo_git_path(&buf, r, "modules/");
1296 ret = file_exists(buf.buf) && !is_empty_dir(buf.buf);
1297 strbuf_release(&buf);
1298 return ret;
1301 static void calculate_changed_submodule_paths(struct repository *r,
1302 struct string_list *changed_submodule_names)
1304 struct strvec argv = STRVEC_INIT;
1305 struct string_list_item *name;
1307 /* No need to check if no submodules would be fetched */
1308 if (!submodule_from_path(r, NULL, NULL) &&
1309 !repo_has_absorbed_submodules(r))
1310 return;
1312 strvec_push(&argv, "--"); /* argv[0] program name */
1313 oid_array_for_each_unique(&ref_tips_after_fetch,
1314 append_oid_to_argv, &argv);
1315 strvec_push(&argv, "--not");
1316 oid_array_for_each_unique(&ref_tips_before_fetch,
1317 append_oid_to_argv, &argv);
1320 * Collect all submodules (whether checked out or not) for which new
1321 * commits have been recorded upstream in "changed_submodule_names".
1323 collect_changed_submodules(r, changed_submodule_names, &argv);
1325 for_each_string_list_item(name, changed_submodule_names) {
1326 struct changed_submodule_data *cs_data = name->util;
1327 const struct submodule *submodule;
1328 const char *path = NULL;
1330 submodule = submodule_from_name(r, null_oid(), name->string);
1331 if (submodule)
1332 path = submodule->path;
1333 else
1334 path = default_name_or_path(name->string);
1336 if (!path)
1337 continue;
1339 if (submodule_has_commits(r, path, null_oid(), &cs_data->new_commits)) {
1340 changed_submodule_data_clear(cs_data);
1341 *name->string = '\0';
1345 string_list_remove_empty_items(changed_submodule_names, 1);
1347 strvec_clear(&argv);
1348 oid_array_clear(&ref_tips_before_fetch);
1349 oid_array_clear(&ref_tips_after_fetch);
1350 initialized_fetch_ref_tips = 0;
1353 int submodule_touches_in_range(struct repository *r,
1354 struct object_id *excl_oid,
1355 struct object_id *incl_oid)
1357 struct string_list subs = STRING_LIST_INIT_DUP;
1358 struct strvec args = STRVEC_INIT;
1359 int ret;
1361 /* No need to check if there are no submodules configured */
1362 if (!submodule_from_path(r, NULL, NULL))
1363 return 0;
1365 strvec_push(&args, "--"); /* args[0] program name */
1366 strvec_push(&args, oid_to_hex(incl_oid));
1367 if (!is_null_oid(excl_oid)) {
1368 strvec_push(&args, "--not");
1369 strvec_push(&args, oid_to_hex(excl_oid));
1372 collect_changed_submodules(r, &subs, &args);
1373 ret = subs.nr;
1375 strvec_clear(&args);
1377 free_submodules_data(&subs);
1378 return ret;
1381 struct submodule_parallel_fetch {
1383 * The index of the last index entry processed by
1384 * get_fetch_task_from_index().
1386 int index_count;
1388 * The index of the last string_list entry processed by
1389 * get_fetch_task_from_changed().
1391 int changed_count;
1392 struct strvec args;
1393 struct repository *r;
1394 const char *prefix;
1395 int command_line_option;
1396 int default_option;
1397 int quiet;
1398 int result;
1401 * Names of submodules that have new commits. Generated by
1402 * walking the newly fetched superproject commits.
1404 struct string_list changed_submodule_names;
1406 * Names of submodules that have already been processed. Lets us
1407 * avoid fetching the same submodule more than once.
1409 struct string_list seen_submodule_names;
1411 /* Pending fetches by OIDs */
1412 struct fetch_task **oid_fetch_tasks;
1413 int oid_fetch_tasks_nr, oid_fetch_tasks_alloc;
1415 struct strbuf submodules_with_errors;
1417 #define SPF_INIT { \
1418 .args = STRVEC_INIT, \
1419 .changed_submodule_names = STRING_LIST_INIT_DUP, \
1420 .seen_submodule_names = STRING_LIST_INIT_DUP, \
1421 .submodules_with_errors = STRBUF_INIT, \
1424 static int get_fetch_recurse_config(const struct submodule *submodule,
1425 struct submodule_parallel_fetch *spf)
1427 if (spf->command_line_option != RECURSE_SUBMODULES_DEFAULT)
1428 return spf->command_line_option;
1430 if (submodule) {
1431 char *key;
1432 const char *value;
1434 int fetch_recurse = submodule->fetch_recurse;
1435 key = xstrfmt("submodule.%s.fetchRecurseSubmodules", submodule->name);
1436 if (!repo_config_get_string_tmp(spf->r, key, &value)) {
1437 fetch_recurse = parse_fetch_recurse_submodules_arg(key, value);
1439 free(key);
1441 if (fetch_recurse != RECURSE_SUBMODULES_NONE)
1442 /* local config overrules everything except commandline */
1443 return fetch_recurse;
1446 return spf->default_option;
1450 * Fetch in progress (if callback data) or
1451 * pending (if in oid_fetch_tasks in struct submodule_parallel_fetch)
1453 struct fetch_task {
1454 struct repository *repo;
1455 const struct submodule *sub;
1456 unsigned free_sub : 1; /* Do we need to free the submodule? */
1457 const char *default_argv; /* The default fetch mode. */
1458 struct strvec git_args; /* Args for the child git process. */
1460 struct oid_array *commits; /* Ensure these commits are fetched */
1464 * When a submodule is not defined in .gitmodules, we cannot access it
1465 * via the regular submodule-config. Create a fake submodule, which we can
1466 * work on.
1468 static const struct submodule *get_non_gitmodules_submodule(const char *path)
1470 struct submodule *ret = NULL;
1471 const char *name = default_name_or_path(path);
1473 if (!name)
1474 return NULL;
1476 ret = xmalloc(sizeof(*ret));
1477 memset(ret, 0, sizeof(*ret));
1478 ret->path = name;
1479 ret->name = name;
1481 return (const struct submodule *) ret;
1484 static void fetch_task_release(struct fetch_task *p)
1486 if (p->free_sub)
1487 free((void*)p->sub);
1488 p->free_sub = 0;
1489 p->sub = NULL;
1491 if (p->repo)
1492 repo_clear(p->repo);
1493 FREE_AND_NULL(p->repo);
1495 strvec_clear(&p->git_args);
1498 static struct repository *get_submodule_repo_for(struct repository *r,
1499 const char *path,
1500 const struct object_id *treeish_name)
1502 struct repository *ret = xmalloc(sizeof(*ret));
1504 if (repo_submodule_init(ret, r, path, treeish_name)) {
1505 free(ret);
1506 return NULL;
1509 return ret;
1512 static struct fetch_task *fetch_task_create(struct submodule_parallel_fetch *spf,
1513 const char *path,
1514 const struct object_id *treeish_name)
1516 struct fetch_task *task = xmalloc(sizeof(*task));
1517 memset(task, 0, sizeof(*task));
1519 if (validate_submodule_path(path) < 0)
1520 exit(128);
1522 task->sub = submodule_from_path(spf->r, treeish_name, path);
1524 if (!task->sub) {
1526 * No entry in .gitmodules? Technically not a submodule,
1527 * but historically we supported repositories that happen to be
1528 * in-place where a gitlink is. Keep supporting them.
1530 task->sub = get_non_gitmodules_submodule(path);
1531 if (!task->sub)
1532 goto cleanup;
1534 task->free_sub = 1;
1537 if (string_list_lookup(&spf->seen_submodule_names, task->sub->name))
1538 goto cleanup;
1540 switch (get_fetch_recurse_config(task->sub, spf))
1542 default:
1543 case RECURSE_SUBMODULES_DEFAULT:
1544 case RECURSE_SUBMODULES_ON_DEMAND:
1545 if (!task->sub ||
1546 !string_list_lookup(
1547 &spf->changed_submodule_names,
1548 task->sub->name))
1549 goto cleanup;
1550 task->default_argv = "on-demand";
1551 break;
1552 case RECURSE_SUBMODULES_ON:
1553 task->default_argv = "yes";
1554 break;
1555 case RECURSE_SUBMODULES_OFF:
1556 goto cleanup;
1559 task->repo = get_submodule_repo_for(spf->r, path, treeish_name);
1561 return task;
1563 cleanup:
1564 fetch_task_release(task);
1565 free(task);
1566 return NULL;
1569 static struct fetch_task *
1570 get_fetch_task_from_index(struct submodule_parallel_fetch *spf,
1571 struct strbuf *err)
1573 for (; spf->index_count < spf->r->index->cache_nr; spf->index_count++) {
1574 const struct cache_entry *ce =
1575 spf->r->index->cache[spf->index_count];
1576 struct fetch_task *task;
1578 if (!S_ISGITLINK(ce->ce_mode))
1579 continue;
1581 task = fetch_task_create(spf, ce->name, null_oid());
1582 if (!task)
1583 continue;
1585 if (task->repo) {
1586 if (!spf->quiet)
1587 strbuf_addf(err, _("Fetching submodule %s%s\n"),
1588 spf->prefix, ce->name);
1590 spf->index_count++;
1591 return task;
1592 } else {
1593 struct strbuf empty_submodule_path = STRBUF_INIT;
1595 fetch_task_release(task);
1596 free(task);
1599 * An empty directory is normal,
1600 * the submodule is not initialized
1602 strbuf_addf(&empty_submodule_path, "%s/%s/",
1603 spf->r->worktree,
1604 ce->name);
1605 if (S_ISGITLINK(ce->ce_mode) &&
1606 !is_empty_dir(empty_submodule_path.buf)) {
1607 spf->result = 1;
1608 strbuf_addf(err,
1609 _("Could not access submodule '%s'\n"),
1610 ce->name);
1612 strbuf_release(&empty_submodule_path);
1615 return NULL;
1618 static struct fetch_task *
1619 get_fetch_task_from_changed(struct submodule_parallel_fetch *spf,
1620 struct strbuf *err)
1622 for (; spf->changed_count < spf->changed_submodule_names.nr;
1623 spf->changed_count++) {
1624 struct string_list_item item =
1625 spf->changed_submodule_names.items[spf->changed_count];
1626 struct changed_submodule_data *cs_data = item.util;
1627 struct fetch_task *task;
1629 if (!is_tree_submodule_active(spf->r, cs_data->super_oid,cs_data->path))
1630 continue;
1632 task = fetch_task_create(spf, cs_data->path,
1633 cs_data->super_oid);
1634 if (!task)
1635 continue;
1637 if (!task->repo) {
1638 strbuf_addf(err, _("Could not access submodule '%s' at commit %s\n"),
1639 cs_data->path,
1640 find_unique_abbrev(cs_data->super_oid, DEFAULT_ABBREV));
1642 fetch_task_release(task);
1643 free(task);
1644 continue;
1647 if (!spf->quiet)
1648 strbuf_addf(err,
1649 _("Fetching submodule %s%s at commit %s\n"),
1650 spf->prefix, task->sub->path,
1651 find_unique_abbrev(cs_data->super_oid,
1652 DEFAULT_ABBREV));
1654 spf->changed_count++;
1656 * NEEDSWORK: Submodules set/unset a value for
1657 * core.worktree when they are populated/unpopulated by
1658 * "git checkout" (and similar commands, see
1659 * submodule_move_head() and
1660 * connect_work_tree_and_git_dir()), but if the
1661 * submodule is unpopulated in another way (e.g. "git
1662 * rm", "rm -r"), core.worktree will still be set even
1663 * though the directory doesn't exist, and the child
1664 * process will crash while trying to chdir into the
1665 * nonexistent directory.
1667 * In this case, we know that the submodule has no
1668 * working tree, so we can work around this by
1669 * setting "--work-tree=." (--bare does not work because
1670 * worktree settings take precedence over bare-ness).
1671 * However, this is not necessarily true in other cases,
1672 * so a generalized solution is still necessary.
1674 * Possible solutions:
1675 * - teach "git [add|rm]" to unset core.worktree and
1676 * discourage users from removing submodules without
1677 * using a Git command.
1678 * - teach submodule child processes to ignore stale
1679 * core.worktree values.
1681 strvec_push(&task->git_args, "--work-tree=.");
1682 return task;
1684 return NULL;
1687 static int get_next_submodule(struct child_process *cp, struct strbuf *err,
1688 void *data, void **task_cb)
1690 struct submodule_parallel_fetch *spf = data;
1691 struct fetch_task *task =
1692 get_fetch_task_from_index(spf, err);
1693 if (!task)
1694 task = get_fetch_task_from_changed(spf, err);
1696 if (task) {
1697 struct strbuf submodule_prefix = STRBUF_INIT;
1699 child_process_init(cp);
1700 cp->dir = task->repo->gitdir;
1701 prepare_submodule_repo_env_in_gitdir(&cp->env);
1702 cp->git_cmd = 1;
1703 strvec_init(&cp->args);
1704 if (task->git_args.nr)
1705 strvec_pushv(&cp->args, task->git_args.v);
1706 strvec_pushv(&cp->args, spf->args.v);
1707 strvec_push(&cp->args, task->default_argv);
1708 strvec_push(&cp->args, "--submodule-prefix");
1710 strbuf_addf(&submodule_prefix, "%s%s/",
1711 spf->prefix,
1712 task->sub->path);
1713 strvec_push(&cp->args, submodule_prefix.buf);
1714 *task_cb = task;
1716 strbuf_release(&submodule_prefix);
1717 string_list_insert(&spf->seen_submodule_names, task->sub->name);
1718 return 1;
1721 if (spf->oid_fetch_tasks_nr) {
1722 struct fetch_task *task =
1723 spf->oid_fetch_tasks[spf->oid_fetch_tasks_nr - 1];
1724 struct strbuf submodule_prefix = STRBUF_INIT;
1725 spf->oid_fetch_tasks_nr--;
1727 strbuf_addf(&submodule_prefix, "%s%s/",
1728 spf->prefix, task->sub->path);
1730 child_process_init(cp);
1731 prepare_submodule_repo_env_in_gitdir(&cp->env);
1732 cp->git_cmd = 1;
1733 cp->dir = task->repo->gitdir;
1735 strvec_init(&cp->args);
1736 strvec_pushv(&cp->args, spf->args.v);
1737 strvec_push(&cp->args, "on-demand");
1738 strvec_push(&cp->args, "--submodule-prefix");
1739 strvec_push(&cp->args, submodule_prefix.buf);
1741 /* NEEDSWORK: have get_default_remote from submodule--helper */
1742 strvec_push(&cp->args, "origin");
1743 oid_array_for_each_unique(task->commits,
1744 append_oid_to_argv, &cp->args);
1746 *task_cb = task;
1747 strbuf_release(&submodule_prefix);
1748 return 1;
1751 return 0;
1754 static int fetch_start_failure(struct strbuf *err,
1755 void *cb, void *task_cb)
1757 struct submodule_parallel_fetch *spf = cb;
1758 struct fetch_task *task = task_cb;
1760 spf->result = 1;
1762 fetch_task_release(task);
1763 return 0;
1766 static int commit_missing_in_sub(const struct object_id *oid, void *data)
1768 struct repository *subrepo = data;
1770 enum object_type type = oid_object_info(subrepo, oid, NULL);
1772 return type != OBJ_COMMIT;
1775 static int fetch_finish(int retvalue, struct strbuf *err,
1776 void *cb, void *task_cb)
1778 struct submodule_parallel_fetch *spf = cb;
1779 struct fetch_task *task = task_cb;
1781 struct string_list_item *it;
1782 struct changed_submodule_data *cs_data;
1784 if (!task || !task->sub)
1785 BUG("callback cookie bogus");
1787 if (retvalue) {
1789 * NEEDSWORK: This indicates that the overall fetch
1790 * failed, even though there may be a subsequent fetch
1791 * by commit hash that might work. It may be a good
1792 * idea to not indicate failure in this case, and only
1793 * indicate failure if the subsequent fetch fails.
1795 spf->result = 1;
1797 strbuf_addf(&spf->submodules_with_errors, "\t%s\n",
1798 task->sub->name);
1801 /* Is this the second time we process this submodule? */
1802 if (task->commits)
1803 goto out;
1805 it = string_list_lookup(&spf->changed_submodule_names, task->sub->name);
1806 if (!it)
1807 /* Could be an unchanged submodule, not contained in the list */
1808 goto out;
1810 cs_data = it->util;
1811 oid_array_filter(&cs_data->new_commits,
1812 commit_missing_in_sub,
1813 task->repo);
1815 /* Are there commits we want, but do not exist? */
1816 if (cs_data->new_commits.nr) {
1817 task->commits = &cs_data->new_commits;
1818 ALLOC_GROW(spf->oid_fetch_tasks,
1819 spf->oid_fetch_tasks_nr + 1,
1820 spf->oid_fetch_tasks_alloc);
1821 spf->oid_fetch_tasks[spf->oid_fetch_tasks_nr] = task;
1822 spf->oid_fetch_tasks_nr++;
1823 return 0;
1826 out:
1827 fetch_task_release(task);
1829 return 0;
1832 int fetch_submodules(struct repository *r,
1833 const struct strvec *options,
1834 const char *prefix, int command_line_option,
1835 int default_option,
1836 int quiet, int max_parallel_jobs)
1838 int i;
1839 struct submodule_parallel_fetch spf = SPF_INIT;
1840 const struct run_process_parallel_opts opts = {
1841 .tr2_category = "submodule",
1842 .tr2_label = "parallel/fetch",
1844 .processes = max_parallel_jobs,
1846 .get_next_task = get_next_submodule,
1847 .start_failure = fetch_start_failure,
1848 .task_finished = fetch_finish,
1849 .data = &spf,
1852 spf.r = r;
1853 spf.command_line_option = command_line_option;
1854 spf.default_option = default_option;
1855 spf.quiet = quiet;
1856 spf.prefix = prefix;
1858 if (!r->worktree)
1859 goto out;
1861 if (repo_read_index(r) < 0)
1862 die(_("index file corrupt"));
1864 strvec_push(&spf.args, "fetch");
1865 for (i = 0; i < options->nr; i++)
1866 strvec_push(&spf.args, options->v[i]);
1867 strvec_push(&spf.args, "--recurse-submodules-default");
1868 /* default value, "--submodule-prefix" and its value are added later */
1870 calculate_changed_submodule_paths(r, &spf.changed_submodule_names);
1871 string_list_sort(&spf.changed_submodule_names);
1872 run_processes_parallel(&opts);
1874 if (spf.submodules_with_errors.len > 0)
1875 fprintf(stderr, _("Errors during submodule fetch:\n%s"),
1876 spf.submodules_with_errors.buf);
1879 strvec_clear(&spf.args);
1880 out:
1881 free_submodules_data(&spf.changed_submodule_names);
1882 return spf.result;
1885 unsigned is_submodule_modified(const char *path, int ignore_untracked)
1887 struct child_process cp = CHILD_PROCESS_INIT;
1888 struct strbuf buf = STRBUF_INIT;
1889 FILE *fp;
1890 unsigned dirty_submodule = 0;
1891 const char *git_dir;
1892 int ignore_cp_exit_code = 0;
1894 if (validate_submodule_path(path) < 0)
1895 exit(128);
1897 strbuf_addf(&buf, "%s/.git", path);
1898 git_dir = read_gitfile(buf.buf);
1899 if (!git_dir)
1900 git_dir = buf.buf;
1901 if (!is_git_directory(git_dir)) {
1902 if (is_directory(git_dir))
1903 die(_("'%s' not recognized as a git repository"), git_dir);
1904 strbuf_release(&buf);
1905 /* The submodule is not checked out, so it is not modified */
1906 return 0;
1908 strbuf_reset(&buf);
1910 strvec_pushl(&cp.args, "status", "--porcelain=2", NULL);
1911 if (ignore_untracked)
1912 strvec_push(&cp.args, "-uno");
1914 prepare_submodule_repo_env(&cp.env);
1915 cp.git_cmd = 1;
1916 cp.no_stdin = 1;
1917 cp.out = -1;
1918 cp.dir = path;
1919 if (start_command(&cp))
1920 die(_("Could not run 'git status --porcelain=2' in submodule %s"), path);
1922 fp = xfdopen(cp.out, "r");
1923 while (strbuf_getwholeline(&buf, fp, '\n') != EOF) {
1924 /* regular untracked files */
1925 if (buf.buf[0] == '?')
1926 dirty_submodule |= DIRTY_SUBMODULE_UNTRACKED;
1928 if (buf.buf[0] == 'u' ||
1929 buf.buf[0] == '1' ||
1930 buf.buf[0] == '2') {
1931 /* T = line type, XY = status, SSSS = submodule state */
1932 if (buf.len < strlen("T XY SSSS"))
1933 BUG("invalid status --porcelain=2 line %s",
1934 buf.buf);
1936 if (buf.buf[5] == 'S' && buf.buf[8] == 'U')
1937 /* nested untracked file */
1938 dirty_submodule |= DIRTY_SUBMODULE_UNTRACKED;
1940 if (buf.buf[0] == 'u' ||
1941 buf.buf[0] == '2' ||
1942 memcmp(buf.buf + 5, "S..U", 4))
1943 /* other change */
1944 dirty_submodule |= DIRTY_SUBMODULE_MODIFIED;
1947 if ((dirty_submodule & DIRTY_SUBMODULE_MODIFIED) &&
1948 ((dirty_submodule & DIRTY_SUBMODULE_UNTRACKED) ||
1949 ignore_untracked)) {
1951 * We're not interested in any further information from
1952 * the child any more, neither output nor its exit code.
1954 ignore_cp_exit_code = 1;
1955 break;
1958 fclose(fp);
1960 if (finish_command(&cp) && !ignore_cp_exit_code)
1961 die(_("'git status --porcelain=2' failed in submodule %s"), path);
1963 strbuf_release(&buf);
1964 return dirty_submodule;
1967 int submodule_uses_gitfile(const char *path)
1969 struct child_process cp = CHILD_PROCESS_INIT;
1970 struct strbuf buf = STRBUF_INIT;
1971 const char *git_dir;
1973 if (validate_submodule_path(path) < 0)
1974 exit(128);
1976 strbuf_addf(&buf, "%s/.git", path);
1977 git_dir = read_gitfile(buf.buf);
1978 if (!git_dir) {
1979 strbuf_release(&buf);
1980 return 0;
1982 strbuf_release(&buf);
1984 /* Now test that all nested submodules use a gitfile too */
1985 strvec_pushl(&cp.args,
1986 "submodule", "foreach", "--quiet", "--recursive",
1987 "test -f .git", NULL);
1989 prepare_submodule_repo_env(&cp.env);
1990 cp.git_cmd = 1;
1991 cp.no_stdin = 1;
1992 cp.no_stderr = 1;
1993 cp.no_stdout = 1;
1994 cp.dir = path;
1995 if (run_command(&cp))
1996 return 0;
1998 return 1;
2002 * Check if it is a bad idea to remove a submodule, i.e. if we'd lose data
2003 * when doing so.
2005 * Return 1 if we'd lose data, return 0 if the removal is fine,
2006 * and negative values for errors.
2008 int bad_to_remove_submodule(const char *path, unsigned flags)
2010 ssize_t len;
2011 struct child_process cp = CHILD_PROCESS_INIT;
2012 struct strbuf buf = STRBUF_INIT;
2013 int ret = 0;
2015 if (validate_submodule_path(path) < 0)
2016 exit(128);
2018 if (!file_exists(path) || is_empty_dir(path))
2019 return 0;
2021 if (!submodule_uses_gitfile(path))
2022 return 1;
2024 strvec_pushl(&cp.args, "status", "--porcelain",
2025 "--ignore-submodules=none", NULL);
2027 if (flags & SUBMODULE_REMOVAL_IGNORE_UNTRACKED)
2028 strvec_push(&cp.args, "-uno");
2029 else
2030 strvec_push(&cp.args, "-uall");
2032 if (!(flags & SUBMODULE_REMOVAL_IGNORE_IGNORED_UNTRACKED))
2033 strvec_push(&cp.args, "--ignored");
2035 prepare_submodule_repo_env(&cp.env);
2036 cp.git_cmd = 1;
2037 cp.no_stdin = 1;
2038 cp.out = -1;
2039 cp.dir = path;
2040 if (start_command(&cp)) {
2041 if (flags & SUBMODULE_REMOVAL_DIE_ON_ERROR)
2042 die(_("could not start 'git status' in submodule '%s'"),
2043 path);
2044 ret = -1;
2045 goto out;
2048 len = strbuf_read(&buf, cp.out, 1024);
2049 if (len > 2)
2050 ret = 1;
2051 close(cp.out);
2053 if (finish_command(&cp)) {
2054 if (flags & SUBMODULE_REMOVAL_DIE_ON_ERROR)
2055 die(_("could not run 'git status' in submodule '%s'"),
2056 path);
2057 ret = -1;
2059 out:
2060 strbuf_release(&buf);
2061 return ret;
2064 void submodule_unset_core_worktree(const struct submodule *sub)
2066 struct strbuf config_path = STRBUF_INIT;
2068 if (validate_submodule_path(sub->path) < 0)
2069 exit(128);
2071 submodule_name_to_gitdir(&config_path, the_repository, sub->name);
2072 strbuf_addstr(&config_path, "/config");
2074 if (git_config_set_in_file_gently(config_path.buf, "core.worktree", NULL))
2075 warning(_("Could not unset core.worktree setting in submodule '%s'"),
2076 sub->path);
2078 strbuf_release(&config_path);
2081 static int submodule_has_dirty_index(const struct submodule *sub)
2083 struct child_process cp = CHILD_PROCESS_INIT;
2085 if (validate_submodule_path(sub->path) < 0)
2086 exit(128);
2088 prepare_submodule_repo_env(&cp.env);
2090 cp.git_cmd = 1;
2091 strvec_pushl(&cp.args, "diff-index", "--quiet",
2092 "--cached", "HEAD", NULL);
2093 cp.no_stdin = 1;
2094 cp.no_stdout = 1;
2095 cp.dir = sub->path;
2096 if (start_command(&cp))
2097 die(_("could not recurse into submodule '%s'"), sub->path);
2099 return finish_command(&cp);
2102 static void submodule_reset_index(const char *path, const char *super_prefix)
2104 struct child_process cp = CHILD_PROCESS_INIT;
2106 if (validate_submodule_path(path) < 0)
2107 exit(128);
2109 prepare_submodule_repo_env(&cp.env);
2111 cp.git_cmd = 1;
2112 cp.no_stdin = 1;
2113 cp.dir = path;
2115 /* TODO: determine if this might overwright untracked files */
2116 strvec_pushl(&cp.args, "read-tree", "-u", "--reset", NULL);
2117 strvec_pushf(&cp.args, "--super-prefix=%s%s/",
2118 (super_prefix ? super_prefix : ""), path);
2120 strvec_push(&cp.args, empty_tree_oid_hex());
2122 if (run_command(&cp))
2123 die(_("could not reset submodule index"));
2127 * Moves a submodule at a given path from a given head to another new head.
2128 * For edge cases (a submodule coming into existence or removing a submodule)
2129 * pass NULL for old or new respectively.
2131 int submodule_move_head(const char *path, const char *super_prefix,
2132 const char *old_head, const char *new_head,
2133 unsigned flags)
2135 int ret = 0;
2136 struct child_process cp = CHILD_PROCESS_INIT;
2137 const struct submodule *sub;
2138 int *error_code_ptr, error_code;
2140 if (!is_submodule_active(the_repository, path))
2141 return 0;
2143 if (flags & SUBMODULE_MOVE_HEAD_FORCE)
2145 * Pass non NULL pointer to is_submodule_populated_gently
2146 * to prevent die()-ing. We'll use connect_work_tree_and_git_dir
2147 * to fixup the submodule in the force case later.
2149 error_code_ptr = &error_code;
2150 else
2151 error_code_ptr = NULL;
2153 if (old_head && !is_submodule_populated_gently(path, error_code_ptr))
2154 return 0;
2156 sub = submodule_from_path(the_repository, null_oid(), path);
2158 if (!sub)
2159 BUG("could not get submodule information for '%s'", path);
2161 if (old_head && !(flags & SUBMODULE_MOVE_HEAD_FORCE)) {
2162 /* Check if the submodule has a dirty index. */
2163 if (submodule_has_dirty_index(sub))
2164 return error(_("submodule '%s' has dirty index"), path);
2167 if (!(flags & SUBMODULE_MOVE_HEAD_DRY_RUN)) {
2168 if (old_head) {
2169 if (!submodule_uses_gitfile(path))
2170 absorb_git_dir_into_superproject(path,
2171 super_prefix);
2172 else {
2173 char *dotgit = xstrfmt("%s/.git", path);
2174 char *git_dir = xstrdup(read_gitfile(dotgit));
2176 free(dotgit);
2177 if (validate_submodule_git_dir(git_dir,
2178 sub->name) < 0)
2179 die(_("refusing to create/use '%s' in "
2180 "another submodule's git dir"),
2181 git_dir);
2182 free(git_dir);
2184 } else {
2185 struct strbuf gitdir = STRBUF_INIT;
2186 submodule_name_to_gitdir(&gitdir, the_repository,
2187 sub->name);
2188 if (validate_submodule_git_dir(gitdir.buf,
2189 sub->name) < 0)
2190 die(_("refusing to create/use '%s' in another "
2191 "submodule's git dir"),
2192 gitdir.buf);
2193 connect_work_tree_and_git_dir(path, gitdir.buf, 0);
2194 strbuf_release(&gitdir);
2196 /* make sure the index is clean as well */
2197 submodule_reset_index(path, super_prefix);
2200 if (old_head && (flags & SUBMODULE_MOVE_HEAD_FORCE)) {
2201 struct strbuf gitdir = STRBUF_INIT;
2202 submodule_name_to_gitdir(&gitdir, the_repository,
2203 sub->name);
2204 connect_work_tree_and_git_dir(path, gitdir.buf, 1);
2205 strbuf_release(&gitdir);
2209 prepare_submodule_repo_env(&cp.env);
2211 cp.git_cmd = 1;
2212 cp.no_stdin = 1;
2213 cp.dir = path;
2215 strvec_pushl(&cp.args, "read-tree", "--recurse-submodules", NULL);
2216 strvec_pushf(&cp.args, "--super-prefix=%s%s/",
2217 (super_prefix ? super_prefix : ""), path);
2219 if (flags & SUBMODULE_MOVE_HEAD_DRY_RUN)
2220 strvec_push(&cp.args, "-n");
2221 else
2222 strvec_push(&cp.args, "-u");
2224 if (flags & SUBMODULE_MOVE_HEAD_FORCE)
2225 strvec_push(&cp.args, "--reset");
2226 else
2227 strvec_push(&cp.args, "-m");
2229 if (!(flags & SUBMODULE_MOVE_HEAD_FORCE))
2230 strvec_push(&cp.args, old_head ? old_head : empty_tree_oid_hex());
2232 strvec_push(&cp.args, new_head ? new_head : empty_tree_oid_hex());
2234 if (run_command(&cp)) {
2235 ret = error(_("Submodule '%s' could not be updated."), path);
2236 goto out;
2239 if (!(flags & SUBMODULE_MOVE_HEAD_DRY_RUN)) {
2240 if (new_head) {
2241 child_process_init(&cp);
2242 /* also set the HEAD accordingly */
2243 cp.git_cmd = 1;
2244 cp.no_stdin = 1;
2245 cp.dir = path;
2247 prepare_submodule_repo_env(&cp.env);
2248 strvec_pushl(&cp.args, "update-ref", "HEAD",
2249 "--no-deref", new_head, NULL);
2251 if (run_command(&cp)) {
2252 ret = -1;
2253 goto out;
2255 } else {
2256 struct strbuf sb = STRBUF_INIT;
2258 strbuf_addf(&sb, "%s/.git", path);
2259 unlink_or_warn(sb.buf);
2260 strbuf_release(&sb);
2262 if (is_empty_dir(path))
2263 rmdir_or_warn(path);
2265 submodule_unset_core_worktree(sub);
2268 out:
2269 return ret;
2272 int validate_submodule_git_dir(char *git_dir, const char *submodule_name)
2274 size_t len = strlen(git_dir), suffix_len = strlen(submodule_name);
2275 char *p;
2276 int ret = 0;
2278 if (len <= suffix_len || (p = git_dir + len - suffix_len)[-1] != '/' ||
2279 strcmp(p, submodule_name))
2280 BUG("submodule name '%s' not a suffix of git dir '%s'",
2281 submodule_name, git_dir);
2284 * We prevent the contents of sibling submodules' git directories to
2285 * clash.
2287 * Example: having a submodule named `hippo` and another one named
2288 * `hippo/hooks` would result in the git directories
2289 * `.git/modules/hippo/` and `.git/modules/hippo/hooks/`, respectively,
2290 * but the latter directory is already designated to contain the hooks
2291 * of the former.
2293 for (; *p; p++) {
2294 if (is_dir_sep(*p)) {
2295 char c = *p;
2297 *p = '\0';
2298 if (is_git_directory(git_dir))
2299 ret = -1;
2300 *p = c;
2302 if (ret < 0)
2303 return error(_("submodule git dir '%s' is "
2304 "inside git dir '%.*s'"),
2305 git_dir,
2306 (int)(p - git_dir), git_dir);
2310 return 0;
2313 int validate_submodule_path(const char *path)
2315 char *p = xstrdup(path);
2316 struct stat st;
2317 int i, ret = 0;
2318 char sep;
2320 for (i = 0; !ret && p[i]; i++) {
2321 if (!is_dir_sep(p[i]))
2322 continue;
2324 sep = p[i];
2325 p[i] = '\0';
2326 /* allow missing components, but no symlinks */
2327 ret = lstat(p, &st) || !S_ISLNK(st.st_mode) ? 0 : -1;
2328 p[i] = sep;
2329 if (ret)
2330 error(_("expected '%.*s' in submodule path '%s' not to "
2331 "be a symbolic link"), i, p, p);
2333 if (!lstat(p, &st) && S_ISLNK(st.st_mode))
2334 ret = error(_("expected submodule path '%s' not to be a "
2335 "symbolic link"), p);
2336 free(p);
2337 return ret;
2342 * Embeds a single submodules git directory into the superprojects git dir,
2343 * non recursively.
2345 static void relocate_single_git_dir_into_superproject(const char *path,
2346 const char *super_prefix)
2348 char *old_git_dir = NULL, *real_old_git_dir = NULL, *real_new_git_dir = NULL;
2349 struct strbuf new_gitdir = STRBUF_INIT;
2350 const struct submodule *sub;
2352 if (validate_submodule_path(path) < 0)
2353 exit(128);
2355 if (submodule_uses_worktrees(path))
2356 die(_("relocate_gitdir for submodule '%s' with "
2357 "more than one worktree not supported"), path);
2359 old_git_dir = xstrfmt("%s/.git", path);
2360 if (read_gitfile(old_git_dir))
2361 /* If it is an actual gitfile, it doesn't need migration. */
2362 return;
2364 real_old_git_dir = real_pathdup(old_git_dir, 1);
2366 sub = submodule_from_path(the_repository, null_oid(), path);
2367 if (!sub)
2368 die(_("could not lookup name for submodule '%s'"), path);
2370 submodule_name_to_gitdir(&new_gitdir, the_repository, sub->name);
2371 if (validate_submodule_git_dir(new_gitdir.buf, sub->name) < 0)
2372 die(_("refusing to move '%s' into an existing git dir"),
2373 real_old_git_dir);
2374 if (safe_create_leading_directories_const(new_gitdir.buf) < 0)
2375 die(_("could not create directory '%s'"), new_gitdir.buf);
2376 real_new_git_dir = real_pathdup(new_gitdir.buf, 1);
2378 fprintf(stderr, _("Migrating git directory of '%s%s' from\n'%s' to\n'%s'\n"),
2379 super_prefix ? super_prefix : "", path,
2380 real_old_git_dir, real_new_git_dir);
2382 relocate_gitdir(path, real_old_git_dir, real_new_git_dir);
2384 free(old_git_dir);
2385 free(real_old_git_dir);
2386 free(real_new_git_dir);
2387 strbuf_release(&new_gitdir);
2390 static void absorb_git_dir_into_superproject_recurse(const char *path,
2391 const char *super_prefix)
2394 struct child_process cp = CHILD_PROCESS_INIT;
2396 if (validate_submodule_path(path) < 0)
2397 exit(128);
2399 cp.dir = path;
2400 cp.git_cmd = 1;
2401 cp.no_stdin = 1;
2402 strvec_pushl(&cp.args, "submodule--helper",
2403 "absorbgitdirs", NULL);
2404 strvec_pushf(&cp.args, "--super-prefix=%s%s/", super_prefix ?
2405 super_prefix : "", path);
2407 prepare_submodule_repo_env(&cp.env);
2408 if (run_command(&cp))
2409 die(_("could not recurse into submodule '%s'"), path);
2413 * Migrate the git directory of the submodule given by path from
2414 * having its git directory within the working tree to the git dir nested
2415 * in its superprojects git dir under modules/.
2417 void absorb_git_dir_into_superproject(const char *path,
2418 const char *super_prefix)
2420 int err_code;
2421 const char *sub_git_dir;
2422 struct strbuf gitdir = STRBUF_INIT;
2424 if (validate_submodule_path(path) < 0)
2425 exit(128);
2427 strbuf_addf(&gitdir, "%s/.git", path);
2428 sub_git_dir = resolve_gitdir_gently(gitdir.buf, &err_code);
2430 /* Not populated? */
2431 if (!sub_git_dir) {
2432 const struct submodule *sub;
2433 struct strbuf sub_gitdir = STRBUF_INIT;
2435 if (err_code == READ_GITFILE_ERR_STAT_FAILED) {
2436 /* unpopulated as expected */
2437 strbuf_release(&gitdir);
2438 return;
2441 if (err_code != READ_GITFILE_ERR_NOT_A_REPO)
2442 /* We don't know what broke here. */
2443 read_gitfile_error_die(err_code, path, NULL);
2446 * Maybe populated, but no git directory was found?
2447 * This can happen if the superproject is a submodule
2448 * itself and was just absorbed. The absorption of the
2449 * superproject did not rewrite the git file links yet,
2450 * fix it now.
2452 sub = submodule_from_path(the_repository, null_oid(), path);
2453 if (!sub)
2454 die(_("could not lookup name for submodule '%s'"), path);
2455 submodule_name_to_gitdir(&sub_gitdir, the_repository, sub->name);
2456 connect_work_tree_and_git_dir(path, sub_gitdir.buf, 0);
2457 strbuf_release(&sub_gitdir);
2458 } else {
2459 /* Is it already absorbed into the superprojects git dir? */
2460 char *real_sub_git_dir = real_pathdup(sub_git_dir, 1);
2461 char *real_common_git_dir = real_pathdup(get_git_common_dir(), 1);
2463 if (!starts_with(real_sub_git_dir, real_common_git_dir))
2464 relocate_single_git_dir_into_superproject(path, super_prefix);
2466 free(real_sub_git_dir);
2467 free(real_common_git_dir);
2469 strbuf_release(&gitdir);
2471 absorb_git_dir_into_superproject_recurse(path, super_prefix);
2474 int get_superproject_working_tree(struct strbuf *buf)
2476 struct child_process cp = CHILD_PROCESS_INIT;
2477 struct strbuf sb = STRBUF_INIT;
2478 struct strbuf one_up = STRBUF_INIT;
2479 char *cwd = xgetcwd();
2480 int ret = 0;
2481 const char *subpath;
2482 int code;
2483 ssize_t len;
2485 if (!is_inside_work_tree())
2487 * FIXME:
2488 * We might have a superproject, but it is harder
2489 * to determine.
2491 return 0;
2493 if (!strbuf_realpath(&one_up, "../", 0))
2494 return 0;
2496 subpath = relative_path(cwd, one_up.buf, &sb);
2497 strbuf_release(&one_up);
2499 prepare_submodule_repo_env(&cp.env);
2500 strvec_pop(&cp.env);
2502 strvec_pushl(&cp.args, "--literal-pathspecs", "-C", "..",
2503 "ls-files", "-z", "--stage", "--full-name", "--",
2504 subpath, NULL);
2505 strbuf_reset(&sb);
2507 cp.no_stdin = 1;
2508 cp.no_stderr = 1;
2509 cp.out = -1;
2510 cp.git_cmd = 1;
2512 if (start_command(&cp))
2513 die(_("could not start ls-files in .."));
2515 len = strbuf_read(&sb, cp.out, PATH_MAX);
2516 close(cp.out);
2518 if (starts_with(sb.buf, "160000")) {
2519 int super_sub_len;
2520 int cwd_len = strlen(cwd);
2521 char *super_sub, *super_wt;
2524 * There is a superproject having this repo as a submodule.
2525 * The format is <mode> SP <hash> SP <stage> TAB <full name> \0,
2526 * We're only interested in the name after the tab.
2528 super_sub = strchr(sb.buf, '\t') + 1;
2529 super_sub_len = strlen(super_sub);
2531 if (super_sub_len > cwd_len ||
2532 strcmp(&cwd[cwd_len - super_sub_len], super_sub))
2533 BUG("returned path string doesn't match cwd?");
2535 super_wt = xstrdup(cwd);
2536 super_wt[cwd_len - super_sub_len] = '\0';
2538 strbuf_realpath(buf, super_wt, 1);
2539 ret = 1;
2540 free(super_wt);
2542 free(cwd);
2543 strbuf_release(&sb);
2545 code = finish_command(&cp);
2547 if (code == 128)
2548 /* '../' is not a git repository */
2549 return 0;
2550 if (code == 0 && len == 0)
2551 /* There is an unrelated git repository at '../' */
2552 return 0;
2553 if (code)
2554 die(_("ls-tree returned unexpected return code %d"), code);
2556 return ret;
2560 * Put the gitdir for a submodule (given relative to the main
2561 * repository worktree) into `buf`, or return -1 on error.
2563 int submodule_to_gitdir(struct strbuf *buf, const char *submodule)
2565 const struct submodule *sub;
2566 const char *git_dir;
2567 int ret = 0;
2569 if (validate_submodule_path(submodule) < 0)
2570 exit(128);
2572 strbuf_reset(buf);
2573 strbuf_addstr(buf, submodule);
2574 strbuf_complete(buf, '/');
2575 strbuf_addstr(buf, ".git");
2577 git_dir = read_gitfile(buf->buf);
2578 if (git_dir) {
2579 strbuf_reset(buf);
2580 strbuf_addstr(buf, git_dir);
2582 if (!is_git_directory(buf->buf)) {
2583 sub = submodule_from_path(the_repository, null_oid(),
2584 submodule);
2585 if (!sub) {
2586 ret = -1;
2587 goto cleanup;
2589 strbuf_reset(buf);
2590 submodule_name_to_gitdir(buf, the_repository, sub->name);
2593 cleanup:
2594 return ret;
2597 void submodule_name_to_gitdir(struct strbuf *buf, struct repository *r,
2598 const char *submodule_name)
2601 * NEEDSWORK: The current way of mapping a submodule's name to
2602 * its location in .git/modules/ has problems with some naming
2603 * schemes. For example, if a submodule is named "foo" and
2604 * another is named "foo/bar" (whether present in the same
2605 * superproject commit or not - the problem will arise if both
2606 * superproject commits have been checked out at any point in
2607 * time), or if two submodule names only have different cases in
2608 * a case-insensitive filesystem.
2610 * There are several solutions, including encoding the path in
2611 * some way, introducing a submodule.<name>.gitdir config in
2612 * .git/config (not .gitmodules) that allows overriding what the
2613 * gitdir of a submodule would be (and teach Git, upon noticing
2614 * a clash, to automatically determine a non-clashing name and
2615 * to write such a config), or introducing a
2616 * submodule.<name>.gitdir config in .gitmodules that repo
2617 * administrators can explicitly set. Nothing has been decided,
2618 * so for now, just append the name at the end of the path.
2620 strbuf_repo_git_path(buf, r, "modules/");
2621 strbuf_addstr(buf, submodule_name);