cocci: remove 'unused.cocci'
[git.git] / submodule.c
blob94644fac0a39f1bad2af719a01f99b1a551e0e8d
1 #include "cache.h"
2 #include "abspath.h"
3 #include "alloc.h"
4 #include "repository.h"
5 #include "config.h"
6 #include "submodule-config.h"
7 #include "submodule.h"
8 #include "dir.h"
9 #include "diff.h"
10 #include "commit.h"
11 #include "environment.h"
12 #include "gettext.h"
13 #include "hex.h"
14 #include "revision.h"
15 #include "run-command.h"
16 #include "diffcore.h"
17 #include "refs.h"
18 #include "string-list.h"
19 #include "oid-array.h"
20 #include "strvec.h"
21 #include "blob.h"
22 #include "thread-utils.h"
23 #include "quote.h"
24 #include "remote.h"
25 #include "worktree.h"
26 #include "parse-options.h"
27 #include "object-store.h"
28 #include "commit-reach.h"
29 #include "setup.h"
30 #include "shallow.h"
32 static int config_update_recurse_submodules = RECURSE_SUBMODULES_OFF;
33 static int initialized_fetch_ref_tips;
34 static struct oid_array ref_tips_before_fetch;
35 static struct oid_array ref_tips_after_fetch;
38 * Check if the .gitmodules file is unmerged. Parsing of the .gitmodules file
39 * will be disabled because we can't guess what might be configured in
40 * .gitmodules unless the user resolves the conflict.
42 int is_gitmodules_unmerged(struct index_state *istate)
44 int pos = index_name_pos(istate, GITMODULES_FILE, strlen(GITMODULES_FILE));
45 if (pos < 0) { /* .gitmodules not found or isn't merged */
46 pos = -1 - pos;
47 if (istate->cache_nr > pos) { /* there is a .gitmodules */
48 const struct cache_entry *ce = istate->cache[pos];
49 if (ce_namelen(ce) == strlen(GITMODULES_FILE) &&
50 !strcmp(ce->name, GITMODULES_FILE))
51 return 1;
55 return 0;
59 * Check if the .gitmodules file is safe to write.
61 * Writing to the .gitmodules file requires that the file exists in the
62 * working tree or, if it doesn't, that a brand new .gitmodules file is going
63 * to be created (i.e. it's neither in the index nor in the current branch).
65 * It is not safe to write to .gitmodules if it's not in the working tree but
66 * it is in the index or in the current branch, because writing new values
67 * (and staging them) would blindly overwrite ALL the old content.
69 int is_writing_gitmodules_ok(void)
71 struct object_id oid;
72 return file_exists(GITMODULES_FILE) ||
73 (repo_get_oid(the_repository, GITMODULES_INDEX, &oid) < 0 && repo_get_oid(the_repository, GITMODULES_HEAD, &oid) < 0);
77 * Check if the .gitmodules file has unstaged modifications. This must be
78 * checked before allowing modifications to the .gitmodules file with the
79 * intention to stage them later, because when continuing we would stage the
80 * modifications the user didn't stage herself too. That might change in a
81 * future version when we learn to stage the changes we do ourselves without
82 * staging any previous modifications.
84 int is_staging_gitmodules_ok(struct index_state *istate)
86 int pos = index_name_pos(istate, GITMODULES_FILE, strlen(GITMODULES_FILE));
88 if ((pos >= 0) && (pos < istate->cache_nr)) {
89 struct stat st;
90 if (lstat(GITMODULES_FILE, &st) == 0 &&
91 ie_modified(istate, istate->cache[pos], &st, 0) & DATA_CHANGED)
92 return 0;
95 return 1;
98 static int for_each_remote_ref_submodule(const char *submodule,
99 each_ref_fn fn, void *cb_data)
101 return refs_for_each_remote_ref(get_submodule_ref_store(submodule),
102 fn, cb_data);
106 * Try to update the "path" entry in the "submodule.<name>" section of the
107 * .gitmodules file. Return 0 only if a .gitmodules file was found, a section
108 * with the correct path=<oldpath> setting was found and we could update it.
110 int update_path_in_gitmodules(const char *oldpath, const char *newpath)
112 struct strbuf entry = STRBUF_INIT;
113 const struct submodule *submodule;
114 int ret;
116 if (!file_exists(GITMODULES_FILE)) /* Do nothing without .gitmodules */
117 return -1;
119 if (is_gitmodules_unmerged(the_repository->index))
120 die(_("Cannot change unmerged .gitmodules, resolve merge conflicts first"));
122 submodule = submodule_from_path(the_repository, null_oid(), oldpath);
123 if (!submodule || !submodule->name) {
124 warning(_("Could not find section in .gitmodules where path=%s"), oldpath);
125 return -1;
127 strbuf_addstr(&entry, "submodule.");
128 strbuf_addstr(&entry, submodule->name);
129 strbuf_addstr(&entry, ".path");
130 ret = config_set_in_gitmodules_file_gently(entry.buf, newpath);
131 strbuf_release(&entry);
132 return ret;
136 * Try to remove the "submodule.<name>" section from .gitmodules where the given
137 * path is configured. Return 0 only if a .gitmodules file was found, a section
138 * with the correct path=<path> setting was found and we could remove it.
140 int remove_path_from_gitmodules(const char *path)
142 struct strbuf sect = STRBUF_INIT;
143 const struct submodule *submodule;
145 if (!file_exists(GITMODULES_FILE)) /* Do nothing without .gitmodules */
146 return -1;
148 if (is_gitmodules_unmerged(the_repository->index))
149 die(_("Cannot change unmerged .gitmodules, resolve merge conflicts first"));
151 submodule = submodule_from_path(the_repository, null_oid(), path);
152 if (!submodule || !submodule->name) {
153 warning(_("Could not find section in .gitmodules where path=%s"), path);
154 return -1;
156 strbuf_addstr(&sect, "submodule.");
157 strbuf_addstr(&sect, submodule->name);
158 if (git_config_rename_section_in_file(GITMODULES_FILE, sect.buf, NULL) < 0) {
159 /* Maybe the user already did that, don't error out here */
160 warning(_("Could not remove .gitmodules entry for %s"), path);
161 strbuf_release(&sect);
162 return -1;
164 strbuf_release(&sect);
165 return 0;
168 void stage_updated_gitmodules(struct index_state *istate)
170 if (add_file_to_index(istate, GITMODULES_FILE, 0))
171 die(_("staging updated .gitmodules failed"));
174 static struct string_list added_submodule_odb_paths = STRING_LIST_INIT_NODUP;
176 void add_submodule_odb_by_path(const char *path)
178 string_list_insert(&added_submodule_odb_paths, xstrdup(path));
181 int register_all_submodule_odb_as_alternates(void)
183 int i;
184 int ret = added_submodule_odb_paths.nr;
186 for (i = 0; i < added_submodule_odb_paths.nr; i++)
187 add_to_alternates_memory(added_submodule_odb_paths.items[i].string);
188 if (ret) {
189 string_list_clear(&added_submodule_odb_paths, 0);
190 trace2_data_intmax("submodule", the_repository,
191 "register_all_submodule_odb_as_alternates/registered", ret);
192 if (git_env_bool("GIT_TEST_FATAL_REGISTER_SUBMODULE_ODB", 0))
193 BUG("register_all_submodule_odb_as_alternates() called");
195 return ret;
198 void set_diffopt_flags_from_submodule_config(struct diff_options *diffopt,
199 const char *path)
201 const struct submodule *submodule = submodule_from_path(the_repository,
202 null_oid(),
203 path);
204 if (submodule) {
205 const char *ignore;
206 char *key;
208 key = xstrfmt("submodule.%s.ignore", submodule->name);
209 if (repo_config_get_string_tmp(the_repository, key, &ignore))
210 ignore = submodule->ignore;
211 free(key);
213 if (ignore)
214 handle_ignore_submodules_arg(diffopt, ignore);
215 else if (is_gitmodules_unmerged(the_repository->index))
216 diffopt->flags.ignore_submodules = 1;
220 /* Cheap function that only determines if we're interested in submodules at all */
221 int git_default_submodule_config(const char *var, const char *value,
222 void *cb UNUSED)
224 if (!strcmp(var, "submodule.recurse")) {
225 int v = git_config_bool(var, value) ?
226 RECURSE_SUBMODULES_ON : RECURSE_SUBMODULES_OFF;
227 config_update_recurse_submodules = v;
229 return 0;
232 int option_parse_recurse_submodules_worktree_updater(const struct option *opt,
233 const char *arg, int unset)
235 if (unset) {
236 config_update_recurse_submodules = RECURSE_SUBMODULES_OFF;
237 return 0;
239 if (arg)
240 config_update_recurse_submodules =
241 parse_update_recurse_submodules_arg(opt->long_name,
242 arg);
243 else
244 config_update_recurse_submodules = RECURSE_SUBMODULES_ON;
246 return 0;
250 * Determine if a submodule has been initialized at a given 'path'
253 * NEEDSWORK: Emit a warning if submodule.active exists, but is valueless,
254 * ie, the config looks like: "[submodule] active\n".
255 * Since that is an invalid pathspec, we should inform the user.
257 int is_tree_submodule_active(struct repository *repo,
258 const struct object_id *treeish_name,
259 const char *path)
261 int ret = 0;
262 char *key = NULL;
263 char *value = NULL;
264 const struct string_list *sl;
265 const struct submodule *module;
267 module = submodule_from_path(repo, treeish_name, path);
269 /* early return if there isn't a path->module mapping */
270 if (!module)
271 return 0;
273 /* submodule.<name>.active is set */
274 key = xstrfmt("submodule.%s.active", module->name);
275 if (!repo_config_get_bool(repo, key, &ret)) {
276 free(key);
277 return ret;
279 free(key);
281 /* submodule.active is set */
282 if (!repo_config_get_string_multi(repo, "submodule.active", &sl)) {
283 struct pathspec ps;
284 struct strvec args = STRVEC_INIT;
285 const struct string_list_item *item;
287 for_each_string_list_item(item, sl) {
288 strvec_push(&args, item->string);
291 parse_pathspec(&ps, 0, 0, NULL, args.v);
292 ret = match_pathspec(repo->index, &ps, path, strlen(path), 0, NULL, 1);
294 strvec_clear(&args);
295 clear_pathspec(&ps);
296 return ret;
299 /* fallback to checking if the URL is set */
300 key = xstrfmt("submodule.%s.url", module->name);
301 ret = !repo_config_get_string(repo, key, &value);
303 free(value);
304 free(key);
305 return ret;
308 int is_submodule_active(struct repository *repo, const char *path)
310 return is_tree_submodule_active(repo, null_oid(), path);
313 int is_submodule_populated_gently(const char *path, int *return_error_code)
315 int ret = 0;
316 char *gitdir = xstrfmt("%s/.git", path);
318 if (resolve_gitdir_gently(gitdir, return_error_code))
319 ret = 1;
321 free(gitdir);
322 return ret;
326 * Dies if the provided 'prefix' corresponds to an unpopulated submodule
328 void die_in_unpopulated_submodule(struct index_state *istate,
329 const char *prefix)
331 int i, prefixlen;
333 if (!prefix)
334 return;
336 prefixlen = strlen(prefix);
338 for (i = 0; i < istate->cache_nr; i++) {
339 struct cache_entry *ce = istate->cache[i];
340 int ce_len = ce_namelen(ce);
342 if (!S_ISGITLINK(ce->ce_mode))
343 continue;
344 if (prefixlen <= ce_len)
345 continue;
346 if (strncmp(ce->name, prefix, ce_len))
347 continue;
348 if (prefix[ce_len] != '/')
349 continue;
351 die(_("in unpopulated submodule '%s'"), ce->name);
356 * Dies if any paths in the provided pathspec descends into a submodule
358 void die_path_inside_submodule(struct index_state *istate,
359 const struct pathspec *ps)
361 int i, j;
363 for (i = 0; i < istate->cache_nr; i++) {
364 struct cache_entry *ce = istate->cache[i];
365 int ce_len = ce_namelen(ce);
367 if (!S_ISGITLINK(ce->ce_mode))
368 continue;
370 for (j = 0; j < ps->nr ; j++) {
371 const struct pathspec_item *item = &ps->items[j];
373 if (item->len <= ce_len)
374 continue;
375 if (item->match[ce_len] != '/')
376 continue;
377 if (strncmp(ce->name, item->match, ce_len))
378 continue;
379 if (item->len == ce_len + 1)
380 continue;
382 die(_("Pathspec '%s' is in submodule '%.*s'"),
383 item->original, ce_len, ce->name);
388 enum submodule_update_type parse_submodule_update_type(const char *value)
390 if (!strcmp(value, "none"))
391 return SM_UPDATE_NONE;
392 else if (!strcmp(value, "checkout"))
393 return SM_UPDATE_CHECKOUT;
394 else if (!strcmp(value, "rebase"))
395 return SM_UPDATE_REBASE;
396 else if (!strcmp(value, "merge"))
397 return SM_UPDATE_MERGE;
398 else if (*value == '!')
399 return SM_UPDATE_COMMAND;
400 else
401 return SM_UPDATE_UNSPECIFIED;
404 int parse_submodule_update_strategy(const char *value,
405 struct submodule_update_strategy *dst)
407 enum submodule_update_type type;
409 free((void*)dst->command);
410 dst->command = NULL;
412 type = parse_submodule_update_type(value);
413 if (type == SM_UPDATE_UNSPECIFIED)
414 return -1;
416 dst->type = type;
417 if (type == SM_UPDATE_COMMAND)
418 dst->command = xstrdup(value + 1);
420 return 0;
423 const char *submodule_update_type_to_string(enum submodule_update_type type)
425 switch (type) {
426 case SM_UPDATE_CHECKOUT:
427 return "checkout";
428 case SM_UPDATE_MERGE:
429 return "merge";
430 case SM_UPDATE_REBASE:
431 return "rebase";
432 case SM_UPDATE_NONE:
433 return "none";
434 case SM_UPDATE_UNSPECIFIED:
435 case SM_UPDATE_COMMAND:
436 BUG("init_submodule() should handle type %d", type);
437 default:
438 BUG("unexpected update strategy type: %d", type);
442 void handle_ignore_submodules_arg(struct diff_options *diffopt,
443 const char *arg)
445 diffopt->flags.ignore_submodule_set = 1;
446 diffopt->flags.ignore_submodules = 0;
447 diffopt->flags.ignore_untracked_in_submodules = 0;
448 diffopt->flags.ignore_dirty_submodules = 0;
450 if (!strcmp(arg, "all"))
451 diffopt->flags.ignore_submodules = 1;
452 else if (!strcmp(arg, "untracked"))
453 diffopt->flags.ignore_untracked_in_submodules = 1;
454 else if (!strcmp(arg, "dirty"))
455 diffopt->flags.ignore_dirty_submodules = 1;
456 else if (strcmp(arg, "none"))
457 die(_("bad --ignore-submodules argument: %s"), arg);
459 * Please update _git_status() in git-completion.bash when you
460 * add new options
464 static int prepare_submodule_diff_summary(struct repository *r, struct rev_info *rev,
465 const char *path,
466 struct commit *left, struct commit *right,
467 struct commit_list *merge_bases)
469 struct commit_list *list;
471 repo_init_revisions(r, rev, NULL);
472 setup_revisions(0, NULL, rev, NULL);
473 rev->left_right = 1;
474 rev->first_parent_only = 1;
475 left->object.flags |= SYMMETRIC_LEFT;
476 add_pending_object(rev, &left->object, path);
477 add_pending_object(rev, &right->object, path);
478 for (list = merge_bases; list; list = list->next) {
479 list->item->object.flags |= UNINTERESTING;
480 add_pending_object(rev, &list->item->object,
481 oid_to_hex(&list->item->object.oid));
483 return prepare_revision_walk(rev);
486 static void print_submodule_diff_summary(struct repository *r, struct rev_info *rev, struct diff_options *o)
488 static const char format[] = " %m %s";
489 struct strbuf sb = STRBUF_INIT;
490 struct commit *commit;
492 while ((commit = get_revision(rev))) {
493 struct pretty_print_context ctx = {0};
494 ctx.date_mode = rev->date_mode;
495 ctx.output_encoding = get_log_output_encoding();
496 strbuf_setlen(&sb, 0);
497 repo_format_commit_message(r, commit, format, &sb,
498 &ctx);
499 strbuf_addch(&sb, '\n');
500 if (commit->object.flags & SYMMETRIC_LEFT)
501 diff_emit_submodule_del(o, sb.buf);
502 else
503 diff_emit_submodule_add(o, sb.buf);
505 strbuf_release(&sb);
508 void prepare_submodule_repo_env(struct strvec *out)
510 prepare_other_repo_env(out, DEFAULT_GIT_DIR_ENVIRONMENT);
513 static void prepare_submodule_repo_env_in_gitdir(struct strvec *out)
515 prepare_other_repo_env(out, ".");
519 * Initialize a repository struct for a submodule based on the provided 'path'.
521 * Returns the repository struct on success,
522 * NULL when the submodule is not present.
524 static struct repository *open_submodule(const char *path)
526 struct strbuf sb = STRBUF_INIT;
527 struct repository *out = xmalloc(sizeof(*out));
529 if (submodule_to_gitdir(&sb, path) || repo_init(out, sb.buf, NULL)) {
530 strbuf_release(&sb);
531 free(out);
532 return NULL;
535 /* Mark it as a submodule */
536 out->submodule_prefix = xstrdup(path);
538 strbuf_release(&sb);
539 return out;
543 * Helper function to display the submodule header line prior to the full
544 * summary output.
546 * If it can locate the submodule git directory it will create a repository
547 * handle for the submodule and lookup both the left and right commits and
548 * put them into the left and right pointers.
550 static void show_submodule_header(struct diff_options *o,
551 const char *path,
552 struct object_id *one, struct object_id *two,
553 unsigned dirty_submodule,
554 struct repository *sub,
555 struct commit **left, struct commit **right,
556 struct commit_list **merge_bases)
558 const char *message = NULL;
559 struct strbuf sb = STRBUF_INIT;
560 int fast_forward = 0, fast_backward = 0;
562 if (dirty_submodule & DIRTY_SUBMODULE_UNTRACKED)
563 diff_emit_submodule_untracked(o, path);
565 if (dirty_submodule & DIRTY_SUBMODULE_MODIFIED)
566 diff_emit_submodule_modified(o, path);
568 if (is_null_oid(one))
569 message = "(new submodule)";
570 else if (is_null_oid(two))
571 message = "(submodule deleted)";
573 if (!sub) {
574 if (!message)
575 message = "(commits not present)";
576 goto output_header;
580 * Attempt to lookup the commit references, and determine if this is
581 * a fast forward or fast backwards update.
583 *left = lookup_commit_reference(sub, one);
584 *right = lookup_commit_reference(sub, two);
587 * Warn about missing commits in the submodule project, but only if
588 * they aren't null.
590 if ((!is_null_oid(one) && !*left) ||
591 (!is_null_oid(two) && !*right))
592 message = "(commits not present)";
594 *merge_bases = repo_get_merge_bases(sub, *left, *right);
595 if (*merge_bases) {
596 if ((*merge_bases)->item == *left)
597 fast_forward = 1;
598 else if ((*merge_bases)->item == *right)
599 fast_backward = 1;
602 if (oideq(one, two)) {
603 strbuf_release(&sb);
604 return;
607 output_header:
608 strbuf_addf(&sb, "Submodule %s ", path);
609 strbuf_add_unique_abbrev(&sb, one, DEFAULT_ABBREV);
610 strbuf_addstr(&sb, (fast_backward || fast_forward) ? ".." : "...");
611 strbuf_add_unique_abbrev(&sb, two, DEFAULT_ABBREV);
612 if (message)
613 strbuf_addf(&sb, " %s\n", message);
614 else
615 strbuf_addf(&sb, "%s:\n", fast_backward ? " (rewind)" : "");
616 diff_emit_submodule_header(o, sb.buf);
618 strbuf_release(&sb);
621 void show_submodule_diff_summary(struct diff_options *o, const char *path,
622 struct object_id *one, struct object_id *two,
623 unsigned dirty_submodule)
625 struct rev_info rev = REV_INFO_INIT;
626 struct commit *left = NULL, *right = NULL;
627 struct commit_list *merge_bases = NULL;
628 struct repository *sub;
630 sub = open_submodule(path);
631 show_submodule_header(o, path, one, two, dirty_submodule,
632 sub, &left, &right, &merge_bases);
635 * If we don't have both a left and a right pointer, there is no
636 * reason to try and display a summary. The header line should contain
637 * all the information the user needs.
639 if (!left || !right || !sub)
640 goto out;
642 /* Treat revision walker failure the same as missing commits */
643 if (prepare_submodule_diff_summary(sub, &rev, path, left, right, merge_bases)) {
644 diff_emit_submodule_error(o, "(revision walker failed)\n");
645 goto out;
648 print_submodule_diff_summary(sub, &rev, o);
650 out:
651 free_commit_list(merge_bases);
652 release_revisions(&rev);
653 clear_commit_marks(left, ~0);
654 clear_commit_marks(right, ~0);
655 if (sub) {
656 repo_clear(sub);
657 free(sub);
661 void show_submodule_inline_diff(struct diff_options *o, const char *path,
662 struct object_id *one, struct object_id *two,
663 unsigned dirty_submodule)
665 const struct object_id *old_oid = the_hash_algo->empty_tree, *new_oid = the_hash_algo->empty_tree;
666 struct commit *left = NULL, *right = NULL;
667 struct commit_list *merge_bases = NULL;
668 struct child_process cp = CHILD_PROCESS_INIT;
669 struct strbuf sb = STRBUF_INIT;
670 struct repository *sub;
672 sub = open_submodule(path);
673 show_submodule_header(o, path, one, two, dirty_submodule,
674 sub, &left, &right, &merge_bases);
676 /* We need a valid left and right commit to display a difference */
677 if (!(left || is_null_oid(one)) ||
678 !(right || is_null_oid(two)))
679 goto done;
681 if (left)
682 old_oid = one;
683 if (right)
684 new_oid = two;
686 cp.git_cmd = 1;
687 cp.dir = path;
688 cp.out = -1;
689 cp.no_stdin = 1;
691 /* TODO: other options may need to be passed here. */
692 strvec_pushl(&cp.args, "diff", "--submodule=diff", NULL);
693 strvec_pushf(&cp.args, "--color=%s", want_color(o->use_color) ?
694 "always" : "never");
696 if (o->flags.reverse_diff) {
697 strvec_pushf(&cp.args, "--src-prefix=%s%s/",
698 o->b_prefix, path);
699 strvec_pushf(&cp.args, "--dst-prefix=%s%s/",
700 o->a_prefix, path);
701 } else {
702 strvec_pushf(&cp.args, "--src-prefix=%s%s/",
703 o->a_prefix, path);
704 strvec_pushf(&cp.args, "--dst-prefix=%s%s/",
705 o->b_prefix, path);
707 strvec_push(&cp.args, oid_to_hex(old_oid));
709 * If the submodule has modified content, we will diff against the
710 * work tree, under the assumption that the user has asked for the
711 * diff format and wishes to actually see all differences even if they
712 * haven't yet been committed to the submodule yet.
714 if (!(dirty_submodule & DIRTY_SUBMODULE_MODIFIED))
715 strvec_push(&cp.args, oid_to_hex(new_oid));
717 prepare_submodule_repo_env(&cp.env);
719 if (!is_directory(path)) {
720 /* fall back to absorbed git dir, if any */
721 if (!sub)
722 goto done;
723 cp.dir = sub->gitdir;
724 strvec_push(&cp.env, GIT_DIR_ENVIRONMENT "=.");
725 strvec_push(&cp.env, GIT_WORK_TREE_ENVIRONMENT "=.");
728 if (start_command(&cp)) {
729 diff_emit_submodule_error(o, "(diff failed)\n");
730 goto done;
733 while (strbuf_getwholeline_fd(&sb, cp.out, '\n') != EOF)
734 diff_emit_submodule_pipethrough(o, sb.buf, sb.len);
736 if (finish_command(&cp))
737 diff_emit_submodule_error(o, "(diff failed)\n");
739 done:
740 strbuf_release(&sb);
741 free_commit_list(merge_bases);
742 if (left)
743 clear_commit_marks(left, ~0);
744 if (right)
745 clear_commit_marks(right, ~0);
746 if (sub) {
747 repo_clear(sub);
748 free(sub);
752 int should_update_submodules(void)
754 return config_update_recurse_submodules == RECURSE_SUBMODULES_ON;
757 const struct submodule *submodule_from_ce(const struct cache_entry *ce)
759 if (!S_ISGITLINK(ce->ce_mode))
760 return NULL;
762 if (!should_update_submodules())
763 return NULL;
765 return submodule_from_path(the_repository, null_oid(), ce->name);
769 struct collect_changed_submodules_cb_data {
770 struct repository *repo;
771 struct string_list *changed;
772 const struct object_id *commit_oid;
776 * this would normally be two functions: default_name_from_path() and
777 * path_from_default_name(). Since the default name is the same as
778 * the submodule path we can get away with just one function which only
779 * checks whether there is a submodule in the working directory at that
780 * location.
782 static const char *default_name_or_path(const char *path_or_name)
784 int error_code;
786 if (!is_submodule_populated_gently(path_or_name, &error_code))
787 return NULL;
789 return path_or_name;
793 * Holds relevant information for a changed submodule. Used as the .util
794 * member of the changed submodule name string_list_item.
796 * (super_oid, path) allows the submodule config to be read from _some_
797 * .gitmodules file. We store this information the first time we find a
798 * superproject commit that points to the submodule, but this is
799 * arbitrary - we can choose any (super_oid, path) that matches the
800 * submodule's name.
802 * NEEDSWORK: Storing an arbitrary commit is undesirable because we can't
803 * guarantee that we're reading the commit that the user would expect. A better
804 * scheme would be to just fetch a submodule by its name. This requires two
805 * steps:
806 * - Create a function that behaves like repo_submodule_init(), but accepts a
807 * submodule name instead of treeish_name and path. This should be easy
808 * because repo_submodule_init() internally uses the submodule's name.
810 * - Replace most instances of 'struct submodule' (which is the .gitmodules
811 * config) with just the submodule name. This is OK because we expect
812 * submodule settings to be stored in .git/config (via "git submodule init"),
813 * not .gitmodules. This also lets us delete get_non_gitmodules_submodule(),
814 * which constructs a bogus 'struct submodule' for the sake of giving a
815 * placeholder name to a gitlink.
817 struct changed_submodule_data {
819 * The first superproject commit in the rev walk that points to
820 * the submodule.
822 const struct object_id *super_oid;
824 * Path to the submodule in the superproject commit referenced
825 * by 'super_oid'.
827 char *path;
828 /* The submodule commits that have changed in the rev walk. */
829 struct oid_array new_commits;
832 static void changed_submodule_data_clear(struct changed_submodule_data *cs_data)
834 oid_array_clear(&cs_data->new_commits);
835 free(cs_data->path);
838 static void collect_changed_submodules_cb(struct diff_queue_struct *q,
839 struct diff_options *options UNUSED,
840 void *data)
842 struct collect_changed_submodules_cb_data *me = data;
843 struct string_list *changed = me->changed;
844 const struct object_id *commit_oid = me->commit_oid;
845 int i;
847 for (i = 0; i < q->nr; i++) {
848 struct diff_filepair *p = q->queue[i];
849 const struct submodule *submodule;
850 const char *name;
851 struct string_list_item *item;
852 struct changed_submodule_data *cs_data;
854 if (!S_ISGITLINK(p->two->mode))
855 continue;
857 submodule = submodule_from_path(me->repo,
858 commit_oid, p->two->path);
859 if (submodule)
860 name = submodule->name;
861 else {
862 name = default_name_or_path(p->two->path);
863 /* make sure name does not collide with existing one */
864 if (name)
865 submodule = submodule_from_name(me->repo,
866 commit_oid, name);
867 if (submodule) {
868 warning(_("Submodule in commit %s at path: "
869 "'%s' collides with a submodule named "
870 "the same. Skipping it."),
871 oid_to_hex(commit_oid), p->two->path);
872 name = NULL;
876 if (!name)
877 continue;
879 item = string_list_insert(changed, name);
880 if (item->util)
881 cs_data = item->util;
882 else {
883 item->util = xcalloc(1, sizeof(struct changed_submodule_data));
884 cs_data = item->util;
885 cs_data->super_oid = commit_oid;
886 cs_data->path = xstrdup(p->two->path);
888 oid_array_append(&cs_data->new_commits, &p->two->oid);
893 * Collect the paths of submodules in 'changed' which have changed based on
894 * the revisions as specified in 'argv'. Each entry in 'changed' will also
895 * have a corresponding 'struct oid_array' (in the 'util' field) which lists
896 * what the submodule pointers were updated to during the change.
898 static void collect_changed_submodules(struct repository *r,
899 struct string_list *changed,
900 struct strvec *argv)
902 struct rev_info rev;
903 const struct commit *commit;
904 int save_warning;
905 struct setup_revision_opt s_r_opt = {
906 .assume_dashdash = 1,
909 save_warning = warn_on_object_refname_ambiguity;
910 warn_on_object_refname_ambiguity = 0;
911 repo_init_revisions(r, &rev, NULL);
912 setup_revisions(argv->nr, argv->v, &rev, &s_r_opt);
913 warn_on_object_refname_ambiguity = save_warning;
914 if (prepare_revision_walk(&rev))
915 die(_("revision walk setup failed"));
917 while ((commit = get_revision(&rev))) {
918 struct rev_info diff_rev;
919 struct collect_changed_submodules_cb_data data;
920 data.repo = r;
921 data.changed = changed;
922 data.commit_oid = &commit->object.oid;
924 repo_init_revisions(r, &diff_rev, NULL);
925 diff_rev.diffopt.output_format |= DIFF_FORMAT_CALLBACK;
926 diff_rev.diffopt.format_callback = collect_changed_submodules_cb;
927 diff_rev.diffopt.format_callback_data = &data;
928 diff_rev.dense_combined_merges = 1;
929 diff_tree_combined_merge(commit, &diff_rev);
930 release_revisions(&diff_rev);
933 reset_revision_walk();
934 release_revisions(&rev);
937 static void free_submodules_data(struct string_list *submodules)
939 struct string_list_item *item;
940 for_each_string_list_item(item, submodules)
941 changed_submodule_data_clear(item->util);
943 string_list_clear(submodules, 1);
946 static int has_remote(const char *refname UNUSED,
947 const struct object_id *oid UNUSED,
948 int flags UNUSED, void *cb_data UNUSED)
950 return 1;
953 static int append_oid_to_argv(const struct object_id *oid, void *data)
955 struct strvec *argv = data;
956 strvec_push(argv, oid_to_hex(oid));
957 return 0;
960 struct has_commit_data {
961 struct repository *repo;
962 int result;
963 const char *path;
964 const struct object_id *super_oid;
967 static int check_has_commit(const struct object_id *oid, void *data)
969 struct has_commit_data *cb = data;
970 struct repository subrepo;
971 enum object_type type;
973 if (repo_submodule_init(&subrepo, cb->repo, cb->path, cb->super_oid)) {
974 cb->result = 0;
975 /* subrepo failed to init, so don't clean it up. */
976 return 0;
979 type = oid_object_info(&subrepo, oid, NULL);
981 switch (type) {
982 case OBJ_COMMIT:
983 goto cleanup;
984 case OBJ_BAD:
986 * Object is missing or invalid. If invalid, an error message
987 * has already been printed.
989 cb->result = 0;
990 goto cleanup;
991 default:
992 die(_("submodule entry '%s' (%s) is a %s, not a commit"),
993 cb->path, oid_to_hex(oid), type_name(type));
995 cleanup:
996 repo_clear(&subrepo);
997 return 0;
1000 static int submodule_has_commits(struct repository *r,
1001 const char *path,
1002 const struct object_id *super_oid,
1003 struct oid_array *commits)
1005 struct has_commit_data has_commit = {
1006 .repo = r,
1007 .result = 1,
1008 .path = path,
1009 .super_oid = super_oid
1012 oid_array_for_each_unique(commits, check_has_commit, &has_commit);
1014 if (has_commit.result) {
1016 * Even if the submodule is checked out and the commit is
1017 * present, make sure it exists in the submodule's object store
1018 * and that it is reachable from a ref.
1020 struct child_process cp = CHILD_PROCESS_INIT;
1021 struct strbuf out = STRBUF_INIT;
1023 strvec_pushl(&cp.args, "rev-list", "-n", "1", NULL);
1024 oid_array_for_each_unique(commits, append_oid_to_argv, &cp.args);
1025 strvec_pushl(&cp.args, "--not", "--all", NULL);
1027 prepare_submodule_repo_env(&cp.env);
1028 cp.git_cmd = 1;
1029 cp.no_stdin = 1;
1030 cp.dir = path;
1032 if (capture_command(&cp, &out, GIT_MAX_HEXSZ + 1) || out.len)
1033 has_commit.result = 0;
1035 strbuf_release(&out);
1038 return has_commit.result;
1041 static int submodule_needs_pushing(struct repository *r,
1042 const char *path,
1043 struct oid_array *commits)
1045 if (!submodule_has_commits(r, path, null_oid(), commits))
1047 * NOTE: We do consider it safe to return "no" here. The
1048 * correct answer would be "We do not know" instead of
1049 * "No push needed", but it is quite hard to change
1050 * the submodule pointer without having the submodule
1051 * around. If a user did however change the submodules
1052 * without having the submodule around, this indicates
1053 * an expert who knows what they are doing or a
1054 * maintainer integrating work from other people. In
1055 * both cases it should be safe to skip this check.
1057 return 0;
1059 if (for_each_remote_ref_submodule(path, has_remote, NULL) > 0) {
1060 struct child_process cp = CHILD_PROCESS_INIT;
1061 struct strbuf buf = STRBUF_INIT;
1062 int needs_pushing = 0;
1064 strvec_push(&cp.args, "rev-list");
1065 oid_array_for_each_unique(commits, append_oid_to_argv, &cp.args);
1066 strvec_pushl(&cp.args, "--not", "--remotes", "-n", "1" , NULL);
1068 prepare_submodule_repo_env(&cp.env);
1069 cp.git_cmd = 1;
1070 cp.no_stdin = 1;
1071 cp.out = -1;
1072 cp.dir = path;
1073 if (start_command(&cp))
1074 die(_("Could not run 'git rev-list <commits> --not --remotes -n 1' command in submodule %s"),
1075 path);
1076 if (strbuf_read(&buf, cp.out, the_hash_algo->hexsz + 1))
1077 needs_pushing = 1;
1078 finish_command(&cp);
1079 close(cp.out);
1080 strbuf_release(&buf);
1081 return needs_pushing;
1084 return 0;
1087 int find_unpushed_submodules(struct repository *r,
1088 struct oid_array *commits,
1089 const char *remotes_name,
1090 struct string_list *needs_pushing)
1092 struct string_list submodules = STRING_LIST_INIT_DUP;
1093 struct string_list_item *name;
1094 struct strvec argv = STRVEC_INIT;
1096 /* argv.v[0] will be ignored by setup_revisions */
1097 strvec_push(&argv, "find_unpushed_submodules");
1098 oid_array_for_each_unique(commits, append_oid_to_argv, &argv);
1099 strvec_push(&argv, "--not");
1100 strvec_pushf(&argv, "--remotes=%s", remotes_name);
1102 collect_changed_submodules(r, &submodules, &argv);
1104 for_each_string_list_item(name, &submodules) {
1105 struct changed_submodule_data *cs_data = name->util;
1106 const struct submodule *submodule;
1107 const char *path = NULL;
1109 submodule = submodule_from_name(r, null_oid(), name->string);
1110 if (submodule)
1111 path = submodule->path;
1112 else
1113 path = default_name_or_path(name->string);
1115 if (!path)
1116 continue;
1118 if (submodule_needs_pushing(r, path, &cs_data->new_commits))
1119 string_list_insert(needs_pushing, path);
1122 free_submodules_data(&submodules);
1123 strvec_clear(&argv);
1125 return needs_pushing->nr;
1128 static int push_submodule(const char *path,
1129 const struct remote *remote,
1130 const struct refspec *rs,
1131 const struct string_list *push_options,
1132 int dry_run)
1134 if (for_each_remote_ref_submodule(path, has_remote, NULL) > 0) {
1135 struct child_process cp = CHILD_PROCESS_INIT;
1136 strvec_push(&cp.args, "push");
1138 * When recursing into a submodule, treat any "only" configurations as "on-
1139 * demand", since "only" would not work (we need all submodules to be pushed
1140 * in order to be able to push the superproject).
1142 strvec_push(&cp.args, "--recurse-submodules=only-is-on-demand");
1143 if (dry_run)
1144 strvec_push(&cp.args, "--dry-run");
1146 if (push_options && push_options->nr) {
1147 const struct string_list_item *item;
1148 for_each_string_list_item(item, push_options)
1149 strvec_pushf(&cp.args, "--push-option=%s",
1150 item->string);
1153 if (remote->origin != REMOTE_UNCONFIGURED) {
1154 int i;
1155 strvec_push(&cp.args, remote->name);
1156 for (i = 0; i < rs->raw_nr; i++)
1157 strvec_push(&cp.args, rs->raw[i]);
1160 prepare_submodule_repo_env(&cp.env);
1161 cp.git_cmd = 1;
1162 cp.no_stdin = 1;
1163 cp.dir = path;
1164 if (run_command(&cp))
1165 return 0;
1166 close(cp.out);
1169 return 1;
1173 * Perform a check in the submodule to see if the remote and refspec work.
1174 * Die if the submodule can't be pushed.
1176 static void submodule_push_check(const char *path, const char *head,
1177 const struct remote *remote,
1178 const struct refspec *rs)
1180 struct child_process cp = CHILD_PROCESS_INIT;
1181 int i;
1183 strvec_push(&cp.args, "submodule--helper");
1184 strvec_push(&cp.args, "push-check");
1185 strvec_push(&cp.args, head);
1186 strvec_push(&cp.args, remote->name);
1188 for (i = 0; i < rs->raw_nr; i++)
1189 strvec_push(&cp.args, rs->raw[i]);
1191 prepare_submodule_repo_env(&cp.env);
1192 cp.git_cmd = 1;
1193 cp.no_stdin = 1;
1194 cp.no_stdout = 1;
1195 cp.dir = path;
1198 * Simply indicate if 'submodule--helper push-check' failed.
1199 * More detailed error information will be provided by the
1200 * child process.
1202 if (run_command(&cp))
1203 die(_("process for submodule '%s' failed"), path);
1206 int push_unpushed_submodules(struct repository *r,
1207 struct oid_array *commits,
1208 const struct remote *remote,
1209 const struct refspec *rs,
1210 const struct string_list *push_options,
1211 int dry_run)
1213 int i, ret = 1;
1214 struct string_list needs_pushing = STRING_LIST_INIT_DUP;
1216 if (!find_unpushed_submodules(r, commits,
1217 remote->name, &needs_pushing))
1218 return 1;
1221 * Verify that the remote and refspec can be propagated to all
1222 * submodules. This check can be skipped if the remote and refspec
1223 * won't be propagated due to the remote being unconfigured (e.g. a URL
1224 * instead of a remote name).
1226 if (remote->origin != REMOTE_UNCONFIGURED) {
1227 char *head;
1228 struct object_id head_oid;
1230 head = resolve_refdup("HEAD", 0, &head_oid, NULL);
1231 if (!head)
1232 die(_("Failed to resolve HEAD as a valid ref."));
1234 for (i = 0; i < needs_pushing.nr; i++)
1235 submodule_push_check(needs_pushing.items[i].string,
1236 head, remote, rs);
1237 free(head);
1240 /* Actually push the submodules */
1241 for (i = 0; i < needs_pushing.nr; i++) {
1242 const char *path = needs_pushing.items[i].string;
1243 fprintf(stderr, _("Pushing submodule '%s'\n"), path);
1244 if (!push_submodule(path, remote, rs,
1245 push_options, dry_run)) {
1246 fprintf(stderr, _("Unable to push submodule '%s'\n"), path);
1247 ret = 0;
1251 string_list_clear(&needs_pushing, 0);
1253 return ret;
1256 static int append_oid_to_array(const char *ref UNUSED,
1257 const struct object_id *oid,
1258 int flags UNUSED, void *data)
1260 struct oid_array *array = data;
1261 oid_array_append(array, oid);
1262 return 0;
1265 void check_for_new_submodule_commits(struct object_id *oid)
1267 if (!initialized_fetch_ref_tips) {
1268 for_each_ref(append_oid_to_array, &ref_tips_before_fetch);
1269 initialized_fetch_ref_tips = 1;
1272 oid_array_append(&ref_tips_after_fetch, oid);
1276 * Returns 1 if there is at least one submodule gitdir in
1277 * $GIT_DIR/modules and 0 otherwise. This follows
1278 * submodule_name_to_gitdir(), which looks for submodules in
1279 * $GIT_DIR/modules, not $GIT_COMMON_DIR.
1281 * A submodule can be moved to $GIT_DIR/modules manually by running "git
1282 * submodule absorbgitdirs", or it may be initialized there by "git
1283 * submodule update".
1285 static int repo_has_absorbed_submodules(struct repository *r)
1287 int ret;
1288 struct strbuf buf = STRBUF_INIT;
1290 strbuf_repo_git_path(&buf, r, "modules/");
1291 ret = file_exists(buf.buf) && !is_empty_dir(buf.buf);
1292 strbuf_release(&buf);
1293 return ret;
1296 static void calculate_changed_submodule_paths(struct repository *r,
1297 struct string_list *changed_submodule_names)
1299 struct strvec argv = STRVEC_INIT;
1300 struct string_list_item *name;
1302 /* No need to check if no submodules would be fetched */
1303 if (!submodule_from_path(r, NULL, NULL) &&
1304 !repo_has_absorbed_submodules(r))
1305 return;
1307 strvec_push(&argv, "--"); /* argv[0] program name */
1308 oid_array_for_each_unique(&ref_tips_after_fetch,
1309 append_oid_to_argv, &argv);
1310 strvec_push(&argv, "--not");
1311 oid_array_for_each_unique(&ref_tips_before_fetch,
1312 append_oid_to_argv, &argv);
1315 * Collect all submodules (whether checked out or not) for which new
1316 * commits have been recorded upstream in "changed_submodule_names".
1318 collect_changed_submodules(r, changed_submodule_names, &argv);
1320 for_each_string_list_item(name, changed_submodule_names) {
1321 struct changed_submodule_data *cs_data = name->util;
1322 const struct submodule *submodule;
1323 const char *path = NULL;
1325 submodule = submodule_from_name(r, null_oid(), name->string);
1326 if (submodule)
1327 path = submodule->path;
1328 else
1329 path = default_name_or_path(name->string);
1331 if (!path)
1332 continue;
1334 if (submodule_has_commits(r, path, null_oid(), &cs_data->new_commits)) {
1335 changed_submodule_data_clear(cs_data);
1336 *name->string = '\0';
1340 string_list_remove_empty_items(changed_submodule_names, 1);
1342 strvec_clear(&argv);
1343 oid_array_clear(&ref_tips_before_fetch);
1344 oid_array_clear(&ref_tips_after_fetch);
1345 initialized_fetch_ref_tips = 0;
1348 int submodule_touches_in_range(struct repository *r,
1349 struct object_id *excl_oid,
1350 struct object_id *incl_oid)
1352 struct string_list subs = STRING_LIST_INIT_DUP;
1353 struct strvec args = STRVEC_INIT;
1354 int ret;
1356 /* No need to check if there are no submodules configured */
1357 if (!submodule_from_path(r, NULL, NULL))
1358 return 0;
1360 strvec_push(&args, "--"); /* args[0] program name */
1361 strvec_push(&args, oid_to_hex(incl_oid));
1362 if (!is_null_oid(excl_oid)) {
1363 strvec_push(&args, "--not");
1364 strvec_push(&args, oid_to_hex(excl_oid));
1367 collect_changed_submodules(r, &subs, &args);
1368 ret = subs.nr;
1370 strvec_clear(&args);
1372 free_submodules_data(&subs);
1373 return ret;
1376 struct submodule_parallel_fetch {
1378 * The index of the last index entry processed by
1379 * get_fetch_task_from_index().
1381 int index_count;
1383 * The index of the last string_list entry processed by
1384 * get_fetch_task_from_changed().
1386 int changed_count;
1387 struct strvec args;
1388 struct repository *r;
1389 const char *prefix;
1390 int command_line_option;
1391 int default_option;
1392 int quiet;
1393 int result;
1396 * Names of submodules that have new commits. Generated by
1397 * walking the newly fetched superproject commits.
1399 struct string_list changed_submodule_names;
1401 * Names of submodules that have already been processed. Lets us
1402 * avoid fetching the same submodule more than once.
1404 struct string_list seen_submodule_names;
1406 /* Pending fetches by OIDs */
1407 struct fetch_task **oid_fetch_tasks;
1408 int oid_fetch_tasks_nr, oid_fetch_tasks_alloc;
1410 struct strbuf submodules_with_errors;
1412 #define SPF_INIT { \
1413 .args = STRVEC_INIT, \
1414 .changed_submodule_names = STRING_LIST_INIT_DUP, \
1415 .seen_submodule_names = STRING_LIST_INIT_DUP, \
1416 .submodules_with_errors = STRBUF_INIT, \
1419 static int get_fetch_recurse_config(const struct submodule *submodule,
1420 struct submodule_parallel_fetch *spf)
1422 if (spf->command_line_option != RECURSE_SUBMODULES_DEFAULT)
1423 return spf->command_line_option;
1425 if (submodule) {
1426 char *key;
1427 const char *value;
1429 int fetch_recurse = submodule->fetch_recurse;
1430 key = xstrfmt("submodule.%s.fetchRecurseSubmodules", submodule->name);
1431 if (!repo_config_get_string_tmp(spf->r, key, &value)) {
1432 fetch_recurse = parse_fetch_recurse_submodules_arg(key, value);
1434 free(key);
1436 if (fetch_recurse != RECURSE_SUBMODULES_NONE)
1437 /* local config overrules everything except commandline */
1438 return fetch_recurse;
1441 return spf->default_option;
1445 * Fetch in progress (if callback data) or
1446 * pending (if in oid_fetch_tasks in struct submodule_parallel_fetch)
1448 struct fetch_task {
1449 struct repository *repo;
1450 const struct submodule *sub;
1451 unsigned free_sub : 1; /* Do we need to free the submodule? */
1452 const char *default_argv; /* The default fetch mode. */
1453 struct strvec git_args; /* Args for the child git process. */
1455 struct oid_array *commits; /* Ensure these commits are fetched */
1459 * When a submodule is not defined in .gitmodules, we cannot access it
1460 * via the regular submodule-config. Create a fake submodule, which we can
1461 * work on.
1463 static const struct submodule *get_non_gitmodules_submodule(const char *path)
1465 struct submodule *ret = NULL;
1466 const char *name = default_name_or_path(path);
1468 if (!name)
1469 return NULL;
1471 ret = xmalloc(sizeof(*ret));
1472 memset(ret, 0, sizeof(*ret));
1473 ret->path = name;
1474 ret->name = name;
1476 return (const struct submodule *) ret;
1479 static void fetch_task_release(struct fetch_task *p)
1481 if (p->free_sub)
1482 free((void*)p->sub);
1483 p->free_sub = 0;
1484 p->sub = NULL;
1486 if (p->repo)
1487 repo_clear(p->repo);
1488 FREE_AND_NULL(p->repo);
1490 strvec_clear(&p->git_args);
1493 static struct repository *get_submodule_repo_for(struct repository *r,
1494 const char *path,
1495 const struct object_id *treeish_name)
1497 struct repository *ret = xmalloc(sizeof(*ret));
1499 if (repo_submodule_init(ret, r, path, treeish_name)) {
1500 free(ret);
1501 return NULL;
1504 return ret;
1507 static struct fetch_task *fetch_task_create(struct submodule_parallel_fetch *spf,
1508 const char *path,
1509 const struct object_id *treeish_name)
1511 struct fetch_task *task = xmalloc(sizeof(*task));
1512 memset(task, 0, sizeof(*task));
1514 task->sub = submodule_from_path(spf->r, treeish_name, path);
1516 if (!task->sub) {
1518 * No entry in .gitmodules? Technically not a submodule,
1519 * but historically we supported repositories that happen to be
1520 * in-place where a gitlink is. Keep supporting them.
1522 task->sub = get_non_gitmodules_submodule(path);
1523 if (!task->sub)
1524 goto cleanup;
1526 task->free_sub = 1;
1529 if (string_list_lookup(&spf->seen_submodule_names, task->sub->name))
1530 goto cleanup;
1532 switch (get_fetch_recurse_config(task->sub, spf))
1534 default:
1535 case RECURSE_SUBMODULES_DEFAULT:
1536 case RECURSE_SUBMODULES_ON_DEMAND:
1537 if (!task->sub ||
1538 !string_list_lookup(
1539 &spf->changed_submodule_names,
1540 task->sub->name))
1541 goto cleanup;
1542 task->default_argv = "on-demand";
1543 break;
1544 case RECURSE_SUBMODULES_ON:
1545 task->default_argv = "yes";
1546 break;
1547 case RECURSE_SUBMODULES_OFF:
1548 goto cleanup;
1551 task->repo = get_submodule_repo_for(spf->r, path, treeish_name);
1553 return task;
1555 cleanup:
1556 fetch_task_release(task);
1557 free(task);
1558 return NULL;
1561 static struct fetch_task *
1562 get_fetch_task_from_index(struct submodule_parallel_fetch *spf,
1563 struct strbuf *err)
1565 for (; spf->index_count < spf->r->index->cache_nr; spf->index_count++) {
1566 const struct cache_entry *ce =
1567 spf->r->index->cache[spf->index_count];
1568 struct fetch_task *task;
1570 if (!S_ISGITLINK(ce->ce_mode))
1571 continue;
1573 task = fetch_task_create(spf, ce->name, null_oid());
1574 if (!task)
1575 continue;
1577 if (task->repo) {
1578 if (!spf->quiet)
1579 strbuf_addf(err, _("Fetching submodule %s%s\n"),
1580 spf->prefix, ce->name);
1582 spf->index_count++;
1583 return task;
1584 } else {
1585 struct strbuf empty_submodule_path = STRBUF_INIT;
1587 fetch_task_release(task);
1588 free(task);
1591 * An empty directory is normal,
1592 * the submodule is not initialized
1594 strbuf_addf(&empty_submodule_path, "%s/%s/",
1595 spf->r->worktree,
1596 ce->name);
1597 if (S_ISGITLINK(ce->ce_mode) &&
1598 !is_empty_dir(empty_submodule_path.buf)) {
1599 spf->result = 1;
1600 strbuf_addf(err,
1601 _("Could not access submodule '%s'\n"),
1602 ce->name);
1604 strbuf_release(&empty_submodule_path);
1607 return NULL;
1610 static struct fetch_task *
1611 get_fetch_task_from_changed(struct submodule_parallel_fetch *spf,
1612 struct strbuf *err)
1614 for (; spf->changed_count < spf->changed_submodule_names.nr;
1615 spf->changed_count++) {
1616 struct string_list_item item =
1617 spf->changed_submodule_names.items[spf->changed_count];
1618 struct changed_submodule_data *cs_data = item.util;
1619 struct fetch_task *task;
1621 if (!is_tree_submodule_active(spf->r, cs_data->super_oid,cs_data->path))
1622 continue;
1624 task = fetch_task_create(spf, cs_data->path,
1625 cs_data->super_oid);
1626 if (!task)
1627 continue;
1629 if (!task->repo) {
1630 strbuf_addf(err, _("Could not access submodule '%s' at commit %s\n"),
1631 cs_data->path,
1632 repo_find_unique_abbrev(the_repository, cs_data->super_oid, DEFAULT_ABBREV));
1634 fetch_task_release(task);
1635 free(task);
1636 continue;
1639 if (!spf->quiet)
1640 strbuf_addf(err,
1641 _("Fetching submodule %s%s at commit %s\n"),
1642 spf->prefix, task->sub->path,
1643 repo_find_unique_abbrev(the_repository, cs_data->super_oid,
1644 DEFAULT_ABBREV));
1646 spf->changed_count++;
1648 * NEEDSWORK: Submodules set/unset a value for
1649 * core.worktree when they are populated/unpopulated by
1650 * "git checkout" (and similar commands, see
1651 * submodule_move_head() and
1652 * connect_work_tree_and_git_dir()), but if the
1653 * submodule is unpopulated in another way (e.g. "git
1654 * rm", "rm -r"), core.worktree will still be set even
1655 * though the directory doesn't exist, and the child
1656 * process will crash while trying to chdir into the
1657 * nonexistent directory.
1659 * In this case, we know that the submodule has no
1660 * working tree, so we can work around this by
1661 * setting "--work-tree=." (--bare does not work because
1662 * worktree settings take precedence over bare-ness).
1663 * However, this is not necessarily true in other cases,
1664 * so a generalized solution is still necessary.
1666 * Possible solutions:
1667 * - teach "git [add|rm]" to unset core.worktree and
1668 * discourage users from removing submodules without
1669 * using a Git command.
1670 * - teach submodule child processes to ignore stale
1671 * core.worktree values.
1673 strvec_push(&task->git_args, "--work-tree=.");
1674 return task;
1676 return NULL;
1679 static int get_next_submodule(struct child_process *cp, struct strbuf *err,
1680 void *data, void **task_cb)
1682 struct submodule_parallel_fetch *spf = data;
1683 struct fetch_task *task =
1684 get_fetch_task_from_index(spf, err);
1685 if (!task)
1686 task = get_fetch_task_from_changed(spf, err);
1688 if (task) {
1689 struct strbuf submodule_prefix = STRBUF_INIT;
1691 child_process_init(cp);
1692 cp->dir = task->repo->gitdir;
1693 prepare_submodule_repo_env_in_gitdir(&cp->env);
1694 cp->git_cmd = 1;
1695 strvec_init(&cp->args);
1696 if (task->git_args.nr)
1697 strvec_pushv(&cp->args, task->git_args.v);
1698 strvec_pushv(&cp->args, spf->args.v);
1699 strvec_push(&cp->args, task->default_argv);
1700 strvec_push(&cp->args, "--submodule-prefix");
1702 strbuf_addf(&submodule_prefix, "%s%s/",
1703 spf->prefix,
1704 task->sub->path);
1705 strvec_push(&cp->args, submodule_prefix.buf);
1706 *task_cb = task;
1708 strbuf_release(&submodule_prefix);
1709 string_list_insert(&spf->seen_submodule_names, task->sub->name);
1710 return 1;
1713 if (spf->oid_fetch_tasks_nr) {
1714 struct fetch_task *task =
1715 spf->oid_fetch_tasks[spf->oid_fetch_tasks_nr - 1];
1716 struct strbuf submodule_prefix = STRBUF_INIT;
1717 spf->oid_fetch_tasks_nr--;
1719 strbuf_addf(&submodule_prefix, "%s%s/",
1720 spf->prefix, task->sub->path);
1722 child_process_init(cp);
1723 prepare_submodule_repo_env_in_gitdir(&cp->env);
1724 cp->git_cmd = 1;
1725 cp->dir = task->repo->gitdir;
1727 strvec_init(&cp->args);
1728 strvec_pushv(&cp->args, spf->args.v);
1729 strvec_push(&cp->args, "on-demand");
1730 strvec_push(&cp->args, "--submodule-prefix");
1731 strvec_push(&cp->args, submodule_prefix.buf);
1733 /* NEEDSWORK: have get_default_remote from submodule--helper */
1734 strvec_push(&cp->args, "origin");
1735 oid_array_for_each_unique(task->commits,
1736 append_oid_to_argv, &cp->args);
1738 *task_cb = task;
1739 strbuf_release(&submodule_prefix);
1740 return 1;
1743 return 0;
1746 static int fetch_start_failure(struct strbuf *err UNUSED,
1747 void *cb, void *task_cb)
1749 struct submodule_parallel_fetch *spf = cb;
1750 struct fetch_task *task = task_cb;
1752 spf->result = 1;
1754 fetch_task_release(task);
1755 return 0;
1758 static int commit_missing_in_sub(const struct object_id *oid, void *data)
1760 struct repository *subrepo = data;
1762 enum object_type type = oid_object_info(subrepo, oid, NULL);
1764 return type != OBJ_COMMIT;
1767 static int fetch_finish(int retvalue, struct strbuf *err UNUSED,
1768 void *cb, void *task_cb)
1770 struct submodule_parallel_fetch *spf = cb;
1771 struct fetch_task *task = task_cb;
1773 struct string_list_item *it;
1774 struct changed_submodule_data *cs_data;
1776 if (!task || !task->sub)
1777 BUG("callback cookie bogus");
1779 if (retvalue) {
1781 * NEEDSWORK: This indicates that the overall fetch
1782 * failed, even though there may be a subsequent fetch
1783 * by commit hash that might work. It may be a good
1784 * idea to not indicate failure in this case, and only
1785 * indicate failure if the subsequent fetch fails.
1787 spf->result = 1;
1789 strbuf_addf(&spf->submodules_with_errors, "\t%s\n",
1790 task->sub->name);
1793 /* Is this the second time we process this submodule? */
1794 if (task->commits)
1795 goto out;
1797 it = string_list_lookup(&spf->changed_submodule_names, task->sub->name);
1798 if (!it)
1799 /* Could be an unchanged submodule, not contained in the list */
1800 goto out;
1802 cs_data = it->util;
1803 oid_array_filter(&cs_data->new_commits,
1804 commit_missing_in_sub,
1805 task->repo);
1807 /* Are there commits we want, but do not exist? */
1808 if (cs_data->new_commits.nr) {
1809 task->commits = &cs_data->new_commits;
1810 ALLOC_GROW(spf->oid_fetch_tasks,
1811 spf->oid_fetch_tasks_nr + 1,
1812 spf->oid_fetch_tasks_alloc);
1813 spf->oid_fetch_tasks[spf->oid_fetch_tasks_nr] = task;
1814 spf->oid_fetch_tasks_nr++;
1815 return 0;
1818 out:
1819 fetch_task_release(task);
1821 return 0;
1824 int fetch_submodules(struct repository *r,
1825 const struct strvec *options,
1826 const char *prefix, int command_line_option,
1827 int default_option,
1828 int quiet, int max_parallel_jobs)
1830 int i;
1831 struct submodule_parallel_fetch spf = SPF_INIT;
1832 const struct run_process_parallel_opts opts = {
1833 .tr2_category = "submodule",
1834 .tr2_label = "parallel/fetch",
1836 .processes = max_parallel_jobs,
1838 .get_next_task = get_next_submodule,
1839 .start_failure = fetch_start_failure,
1840 .task_finished = fetch_finish,
1841 .data = &spf,
1844 spf.r = r;
1845 spf.command_line_option = command_line_option;
1846 spf.default_option = default_option;
1847 spf.quiet = quiet;
1848 spf.prefix = prefix;
1850 if (!r->worktree)
1851 goto out;
1853 if (repo_read_index(r) < 0)
1854 die(_("index file corrupt"));
1856 strvec_push(&spf.args, "fetch");
1857 for (i = 0; i < options->nr; i++)
1858 strvec_push(&spf.args, options->v[i]);
1859 strvec_push(&spf.args, "--recurse-submodules-default");
1860 /* default value, "--submodule-prefix" and its value are added later */
1862 calculate_changed_submodule_paths(r, &spf.changed_submodule_names);
1863 string_list_sort(&spf.changed_submodule_names);
1864 run_processes_parallel(&opts);
1866 if (spf.submodules_with_errors.len > 0)
1867 fprintf(stderr, _("Errors during submodule fetch:\n%s"),
1868 spf.submodules_with_errors.buf);
1871 strvec_clear(&spf.args);
1872 out:
1873 free_submodules_data(&spf.changed_submodule_names);
1874 return spf.result;
1877 unsigned is_submodule_modified(const char *path, int ignore_untracked)
1879 struct child_process cp = CHILD_PROCESS_INIT;
1880 struct strbuf buf = STRBUF_INIT;
1881 FILE *fp;
1882 unsigned dirty_submodule = 0;
1883 const char *git_dir;
1884 int ignore_cp_exit_code = 0;
1886 strbuf_addf(&buf, "%s/.git", path);
1887 git_dir = read_gitfile(buf.buf);
1888 if (!git_dir)
1889 git_dir = buf.buf;
1890 if (!is_git_directory(git_dir)) {
1891 if (is_directory(git_dir))
1892 die(_("'%s' not recognized as a git repository"), git_dir);
1893 strbuf_release(&buf);
1894 /* The submodule is not checked out, so it is not modified */
1895 return 0;
1897 strbuf_reset(&buf);
1899 strvec_pushl(&cp.args, "status", "--porcelain=2", NULL);
1900 if (ignore_untracked)
1901 strvec_push(&cp.args, "-uno");
1903 prepare_submodule_repo_env(&cp.env);
1904 cp.git_cmd = 1;
1905 cp.no_stdin = 1;
1906 cp.out = -1;
1907 cp.dir = path;
1908 if (start_command(&cp))
1909 die(_("Could not run 'git status --porcelain=2' in submodule %s"), path);
1911 fp = xfdopen(cp.out, "r");
1912 while (strbuf_getwholeline(&buf, fp, '\n') != EOF) {
1913 /* regular untracked files */
1914 if (buf.buf[0] == '?')
1915 dirty_submodule |= DIRTY_SUBMODULE_UNTRACKED;
1917 if (buf.buf[0] == 'u' ||
1918 buf.buf[0] == '1' ||
1919 buf.buf[0] == '2') {
1920 /* T = line type, XY = status, SSSS = submodule state */
1921 if (buf.len < strlen("T XY SSSS"))
1922 BUG("invalid status --porcelain=2 line %s",
1923 buf.buf);
1925 if (buf.buf[5] == 'S' && buf.buf[8] == 'U')
1926 /* nested untracked file */
1927 dirty_submodule |= DIRTY_SUBMODULE_UNTRACKED;
1929 if (buf.buf[0] == 'u' ||
1930 buf.buf[0] == '2' ||
1931 memcmp(buf.buf + 5, "S..U", 4))
1932 /* other change */
1933 dirty_submodule |= DIRTY_SUBMODULE_MODIFIED;
1936 if ((dirty_submodule & DIRTY_SUBMODULE_MODIFIED) &&
1937 ((dirty_submodule & DIRTY_SUBMODULE_UNTRACKED) ||
1938 ignore_untracked)) {
1940 * We're not interested in any further information from
1941 * the child any more, neither output nor its exit code.
1943 ignore_cp_exit_code = 1;
1944 break;
1947 fclose(fp);
1949 if (finish_command(&cp) && !ignore_cp_exit_code)
1950 die(_("'git status --porcelain=2' failed in submodule %s"), path);
1952 strbuf_release(&buf);
1953 return dirty_submodule;
1956 int submodule_uses_gitfile(const char *path)
1958 struct child_process cp = CHILD_PROCESS_INIT;
1959 struct strbuf buf = STRBUF_INIT;
1960 const char *git_dir;
1962 strbuf_addf(&buf, "%s/.git", path);
1963 git_dir = read_gitfile(buf.buf);
1964 if (!git_dir) {
1965 strbuf_release(&buf);
1966 return 0;
1968 strbuf_release(&buf);
1970 /* Now test that all nested submodules use a gitfile too */
1971 strvec_pushl(&cp.args,
1972 "submodule", "foreach", "--quiet", "--recursive",
1973 "test -f .git", NULL);
1975 prepare_submodule_repo_env(&cp.env);
1976 cp.git_cmd = 1;
1977 cp.no_stdin = 1;
1978 cp.no_stderr = 1;
1979 cp.no_stdout = 1;
1980 cp.dir = path;
1981 if (run_command(&cp))
1982 return 0;
1984 return 1;
1988 * Check if it is a bad idea to remove a submodule, i.e. if we'd lose data
1989 * when doing so.
1991 * Return 1 if we'd lose data, return 0 if the removal is fine,
1992 * and negative values for errors.
1994 int bad_to_remove_submodule(const char *path, unsigned flags)
1996 ssize_t len;
1997 struct child_process cp = CHILD_PROCESS_INIT;
1998 struct strbuf buf = STRBUF_INIT;
1999 int ret = 0;
2001 if (!file_exists(path) || is_empty_dir(path))
2002 return 0;
2004 if (!submodule_uses_gitfile(path))
2005 return 1;
2007 strvec_pushl(&cp.args, "status", "--porcelain",
2008 "--ignore-submodules=none", NULL);
2010 if (flags & SUBMODULE_REMOVAL_IGNORE_UNTRACKED)
2011 strvec_push(&cp.args, "-uno");
2012 else
2013 strvec_push(&cp.args, "-uall");
2015 if (!(flags & SUBMODULE_REMOVAL_IGNORE_IGNORED_UNTRACKED))
2016 strvec_push(&cp.args, "--ignored");
2018 prepare_submodule_repo_env(&cp.env);
2019 cp.git_cmd = 1;
2020 cp.no_stdin = 1;
2021 cp.out = -1;
2022 cp.dir = path;
2023 if (start_command(&cp)) {
2024 if (flags & SUBMODULE_REMOVAL_DIE_ON_ERROR)
2025 die(_("could not start 'git status' in submodule '%s'"),
2026 path);
2027 ret = -1;
2028 goto out;
2031 len = strbuf_read(&buf, cp.out, 1024);
2032 if (len > 2)
2033 ret = 1;
2034 close(cp.out);
2036 if (finish_command(&cp)) {
2037 if (flags & SUBMODULE_REMOVAL_DIE_ON_ERROR)
2038 die(_("could not run 'git status' in submodule '%s'"),
2039 path);
2040 ret = -1;
2042 out:
2043 strbuf_release(&buf);
2044 return ret;
2047 void submodule_unset_core_worktree(const struct submodule *sub)
2049 struct strbuf config_path = STRBUF_INIT;
2051 submodule_name_to_gitdir(&config_path, the_repository, sub->name);
2052 strbuf_addstr(&config_path, "/config");
2054 if (git_config_set_in_file_gently(config_path.buf, "core.worktree", NULL))
2055 warning(_("Could not unset core.worktree setting in submodule '%s'"),
2056 sub->path);
2058 strbuf_release(&config_path);
2061 static int submodule_has_dirty_index(const struct submodule *sub)
2063 struct child_process cp = CHILD_PROCESS_INIT;
2065 prepare_submodule_repo_env(&cp.env);
2067 cp.git_cmd = 1;
2068 strvec_pushl(&cp.args, "diff-index", "--quiet",
2069 "--cached", "HEAD", NULL);
2070 cp.no_stdin = 1;
2071 cp.no_stdout = 1;
2072 cp.dir = sub->path;
2073 if (start_command(&cp))
2074 die(_("could not recurse into submodule '%s'"), sub->path);
2076 return finish_command(&cp);
2079 static void submodule_reset_index(const char *path, const char *super_prefix)
2081 struct child_process cp = CHILD_PROCESS_INIT;
2082 prepare_submodule_repo_env(&cp.env);
2084 cp.git_cmd = 1;
2085 cp.no_stdin = 1;
2086 cp.dir = path;
2088 /* TODO: determine if this might overwright untracked files */
2089 strvec_pushl(&cp.args, "read-tree", "-u", "--reset", NULL);
2090 strvec_pushf(&cp.args, "--super-prefix=%s%s/",
2091 (super_prefix ? super_prefix : ""), path);
2093 strvec_push(&cp.args, empty_tree_oid_hex());
2095 if (run_command(&cp))
2096 die(_("could not reset submodule index"));
2100 * Moves a submodule at a given path from a given head to another new head.
2101 * For edge cases (a submodule coming into existence or removing a submodule)
2102 * pass NULL for old or new respectively.
2104 int submodule_move_head(const char *path, const char *super_prefix,
2105 const char *old_head, const char *new_head,
2106 unsigned flags)
2108 int ret = 0;
2109 struct child_process cp = CHILD_PROCESS_INIT;
2110 const struct submodule *sub;
2111 int *error_code_ptr, error_code;
2113 if (!is_submodule_active(the_repository, path))
2114 return 0;
2116 if (flags & SUBMODULE_MOVE_HEAD_FORCE)
2118 * Pass non NULL pointer to is_submodule_populated_gently
2119 * to prevent die()-ing. We'll use connect_work_tree_and_git_dir
2120 * to fixup the submodule in the force case later.
2122 error_code_ptr = &error_code;
2123 else
2124 error_code_ptr = NULL;
2126 if (old_head && !is_submodule_populated_gently(path, error_code_ptr))
2127 return 0;
2129 sub = submodule_from_path(the_repository, null_oid(), path);
2131 if (!sub)
2132 BUG("could not get submodule information for '%s'", path);
2134 if (old_head && !(flags & SUBMODULE_MOVE_HEAD_FORCE)) {
2135 /* Check if the submodule has a dirty index. */
2136 if (submodule_has_dirty_index(sub))
2137 return error(_("submodule '%s' has dirty index"), path);
2140 if (!(flags & SUBMODULE_MOVE_HEAD_DRY_RUN)) {
2141 if (old_head) {
2142 if (!submodule_uses_gitfile(path))
2143 absorb_git_dir_into_superproject(path,
2144 super_prefix);
2145 } else {
2146 struct strbuf gitdir = STRBUF_INIT;
2147 submodule_name_to_gitdir(&gitdir, the_repository,
2148 sub->name);
2149 connect_work_tree_and_git_dir(path, gitdir.buf, 0);
2150 strbuf_release(&gitdir);
2152 /* make sure the index is clean as well */
2153 submodule_reset_index(path, super_prefix);
2156 if (old_head && (flags & SUBMODULE_MOVE_HEAD_FORCE)) {
2157 struct strbuf gitdir = STRBUF_INIT;
2158 submodule_name_to_gitdir(&gitdir, the_repository,
2159 sub->name);
2160 connect_work_tree_and_git_dir(path, gitdir.buf, 1);
2161 strbuf_release(&gitdir);
2165 prepare_submodule_repo_env(&cp.env);
2167 cp.git_cmd = 1;
2168 cp.no_stdin = 1;
2169 cp.dir = path;
2171 strvec_pushl(&cp.args, "read-tree", "--recurse-submodules", NULL);
2172 strvec_pushf(&cp.args, "--super-prefix=%s%s/",
2173 (super_prefix ? super_prefix : ""), path);
2175 if (flags & SUBMODULE_MOVE_HEAD_DRY_RUN)
2176 strvec_push(&cp.args, "-n");
2177 else
2178 strvec_push(&cp.args, "-u");
2180 if (flags & SUBMODULE_MOVE_HEAD_FORCE)
2181 strvec_push(&cp.args, "--reset");
2182 else
2183 strvec_push(&cp.args, "-m");
2185 if (!(flags & SUBMODULE_MOVE_HEAD_FORCE))
2186 strvec_push(&cp.args, old_head ? old_head : empty_tree_oid_hex());
2188 strvec_push(&cp.args, new_head ? new_head : empty_tree_oid_hex());
2190 if (run_command(&cp)) {
2191 ret = error(_("Submodule '%s' could not be updated."), path);
2192 goto out;
2195 if (!(flags & SUBMODULE_MOVE_HEAD_DRY_RUN)) {
2196 if (new_head) {
2197 child_process_init(&cp);
2198 /* also set the HEAD accordingly */
2199 cp.git_cmd = 1;
2200 cp.no_stdin = 1;
2201 cp.dir = path;
2203 prepare_submodule_repo_env(&cp.env);
2204 strvec_pushl(&cp.args, "update-ref", "HEAD",
2205 "--no-deref", new_head, NULL);
2207 if (run_command(&cp)) {
2208 ret = -1;
2209 goto out;
2211 } else {
2212 struct strbuf sb = STRBUF_INIT;
2214 strbuf_addf(&sb, "%s/.git", path);
2215 unlink_or_warn(sb.buf);
2216 strbuf_release(&sb);
2218 if (is_empty_dir(path))
2219 rmdir_or_warn(path);
2221 submodule_unset_core_worktree(sub);
2224 out:
2225 return ret;
2228 int validate_submodule_git_dir(char *git_dir, const char *submodule_name)
2230 size_t len = strlen(git_dir), suffix_len = strlen(submodule_name);
2231 char *p;
2232 int ret = 0;
2234 if (len <= suffix_len || (p = git_dir + len - suffix_len)[-1] != '/' ||
2235 strcmp(p, submodule_name))
2236 BUG("submodule name '%s' not a suffix of git dir '%s'",
2237 submodule_name, git_dir);
2240 * We prevent the contents of sibling submodules' git directories to
2241 * clash.
2243 * Example: having a submodule named `hippo` and another one named
2244 * `hippo/hooks` would result in the git directories
2245 * `.git/modules/hippo/` and `.git/modules/hippo/hooks/`, respectively,
2246 * but the latter directory is already designated to contain the hooks
2247 * of the former.
2249 for (; *p; p++) {
2250 if (is_dir_sep(*p)) {
2251 char c = *p;
2253 *p = '\0';
2254 if (is_git_directory(git_dir))
2255 ret = -1;
2256 *p = c;
2258 if (ret < 0)
2259 return error(_("submodule git dir '%s' is "
2260 "inside git dir '%.*s'"),
2261 git_dir,
2262 (int)(p - git_dir), git_dir);
2266 return 0;
2270 * Embeds a single submodules git directory into the superprojects git dir,
2271 * non recursively.
2273 static void relocate_single_git_dir_into_superproject(const char *path,
2274 const char *super_prefix)
2276 char *old_git_dir = NULL, *real_old_git_dir = NULL, *real_new_git_dir = NULL;
2277 struct strbuf new_gitdir = STRBUF_INIT;
2278 const struct submodule *sub;
2280 if (submodule_uses_worktrees(path))
2281 die(_("relocate_gitdir for submodule '%s' with "
2282 "more than one worktree not supported"), path);
2284 old_git_dir = xstrfmt("%s/.git", path);
2285 if (read_gitfile(old_git_dir))
2286 /* If it is an actual gitfile, it doesn't need migration. */
2287 return;
2289 real_old_git_dir = real_pathdup(old_git_dir, 1);
2291 sub = submodule_from_path(the_repository, null_oid(), path);
2292 if (!sub)
2293 die(_("could not lookup name for submodule '%s'"), path);
2295 submodule_name_to_gitdir(&new_gitdir, the_repository, sub->name);
2296 if (validate_submodule_git_dir(new_gitdir.buf, sub->name) < 0)
2297 die(_("refusing to move '%s' into an existing git dir"),
2298 real_old_git_dir);
2299 if (safe_create_leading_directories_const(new_gitdir.buf) < 0)
2300 die(_("could not create directory '%s'"), new_gitdir.buf);
2301 real_new_git_dir = real_pathdup(new_gitdir.buf, 1);
2303 fprintf(stderr, _("Migrating git directory of '%s%s' from\n'%s' to\n'%s'\n"),
2304 super_prefix ? super_prefix : "", path,
2305 real_old_git_dir, real_new_git_dir);
2307 relocate_gitdir(path, real_old_git_dir, real_new_git_dir);
2309 free(old_git_dir);
2310 free(real_old_git_dir);
2311 free(real_new_git_dir);
2312 strbuf_release(&new_gitdir);
2315 static void absorb_git_dir_into_superproject_recurse(const char *path,
2316 const char *super_prefix)
2319 struct child_process cp = CHILD_PROCESS_INIT;
2321 cp.dir = path;
2322 cp.git_cmd = 1;
2323 cp.no_stdin = 1;
2324 strvec_pushl(&cp.args, "submodule--helper",
2325 "absorbgitdirs", NULL);
2326 strvec_pushf(&cp.args, "--super-prefix=%s%s/", super_prefix ?
2327 super_prefix : "", path);
2329 prepare_submodule_repo_env(&cp.env);
2330 if (run_command(&cp))
2331 die(_("could not recurse into submodule '%s'"), path);
2335 * Migrate the git directory of the submodule given by path from
2336 * having its git directory within the working tree to the git dir nested
2337 * in its superprojects git dir under modules/.
2339 void absorb_git_dir_into_superproject(const char *path,
2340 const char *super_prefix)
2342 int err_code;
2343 const char *sub_git_dir;
2344 struct strbuf gitdir = STRBUF_INIT;
2345 strbuf_addf(&gitdir, "%s/.git", path);
2346 sub_git_dir = resolve_gitdir_gently(gitdir.buf, &err_code);
2348 /* Not populated? */
2349 if (!sub_git_dir) {
2350 const struct submodule *sub;
2351 struct strbuf sub_gitdir = STRBUF_INIT;
2353 if (err_code == READ_GITFILE_ERR_STAT_FAILED) {
2354 /* unpopulated as expected */
2355 strbuf_release(&gitdir);
2356 return;
2359 if (err_code != READ_GITFILE_ERR_NOT_A_REPO)
2360 /* We don't know what broke here. */
2361 read_gitfile_error_die(err_code, path, NULL);
2364 * Maybe populated, but no git directory was found?
2365 * This can happen if the superproject is a submodule
2366 * itself and was just absorbed. The absorption of the
2367 * superproject did not rewrite the git file links yet,
2368 * fix it now.
2370 sub = submodule_from_path(the_repository, null_oid(), path);
2371 if (!sub)
2372 die(_("could not lookup name for submodule '%s'"), path);
2373 submodule_name_to_gitdir(&sub_gitdir, the_repository, sub->name);
2374 connect_work_tree_and_git_dir(path, sub_gitdir.buf, 0);
2375 strbuf_release(&sub_gitdir);
2376 } else {
2377 /* Is it already absorbed into the superprojects git dir? */
2378 char *real_sub_git_dir = real_pathdup(sub_git_dir, 1);
2379 char *real_common_git_dir = real_pathdup(get_git_common_dir(), 1);
2381 if (!starts_with(real_sub_git_dir, real_common_git_dir))
2382 relocate_single_git_dir_into_superproject(path, super_prefix);
2384 free(real_sub_git_dir);
2385 free(real_common_git_dir);
2387 strbuf_release(&gitdir);
2389 absorb_git_dir_into_superproject_recurse(path, super_prefix);
2392 int get_superproject_working_tree(struct strbuf *buf)
2394 struct child_process cp = CHILD_PROCESS_INIT;
2395 struct strbuf sb = STRBUF_INIT;
2396 struct strbuf one_up = STRBUF_INIT;
2397 char *cwd = xgetcwd();
2398 int ret = 0;
2399 const char *subpath;
2400 int code;
2401 ssize_t len;
2403 if (!is_inside_work_tree())
2405 * FIXME:
2406 * We might have a superproject, but it is harder
2407 * to determine.
2409 return 0;
2411 if (!strbuf_realpath(&one_up, "../", 0))
2412 return 0;
2414 subpath = relative_path(cwd, one_up.buf, &sb);
2415 strbuf_release(&one_up);
2417 prepare_submodule_repo_env(&cp.env);
2418 strvec_pop(&cp.env);
2420 strvec_pushl(&cp.args, "--literal-pathspecs", "-C", "..",
2421 "ls-files", "-z", "--stage", "--full-name", "--",
2422 subpath, NULL);
2423 strbuf_reset(&sb);
2425 cp.no_stdin = 1;
2426 cp.no_stderr = 1;
2427 cp.out = -1;
2428 cp.git_cmd = 1;
2430 if (start_command(&cp))
2431 die(_("could not start ls-files in .."));
2433 len = strbuf_read(&sb, cp.out, PATH_MAX);
2434 close(cp.out);
2436 if (starts_with(sb.buf, "160000")) {
2437 int super_sub_len;
2438 int cwd_len = strlen(cwd);
2439 char *super_sub, *super_wt;
2442 * There is a superproject having this repo as a submodule.
2443 * The format is <mode> SP <hash> SP <stage> TAB <full name> \0,
2444 * We're only interested in the name after the tab.
2446 super_sub = strchr(sb.buf, '\t') + 1;
2447 super_sub_len = strlen(super_sub);
2449 if (super_sub_len > cwd_len ||
2450 strcmp(&cwd[cwd_len - super_sub_len], super_sub))
2451 BUG("returned path string doesn't match cwd?");
2453 super_wt = xstrdup(cwd);
2454 super_wt[cwd_len - super_sub_len] = '\0';
2456 strbuf_realpath(buf, super_wt, 1);
2457 ret = 1;
2458 free(super_wt);
2460 free(cwd);
2461 strbuf_release(&sb);
2463 code = finish_command(&cp);
2465 if (code == 128)
2466 /* '../' is not a git repository */
2467 return 0;
2468 if (code == 0 && len == 0)
2469 /* There is an unrelated git repository at '../' */
2470 return 0;
2471 if (code)
2472 die(_("ls-tree returned unexpected return code %d"), code);
2474 return ret;
2478 * Put the gitdir for a submodule (given relative to the main
2479 * repository worktree) into `buf`, or return -1 on error.
2481 int submodule_to_gitdir(struct strbuf *buf, const char *submodule)
2483 const struct submodule *sub;
2484 const char *git_dir;
2485 int ret = 0;
2487 strbuf_reset(buf);
2488 strbuf_addstr(buf, submodule);
2489 strbuf_complete(buf, '/');
2490 strbuf_addstr(buf, ".git");
2492 git_dir = read_gitfile(buf->buf);
2493 if (git_dir) {
2494 strbuf_reset(buf);
2495 strbuf_addstr(buf, git_dir);
2497 if (!is_git_directory(buf->buf)) {
2498 sub = submodule_from_path(the_repository, null_oid(),
2499 submodule);
2500 if (!sub) {
2501 ret = -1;
2502 goto cleanup;
2504 strbuf_reset(buf);
2505 submodule_name_to_gitdir(buf, the_repository, sub->name);
2508 cleanup:
2509 return ret;
2512 void submodule_name_to_gitdir(struct strbuf *buf, struct repository *r,
2513 const char *submodule_name)
2516 * NEEDSWORK: The current way of mapping a submodule's name to
2517 * its location in .git/modules/ has problems with some naming
2518 * schemes. For example, if a submodule is named "foo" and
2519 * another is named "foo/bar" (whether present in the same
2520 * superproject commit or not - the problem will arise if both
2521 * superproject commits have been checked out at any point in
2522 * time), or if two submodule names only have different cases in
2523 * a case-insensitive filesystem.
2525 * There are several solutions, including encoding the path in
2526 * some way, introducing a submodule.<name>.gitdir config in
2527 * .git/config (not .gitmodules) that allows overriding what the
2528 * gitdir of a submodule would be (and teach Git, upon noticing
2529 * a clash, to automatically determine a non-clashing name and
2530 * to write such a config), or introducing a
2531 * submodule.<name>.gitdir config in .gitmodules that repo
2532 * administrators can explicitly set. Nothing has been decided,
2533 * so for now, just append the name at the end of the path.
2535 strbuf_repo_git_path(buf, r, "modules/");
2536 strbuf_addstr(buf, submodule_name);